Moodle release 3.4rc2
[moodle.git] / lib / deprecatedlib.php
blob33e039816e096f9ecf6b0600aebf850df736db84
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 * Print a bold message in an optional color.
844 * @deprecated since Moodle 2.0 MDL-19077 - use $OUTPUT->notification instead.
845 * @todo MDL-50469 This will be deleted in Moodle 3.3.
846 * @param string $message The message to print out
847 * @param string $classes Optional style to display message text in
848 * @param string $align Alignment option
849 * @param bool $return whether to return an output string or echo now
850 * @return string|bool Depending on $result
852 function notify($message, $classes = 'error', $align = 'center', $return = false) {
853 global $OUTPUT;
855 debugging('notify() is deprecated, please use $OUTPUT->notification() instead', DEBUG_DEVELOPER);
857 if ($classes == 'green') {
858 debugging('Use of deprecated class name "green" in notify. Please change to "success".', DEBUG_DEVELOPER);
859 $classes = 'success'; // Backward compatible with old color system.
862 $output = $OUTPUT->notification($message, $classes);
863 if ($return) {
864 return $output;
865 } else {
866 echo $output;
871 * @deprecated use $OUTPUT->continue_button() instead.
873 function print_continue($link, $return = false) {
874 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
878 * @deprecated use $PAGE methods instead.
880 function print_header($title='', $heading='', $navigation='', $focus='',
881 $meta='', $cache=true, $button='&nbsp;', $menu=null,
882 $usexml=false, $bodytags='', $return=false) {
884 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
888 * @deprecated use $PAGE methods instead.
890 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
891 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
893 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
897 * @deprecated use $OUTPUT->block() instead.
899 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
900 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
904 * Prints a basic textarea field.
906 * @deprecated since Moodle 2.0
908 * When using this function, you should
910 * @global object
911 * @param bool $unused No longer used.
912 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
913 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
914 * @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.
915 * @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.
916 * @param string $name Name to use for the textarea element.
917 * @param string $value Initial content to display in the textarea.
918 * @param int $obsolete deprecated
919 * @param bool $return If false, will output string. If true, will return string value.
920 * @param string $id CSS ID to add to the textarea element.
921 * @return string|void depending on the value of $return
923 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
924 /// $width and height are legacy fields and no longer used as pixels like they used to be.
925 /// However, you can set them to zero to override the mincols and minrows values below.
927 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
928 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
930 global $CFG;
932 $mincols = 65;
933 $minrows = 10;
934 $str = '';
936 if ($id === '') {
937 $id = 'edit-'.$name;
940 if ($height && ($rows < $minrows)) {
941 $rows = $minrows;
943 if ($width && ($cols < $mincols)) {
944 $cols = $mincols;
947 editors_head_setup();
948 $editor = editors_get_preferred_editor(FORMAT_HTML);
949 $editor->set_text($value);
950 $editor->use_editor($id, array('legacy'=>true));
952 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
953 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
954 $str .= '</textarea>'."\n";
956 if ($return) {
957 return $str;
959 echo $str;
963 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
964 * provide this function with the language strings for sortasc and sortdesc.
966 * @deprecated use $OUTPUT->arrow() instead.
967 * @todo final deprecation of this function once MDL-45448 is resolved
969 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
971 * @global object
972 * @param string $direction 'up' or 'down'
973 * @param string $strsort The language string used for the alt attribute of this image
974 * @param bool $return Whether to print directly or return the html string
975 * @return string|void depending on $return
978 function print_arrow($direction='up', $strsort=null, $return=false) {
979 global $OUTPUT;
981 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
983 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
984 return null;
987 $return = null;
989 switch ($direction) {
990 case 'up':
991 $sortdir = 'asc';
992 break;
993 case 'down':
994 $sortdir = 'desc';
995 break;
996 case 'move':
997 $sortdir = 'asc';
998 break;
999 default:
1000 $sortdir = null;
1001 break;
1004 // Prepare language string
1005 $strsort = '';
1006 if (empty($strsort) && !empty($sortdir)) {
1007 $strsort = get_string('sort' . $sortdir, 'grades');
1010 $return = ' ' . $OUTPUT->pix_icon('t/' . $direction, $strsort) . ' ';
1012 if ($return) {
1013 return $return;
1014 } else {
1015 echo $return;
1020 * @deprecated since Moodle 2.0
1022 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1023 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1024 $id='', $listbox=false, $multiple=false, $class='') {
1025 throw new coding_exception('choose_from_menu() is removed. Please change your code to use html_writer::select().');
1030 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1032 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1033 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1034 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1038 * @deprecated use html_writer::checkbox() instead.
1040 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1041 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1045 * Prints the 'update this xxx' button that appears on module pages.
1047 * @deprecated since Moodle 3.2
1049 * @param string $cmid the course_module id.
1050 * @param string $ignored not used any more. (Used to be courseid.)
1051 * @param string $string the module name - get_string('modulename', 'xxx')
1052 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1054 function update_module_button($cmid, $ignored, $string) {
1055 global $CFG, $OUTPUT;
1057 debugging('update_module_button() has been deprecated and should not be used anymore. Activity modules should not add the ' .
1058 'edit module button, the link is already available in the Administration block. Themes can choose to display the link ' .
1059 'in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
1061 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1062 $string = get_string('updatethis', '', $string);
1064 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1065 return $OUTPUT->single_button($url, $string);
1066 } else {
1067 return '';
1072 * @deprecated use $OUTPUT->navbar() instead
1074 function print_navigation ($navigation, $separator=0, $return=false) {
1075 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1079 * @deprecated Please use $PAGE->navabar methods instead.
1081 function build_navigation($extranavlinks, $cm = null) {
1082 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1086 * @deprecated not relevant with global navigation in Moodle 2.x+
1088 function navmenu($course, $cm=NULL, $targetwindow='self') {
1089 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1092 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1096 * @deprecated please use calendar_event::create() instead.
1098 function add_event($event) {
1099 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1103 * @deprecated please calendar_event->update() instead.
1105 function update_event($event) {
1106 throw new coding_exception('update_event() is removed, please use calendar_event->update() instead.');
1110 * @deprecated please use calendar_event->delete() instead.
1112 function delete_event($id) {
1113 throw new coding_exception('delete_event() can not be used any more, please use '.
1114 'calendar_event->delete() instead.');
1118 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1120 function hide_event($event) {
1121 throw new coding_exception('hide_event() can not be used any more, please use '.
1122 'calendar_event->toggle_visibility(false) instead.');
1126 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1128 function show_event($event) {
1129 throw new coding_exception('show_event() can not be used any more, please use '.
1130 'calendar_event->toggle_visibility(true) instead.');
1134 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1135 * @see core_text
1137 function textlib_get_instance() {
1138 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1139 'core_text::functioname() instead.');
1143 * @deprecated since 2.4
1144 * @see get_section_name()
1145 * @see format_base::get_section_name()
1148 function get_generic_section_name($format, stdClass $section) {
1149 throw new coding_exception('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base');
1153 * Returns an array of sections for the requested course id
1155 * It is usually not recommended to display the list of sections used
1156 * in course because the course format may have it's own way to do it.
1158 * If you need to just display the name of the section please call:
1159 * get_section_name($course, $section)
1160 * {@link get_section_name()}
1161 * from 2.4 $section may also be just the field course_sections.section
1163 * If you need the list of all sections it is more efficient to get this data by calling
1164 * $modinfo = get_fast_modinfo($courseorid);
1165 * $sections = $modinfo->get_section_info_all()
1166 * {@link get_fast_modinfo()}
1167 * {@link course_modinfo::get_section_info_all()}
1169 * Information about one section (instance of section_info):
1170 * get_fast_modinfo($courseorid)->get_sections_info($section)
1171 * {@link course_modinfo::get_section_info()}
1173 * @deprecated since 2.4
1175 function get_all_sections($courseid) {
1177 throw new coding_exception('get_all_sections() is removed. See phpdocs for this function');
1181 * This function is deprecated, please use {@link course_add_cm_to_section()}
1182 * Note that course_add_cm_to_section() also updates field course_modules.section and
1183 * calls rebuild_course_cache()
1185 * @deprecated since 2.4
1187 function add_mod_to_section($mod, $beforemod = null) {
1188 throw new coding_exception('Function add_mod_to_section() is removed, please use course_add_cm_to_section()');
1192 * Returns a number of useful structures for course displays
1194 * Function get_all_mods() is deprecated in 2.4
1195 * Instead of:
1196 * <code>
1197 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1198 * </code>
1199 * please use:
1200 * <code>
1201 * $mods = get_fast_modinfo($courseorid)->get_cms();
1202 * $modnames = get_module_types_names();
1203 * $modnamesplural = get_module_types_names(true);
1204 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1205 * </code>
1207 * @deprecated since 2.4
1209 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1210 throw new coding_exception('Function get_all_mods() is removed. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details');
1214 * Returns course section - creates new if does not exist yet
1216 * This function is deprecated. To create a course section call:
1217 * course_create_sections_if_missing($courseorid, $sections);
1218 * to get the section call:
1219 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1221 * @see course_create_sections_if_missing()
1222 * @see get_fast_modinfo()
1223 * @deprecated since 2.4
1225 function get_course_section($section, $courseid) {
1226 throw new coding_exception('Function get_course_section() is removed. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.');
1230 * @deprecated since 2.4
1231 * @see format_weeks::get_section_dates()
1233 function format_weeks_get_section_dates($section, $course) {
1234 throw new coding_exception('Function format_weeks_get_section_dates() is removed. It is not recommended to'.
1235 ' use it outside of format_weeks plugin');
1239 * Deprecated. Instead of:
1240 * list($content, $name) = get_print_section_cm_text($cm, $course);
1241 * use:
1242 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1243 * $name = $cm->get_formatted_name();
1245 * @deprecated since 2.5
1246 * @see cm_info::get_formatted_content()
1247 * @see cm_info::get_formatted_name()
1249 function get_print_section_cm_text(cm_info $cm, $course) {
1250 throw new coding_exception('Function get_print_section_cm_text() is removed. Please use '.
1251 'cm_info::get_formatted_content() and cm_info::get_formatted_name()');
1255 * Deprecated. Please use:
1256 * $courserenderer = $PAGE->get_renderer('core', 'course');
1257 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1258 * array('inblock' => $vertical));
1259 * echo $output;
1261 * @deprecated since 2.5
1262 * @see core_course_renderer::course_section_add_cm_control()
1264 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1265 throw new coding_exception('Function print_section_add_menus() is removed. Please use course renderer '.
1266 'function course_section_add_cm_control()');
1270 * Deprecated. Please use:
1271 * $courserenderer = $PAGE->get_renderer('core', 'course');
1272 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1273 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1275 * @deprecated since 2.5
1276 * @see course_get_cm_edit_actions()
1277 * @see core_course_renderer->course_section_cm_edit_actions()
1279 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1280 throw new coding_exception('Function make_editing_buttons() is removed, please see PHPdocs in '.
1281 'lib/deprecatedlib.php on how to replace it');
1285 * Deprecated. Please use:
1286 * $courserenderer = $PAGE->get_renderer('core', 'course');
1287 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1288 * array('hidecompletion' => $hidecompletion));
1290 * @deprecated since 2.5
1291 * @see core_course_renderer::course_section_cm_list()
1293 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1294 throw new coding_exception('Function print_section() is removed. Please use course renderer function '.
1295 'course_section_cm_list() instead.');
1299 * @deprecated since 2.5
1301 function print_overview($courses, array $remote_courses=array()) {
1302 throw new coding_exception('Function print_overview() is removed. Use block course_overview to display this information');
1306 * @deprecated since 2.5
1308 function print_recent_activity($course) {
1309 throw new coding_exception('Function print_recent_activity() is removed. It is not recommended to'.
1310 ' use it outside of block_recent_activity');
1314 * @deprecated since 2.5
1316 function delete_course_module($id) {
1317 throw new coding_exception('Function delete_course_module() is removed. Please use course_delete_module() instead.');
1321 * @deprecated since 2.5
1323 function update_category_button($categoryid = 0) {
1324 throw new coding_exception('Function update_category_button() is removed. Pages to view '.
1325 'and edit courses are now separate and no longer depend on editing mode.');
1329 * This function is deprecated! For list of categories use
1330 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
1331 * For parents of one particular category use
1332 * coursecat::get($id)->get_parents()
1334 * @deprecated since 2.5
1336 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1337 $excludeid = 0, $category = NULL, $path = "") {
1338 throw new coding_exception('Global function make_categories_list() is removed. Please use '.
1339 'coursecat::make_categories_list() and coursecat::get_parents()');
1343 * @deprecated since 2.5
1345 function category_delete_move($category, $newparentid, $showfeedback=true) {
1346 throw new coding_exception('Function category_delete_move() is removed. Please use coursecat::delete_move() instead.');
1350 * @deprecated since 2.5
1352 function category_delete_full($category, $showfeedback=true) {
1353 throw new coding_exception('Function category_delete_full() is removed. Please use coursecat::delete_full() instead.');
1357 * This function is deprecated. Please use
1358 * $coursecat = coursecat::get($category->id);
1359 * if ($coursecat->can_change_parent($newparentcat->id)) {
1360 * $coursecat->change_parent($newparentcat->id);
1363 * Alternatively you can use
1364 * $coursecat->update(array('parent' => $newparentcat->id));
1366 * @see coursecat::change_parent()
1367 * @see coursecat::update()
1368 * @deprecated since 2.5
1370 function move_category($category, $newparentcat) {
1371 throw new coding_exception('Function move_category() is removed. Please use coursecat::change_parent() instead.');
1375 * This function is deprecated. Please use
1376 * coursecat::get($category->id)->hide();
1378 * @see coursecat::hide()
1379 * @deprecated since 2.5
1381 function course_category_hide($category) {
1382 throw new coding_exception('Function course_category_hide() is removed. Please use coursecat::hide() instead.');
1386 * This function is deprecated. Please use
1387 * coursecat::get($category->id)->show();
1389 * @see coursecat::show()
1390 * @deprecated since 2.5
1392 function course_category_show($category) {
1393 throw new coding_exception('Function course_category_show() is removed. Please use coursecat::show() instead.');
1397 * This function is deprecated.
1398 * To get the category with the specified it please use:
1399 * coursecat::get($catid, IGNORE_MISSING);
1400 * or
1401 * coursecat::get($catid, MUST_EXIST);
1403 * To get the first available category please use
1404 * coursecat::get_default();
1406 * @deprecated since 2.5
1408 function get_course_category($catid=0) {
1409 throw new coding_exception('Function get_course_category() is removed. Please use coursecat::get(), see phpdocs for more details');
1413 * This function is deprecated. It is replaced with the method create() in class coursecat.
1414 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
1416 * @deprecated since 2.5
1418 function create_course_category($category) {
1419 throw new coding_exception('Function create_course_category() is removed. Please use coursecat::create(), see phpdocs for more details');
1423 * This function is deprecated.
1425 * To get visible children categories of the given category use:
1426 * coursecat::get($categoryid)->get_children();
1427 * This function will return the array or coursecat objects, on each of them
1428 * you can call get_children() again
1430 * @see coursecat::get()
1431 * @see coursecat::get_children()
1433 * @deprecated since 2.5
1435 function get_all_subcategories($catid) {
1436 throw new coding_exception('Function get_all_subcategories() is removed. Please use appropriate methods() of coursecat
1437 class. See phpdocs for more details');
1441 * This function is deprecated. Please use functions in class coursecat:
1442 * - coursecat::get($parentid)->has_children()
1443 * tells if the category has children (visible or not to the current user)
1445 * - coursecat::get($parentid)->get_children()
1446 * returns an array of coursecat objects, each of them represents a children category visible
1447 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
1449 * - coursecat::get($parentid)->get_children_count()
1450 * returns number of children categories visible to the current user
1452 * - coursecat::count_all()
1453 * returns total count of all categories in the system (both visible and not)
1455 * - coursecat::get_default()
1456 * returns the first category (usually to be used if count_all() == 1)
1458 * @deprecated since 2.5
1460 function get_child_categories($parentid) {
1461 throw new coding_exception('Function get_child_categories() is removed. Use coursecat::get_children() or see phpdocs for
1462 more details.');
1467 * @deprecated since 2.5
1469 * This function is deprecated. Use appropriate functions from class coursecat.
1470 * Examples:
1472 * coursecat::get($categoryid)->get_children()
1473 * - returns all children of the specified category as instances of class
1474 * coursecat, which means on each of them method get_children() can be called again.
1475 * Only categories visible to the current user are returned.
1477 * coursecat::get(0)->get_children()
1478 * - returns all top-level categories visible to the current user.
1480 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
1482 * coursecat::make_categories_list()
1483 * - returns an array of all categories id/names in the system.
1484 * Also only returns categories visible to current user and can additionally be
1485 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
1487 * make_categories_options()
1488 * - Returns full course categories tree to be used in html_writer::select()
1490 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
1491 * {@link coursecat::get_default()}
1493 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1494 throw new coding_exception('Function get_categories() is removed. Please use coursecat::get_children() or see phpdocs for other alternatives');
1498 * This function is deprecated, please use course renderer:
1499 * $renderer = $PAGE->get_renderer('core', 'course');
1500 * echo $renderer->course_search_form($value, $format);
1502 * @deprecated since 2.5
1504 function print_course_search($value="", $return=false, $format="plain") {
1505 throw new coding_exception('Function print_course_search() is removed, please use course renderer');
1509 * This function is deprecated, please use:
1510 * $renderer = $PAGE->get_renderer('core', 'course');
1511 * echo $renderer->frontpage_my_courses()
1513 * @deprecated since 2.5
1515 function print_my_moodle() {
1516 throw new coding_exception('Function print_my_moodle() is removed, please use course renderer function frontpage_my_courses()');
1520 * This function is deprecated, it is replaced with protected function
1521 * {@link core_course_renderer::frontpage_remote_course()}
1522 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1524 * @deprecated since 2.5
1526 function print_remote_course($course, $width="100%") {
1527 throw new coding_exception('Function print_remote_course() is removed, please use course renderer');
1531 * This function is deprecated, it is replaced with protected function
1532 * {@link core_course_renderer::frontpage_remote_host()}
1533 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1535 * @deprecated since 2.5
1537 function print_remote_host($host, $width="100%") {
1538 throw new coding_exception('Function print_remote_host() is removed, please use course renderer');
1542 * @deprecated since 2.5
1544 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1546 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1547 throw new coding_exception('Function print_whole_category_list() is removed, please use course renderer');
1551 * @deprecated since 2.5
1553 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1554 throw new coding_exception('Function print_category_info() is removed, please use course renderer');
1558 * @deprecated since 2.5
1560 * This function is not used any more in moodle core and course renderer does not have render function for it.
1561 * Combo list on the front page is displayed as:
1562 * $renderer = $PAGE->get_renderer('core', 'course');
1563 * echo $renderer->frontpage_combo_list()
1565 * The new class {@link coursecat} stores the information about course category tree
1566 * To get children categories use:
1567 * coursecat::get($id)->get_children()
1568 * To get list of courses use:
1569 * coursecat::get($id)->get_courses()
1571 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1573 function get_course_category_tree($id = 0, $depth = 0) {
1574 throw new coding_exception('Function get_course_category_tree() is removed, please use course renderer or coursecat class,
1575 see function phpdocs for more info');
1579 * @deprecated since 2.5
1581 * To print a generic list of courses use:
1582 * $renderer = $PAGE->get_renderer('core', 'course');
1583 * echo $renderer->courses_list($courses);
1585 * To print list of all courses:
1586 * $renderer = $PAGE->get_renderer('core', 'course');
1587 * echo $renderer->frontpage_available_courses();
1589 * To print list of courses inside category:
1590 * $renderer = $PAGE->get_renderer('core', 'course');
1591 * echo $renderer->course_category($category); // this will also print subcategories
1593 function print_courses($category) {
1594 throw new coding_exception('Function print_courses() is removed, please use course renderer');
1598 * @deprecated since 2.5
1600 * Please use course renderer to display a course information box.
1601 * $renderer = $PAGE->get_renderer('core', 'course');
1602 * echo $renderer->courses_list($courses); // will print list of courses
1603 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
1605 function print_course($course, $highlightterms = '') {
1606 throw new coding_exception('Function print_course() is removed, please use course renderer');
1610 * @deprecated since 2.5
1612 * This function is not used any more in moodle core and course renderer does not have render function for it.
1613 * Combo list on the front page is displayed as:
1614 * $renderer = $PAGE->get_renderer('core', 'course');
1615 * echo $renderer->frontpage_combo_list()
1617 * The new class {@link coursecat} stores the information about course category tree
1618 * To get children categories use:
1619 * coursecat::get($id)->get_children()
1620 * To get list of courses use:
1621 * coursecat::get($id)->get_courses()
1623 function get_category_courses_array($categoryid = 0) {
1624 throw new coding_exception('Function get_category_courses_array() is removed, please use methods of coursecat class');
1628 * @deprecated since 2.5
1630 function get_category_courses_array_recursively(array &$flattened, $category) {
1631 throw new coding_exception('Function get_category_courses_array_recursively() is removed, please use methods of coursecat class', DEBUG_DEVELOPER);
1635 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
1637 function blog_get_context_url($context=null) {
1638 throw new coding_exception('Function blog_get_context_url() is removed, getting params from context is not reliable for blogs.');
1642 * @deprecated since 2.5
1644 * To get list of all courses with course contacts ('managers') use
1645 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
1647 * To get list of courses inside particular category use
1648 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
1650 * Additionally you can specify sort order, offset and maximum number of courses,
1651 * see {@link coursecat::get_courses()}
1653 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
1654 throw new coding_exception('Function get_courses_wmanagers() is removed, please use coursecat::get_courses()');
1658 * @deprecated since 2.5
1660 function convert_tree_to_html($tree, $row=0) {
1661 throw new coding_exception('Function convert_tree_to_html() is removed. Consider using class tabtree and core_renderer::render_tabtree()');
1665 * @deprecated since 2.5
1667 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
1668 throw new coding_exception('Function convert_tabrows_to_tree() is removed. Consider using class tabtree');
1672 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
1674 function can_use_rotated_text() {
1675 debugging('can_use_rotated_text() is removed. JS feature detection is used automatically.');
1679 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
1680 * @see context::instance_by_id($id)
1682 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
1683 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
1687 * Returns system context or null if can not be created yet.
1689 * @see context_system::instance()
1690 * @deprecated since 2.2
1691 * @param bool $cache use caching
1692 * @return context system context (null if context table not created yet)
1694 function get_system_context($cache = true) {
1695 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
1696 return context_system::instance(0, IGNORE_MISSING, $cache);
1700 * @see context::get_parent_context_ids()
1701 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
1703 function get_parent_contexts(context $context, $includeself = false) {
1704 throw new coding_exception('get_parent_contexts() is removed, please use $context->get_parent_context_ids() instead.');
1708 * @deprecated since Moodle 2.2
1709 * @see context::get_parent_context()
1711 function get_parent_contextid(context $context) {
1712 throw new coding_exception('get_parent_contextid() is removed, please use $context->get_parent_context() instead.');
1716 * @see context::get_child_contexts()
1717 * @deprecated since 2.2
1719 function get_child_contexts(context $context) {
1720 throw new coding_exception('get_child_contexts() is removed, please use $context->get_child_contexts() instead.');
1724 * @see context_helper::create_instances()
1725 * @deprecated since 2.2
1727 function create_contexts($contextlevel = null, $buildpaths = true) {
1728 throw new coding_exception('create_contexts() is removed, please use context_helper::create_instances() instead.');
1732 * @see context_helper::cleanup_instances()
1733 * @deprecated since 2.2
1735 function cleanup_contexts() {
1736 throw new coding_exception('cleanup_contexts() is removed, please use context_helper::cleanup_instances() instead.');
1740 * Populate context.path and context.depth where missing.
1742 * @deprecated since 2.2
1744 function build_context_path($force = false) {
1745 throw new coding_exception('build_context_path() is removed, please use context_helper::build_all_paths() instead.');
1749 * @deprecated since 2.2
1751 function rebuild_contexts(array $fixcontexts) {
1752 throw new coding_exception('rebuild_contexts() is removed, please use $context->reset_paths(true) instead.');
1756 * @deprecated since Moodle 2.2
1757 * @see context_helper::preload_course()
1759 function preload_course_contexts($courseid) {
1760 throw new coding_exception('preload_course_contexts() is removed, please use context_helper::preload_course() instead.');
1764 * @deprecated since Moodle 2.2
1765 * @see context::update_moved()
1767 function context_moved(context $context, context $newparent) {
1768 throw new coding_exception('context_moved() is removed, please use context::update_moved() instead.');
1772 * @see context::get_capabilities()
1773 * @deprecated since 2.2
1775 function fetch_context_capabilities(context $context) {
1776 throw new coding_exception('fetch_context_capabilities() is removed, please use $context->get_capabilities() instead.');
1780 * @deprecated since 2.2
1781 * @see context_helper::preload_from_record()
1783 function context_instance_preload(stdClass $rec) {
1784 throw new coding_exception('context_instance_preload() is removed, please use context_helper::preload_from_record() instead.');
1788 * Returns context level name
1790 * @deprecated since 2.2
1791 * @see context_helper::get_level_name()
1793 function get_contextlevel_name($contextlevel) {
1794 throw new coding_exception('get_contextlevel_name() is removed, please use context_helper::get_level_name() instead.');
1798 * @deprecated since 2.2
1799 * @see context::get_context_name()
1801 function print_context_name(context $context, $withprefix = true, $short = false) {
1802 throw new coding_exception('print_context_name() is removed, please use $context->get_context_name() instead.');
1806 * @deprecated since 2.2, use $context->mark_dirty() instead
1807 * @see context::mark_dirty()
1809 function mark_context_dirty($path) {
1810 throw new coding_exception('mark_context_dirty() is removed, please use $context->mark_dirty() instead.');
1814 * @deprecated since Moodle 2.2
1815 * @see context_helper::delete_instance() or context::delete_content()
1817 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1818 if ($deleterecord) {
1819 throw new coding_exception('delete_context() is removed, please use context_helper::delete_instance() instead.');
1820 } else {
1821 throw new coding_exception('delete_context() is removed, please use $context->delete_content() instead.');
1826 * @deprecated since 2.2
1827 * @see context::get_url()
1829 function get_context_url(context $context) {
1830 throw new coding_exception('get_context_url() is removed, please use $context->get_url() instead.');
1834 * @deprecated since 2.2
1835 * @see context::get_course_context()
1837 function get_course_context(context $context) {
1838 throw new coding_exception('get_course_context() is removed, please use $context->get_course_context(true) instead.');
1842 * @deprecated since 2.2
1843 * @see enrol_get_users_courses()
1845 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1847 throw new coding_exception('get_user_courses_bycap() is removed, please use enrol_get_users_courses() instead.');
1851 * @deprecated since Moodle 2.2
1853 function get_role_context_caps($roleid, context $context) {
1854 throw new coding_exception('get_role_context_caps() is removed, it is really slow. Don\'t use it.');
1858 * @see context::get_course_context()
1859 * @deprecated since 2.2
1861 function get_courseid_from_context(context $context) {
1862 throw new coding_exception('get_courseid_from_context() is removed, please use $context->get_course_context(false) instead.');
1866 * If you are using this methid, you should have something like this:
1868 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1870 * To prevent the use of this deprecated function, replace the line above with something similar to this:
1872 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1874 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1875 * ^ ^ ^ ^
1876 * $params = array('contextlevel' => CONTEXT_COURSE);
1878 * @see context_helper:;get_preload_record_columns_sql()
1879 * @deprecated since 2.2
1881 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
1882 throw new coding_exception('context_instance_preload_sql() is removed, please use context_helper::get_preload_record_columns_sql() instead.');
1886 * @deprecated since 2.2
1887 * @see context::get_parent_context_ids()
1889 function get_related_contexts_string(context $context) {
1890 throw new coding_exception('get_related_contexts_string() is removed, please use $context->get_parent_context_ids(true) instead.');
1894 * @deprecated since 2.6
1895 * @see core_component::get_plugin_list_with_file()
1897 function get_plugin_list_with_file($plugintype, $file, $include = false) {
1898 throw new coding_exception('get_plugin_list_with_file() is removed, please use core_component::get_plugin_list_with_file() instead.');
1902 * @deprecated since 2.6
1904 function check_browser_operating_system($brand) {
1905 throw new coding_exception('check_browser_operating_system is removed, please update your code to use core_useragent instead.');
1909 * @deprecated since 2.6
1911 function check_browser_version($brand, $version = null) {
1912 throw new coding_exception('check_browser_version is removed, please update your code to use core_useragent instead.');
1916 * @deprecated since 2.6
1918 function get_device_type() {
1919 throw new coding_exception('get_device_type is removed, please update your code to use core_useragent instead.');
1923 * @deprecated since 2.6
1925 function get_device_type_list($incusertypes = true) {
1926 throw new coding_exception('get_device_type_list is removed, please update your code to use core_useragent instead.');
1930 * @deprecated since 2.6
1932 function get_selected_theme_for_device_type($devicetype = null) {
1933 throw new coding_exception('get_selected_theme_for_device_type is removed, please update your code to use core_useragent instead.');
1937 * @deprecated since 2.6
1939 function get_device_cfg_var_name($devicetype = null) {
1940 throw new coding_exception('get_device_cfg_var_name is removed, please update your code to use core_useragent instead.');
1944 * @deprecated since 2.6
1946 function set_user_device_type($newdevice) {
1947 throw new coding_exception('set_user_device_type is removed, please update your code to use core_useragent instead.');
1951 * @deprecated since 2.6
1953 function get_user_device_type() {
1954 throw new coding_exception('get_user_device_type is removed, please update your code to use core_useragent instead.');
1958 * @deprecated since 2.6
1960 function get_browser_version_classes() {
1961 throw new coding_exception('get_browser_version_classes is removed, please update your code to use core_useragent instead.');
1965 * @deprecated since Moodle 2.6
1966 * @see core_user::get_support_user()
1968 function generate_email_supportuser() {
1969 throw new coding_exception('generate_email_supportuser is removed, please use core_user::get_support_user');
1973 * @deprecated since Moodle 2.6
1975 function badges_get_issued_badge_info($hash) {
1976 throw new coding_exception('Function badges_get_issued_badge_info() is removed. Please use core_badges_assertion class and methods to generate badge assertion.');
1980 * @deprecated since 2.6
1982 function can_use_html_editor() {
1983 throw new coding_exception('can_use_html_editor is removed, please update your code to assume it returns true.');
1988 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
1990 function count_login_failures($mode, $username, $lastlogin) {
1991 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
1995 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
1997 function ajaxenabled(array $browsers = null) {
1998 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
2002 * @deprecated Since Moodle 2.7 MDL-44070
2004 function coursemodule_visible_for_user($cm, $userid=0) {
2005 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
2006 please use \core_availability\info_module::is_user_visible()');
2010 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
2012 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
2013 throw new coding_exception('Function enrol_cohort_get_cohorts() is removed, use enrol_cohort_search_cohorts() or '.
2014 'cohort_get_available_cohorts() instead');
2018 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
2019 * takes into account current context
2021 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
2023 function enrol_cohort_can_view_cohort($cohortid) {
2024 throw new coding_exception('Function enrol_cohort_can_view_cohort() is removed, use cohort_can_view_cohort() instead');
2028 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
2030 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
2032 function cohort_get_visible_list($course, $onlyenrolled=true) {
2033 throw new coding_exception('Function cohort_get_visible_list() is removed. Please use function cohort_get_available_cohorts() ".
2034 "that correctly checks capabilities.');
2038 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2040 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
2041 throw new coding_exception('enrol_cohort_enrol_all_users() is removed. This functionality is moved to enrol_manual.');
2045 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2047 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
2048 throw new coding_exception('enrol_cohort_search_cohorts() is removed. This functionality is moved to enrol_manual.');
2051 /* === Apis deprecated in since Moodle 2.9 === */
2054 * Is $USER one of the supplied users?
2056 * $user2 will be null if viewing a user's recent conversations
2058 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
2060 function message_current_user_is_involved($user1, $user2) {
2061 throw new coding_exception('message_current_user_is_involved() can not be used any more.');
2065 * Print badges on user profile page.
2067 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
2069 function profile_display_badges($userid, $courseid = 0) {
2070 throw new coding_exception('profile_display_badges() can not be used any more.');
2074 * Adds user preferences elements to user edit form.
2076 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
2078 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
2079 throw new coding_exception('useredit_shared_definition_preferences() can not be used any more.');
2084 * Convert region timezone to php supported timezone
2086 * @deprecated since Moodle 2.9
2088 function calendar_normalize_tz($tz) {
2089 throw new coding_exception('calendar_normalize_tz() can not be used any more, please use core_date::normalise_timezone() instead.');
2093 * Returns a float which represents the user's timezone difference from GMT in hours
2094 * Checks various settings and picks the most dominant of those which have a value
2095 * @deprecated since Moodle 2.9
2097 function get_user_timezone_offset($tz = 99) {
2098 throw new coding_exception('get_user_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2103 * Returns an int which represents the systems's timezone difference from GMT in seconds
2104 * @deprecated since Moodle 2.9
2106 function get_timezone_offset($tz) {
2107 throw new coding_exception('get_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2111 * Returns a list of timezones in the current language.
2112 * @deprecated since Moodle 2.9
2114 function get_list_of_timezones() {
2115 throw new coding_exception('get_list_of_timezones() can not be used any more, please use core_date::get_list_of_timezones() instead');
2119 * Previous internal API, it was not supposed to be used anywhere.
2120 * @deprecated since Moodle 2.9
2122 function update_timezone_records($timezones) {
2123 throw new coding_exception('update_timezone_records() can not be used any more, please use standard PHP DateTime class instead');
2127 * Previous internal API, it was not supposed to be used anywhere.
2128 * @deprecated since Moodle 2.9
2130 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2131 throw new coding_exception('calculate_user_dst_table() can not be used any more, please use standard PHP DateTime class instead');
2135 * Previous internal API, it was not supposed to be used anywhere.
2136 * @deprecated since Moodle 2.9
2138 function dst_changes_for_year($year, $timezone) {
2139 throw new coding_exception('dst_changes_for_year() can not be used any more, please use standard DateTime class instead');
2143 * Previous internal API, it was not supposed to be used anywhere.
2144 * @deprecated since Moodle 2.9
2146 function get_timezone_record($timezonename) {
2147 throw new coding_exception('get_timezone_record() can not be used any more, please use standard PHP DateTime class instead');
2150 /* === Apis deprecated since Moodle 3.0 === */
2152 * @deprecated since Moodle 3.0 MDL-49360 - please do not use this function any more.
2154 function get_referer($stripquery = true) {
2155 throw new coding_exception('get_referer() can not be used any more. Please use get_local_referer() instead.');
2159 * @deprecated since Moodle 3.0 use \core_useragent::is_web_crawler instead.
2161 function is_web_crawler() {
2162 throw new coding_exception('is_web_crawler() can not be used any more. Please use core_useragent::is_web_crawler() instead.');
2166 * @deprecated since Moodle 3.0 MDL-50287 - please do not use this function any more.
2168 function completion_cron() {
2169 throw new coding_exception('completion_cron() can not be used any more. Functionality has been moved to scheduled tasks.');
2173 * @deprecated since 3.0
2175 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $unused = '') {
2176 throw new coding_exception('Function coursetag_get_tags() can not be used any more. Userid is no longer used for tagging courses.');
2180 * @deprecated since 3.0
2182 function coursetag_get_all_tags($unused='', $numtags=0) {
2183 throw new coding_exception('Function coursetag_get_all_tag() can not be used any more. Userid is no longer used for tagging courses.');
2187 * @deprecated since 3.0
2189 function coursetag_get_jscript() {
2190 throw new coding_exception('Function coursetag_get_jscript() can not be used any more and is obsolete.');
2194 * @deprecated since 3.0
2196 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
2197 throw new coding_exception('Function coursetag_get_jscript_links() can not be used any more and is obsolete.');
2201 * @deprecated since 3.0
2203 function coursetag_get_records($courseid, $userid) {
2204 throw new coding_exception('Function coursetag_get_records() can not be used any more. Userid is no longer used for tagging courses.');
2208 * @deprecated since 3.0
2210 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
2211 throw new coding_exception('Function coursetag_store_keywords() can not be used any more. Userid is no longer used for tagging courses.');
2215 * @deprecated since 3.0
2217 function coursetag_delete_keyword($tagid, $userid, $courseid) {
2218 throw new coding_exception('Function coursetag_delete_keyword() can not be used any more. Userid is no longer used for tagging courses.');
2222 * @deprecated since 3.0
2224 function coursetag_get_tagged_courses($tagid) {
2225 throw new coding_exception('Function coursetag_get_tagged_courses() can not be used any more. Userid is no longer used for tagging courses.');
2229 * @deprecated since 3.0
2231 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
2232 throw new coding_exception('Function coursetag_delete_course_tags() is deprecated. Use core_tag_tag::remove_all_item_tags().');
2236 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
2237 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
2239 * @package core_tag
2240 * @deprecated since 3.1
2241 * @param string $tagid tagid to modify
2242 * @param string $type either 'default' or 'official'
2243 * @return bool true on success, false otherwise
2245 function tag_type_set($tagid, $type) {
2246 debugging('Function tag_type_set() is deprecated and can be replaced with use core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2247 if ($tag = core_tag_tag::get($tagid, '*')) {
2248 return $tag->update(array('isstandard' => ($type === 'official') ? 1 : 0));
2250 return false;
2254 * Set the description of a tag
2256 * @package core_tag
2257 * @deprecated since 3.1
2258 * @param int $tagid the id of the tag
2259 * @param string $description the tag's description string to be set
2260 * @param int $descriptionformat the moodle text format of the description
2261 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
2262 * @return bool true on success, false otherwise
2264 function tag_description_set($tagid, $description, $descriptionformat) {
2265 debugging('Function tag_type_set() is deprecated and can be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2266 if ($tag = core_tag_tag::get($tagid, '*')) {
2267 return $tag->update(array('description' => $description, 'descriptionformat' => $descriptionformat));
2269 return false;
2273 * Get the array of db record of tags associated to a record (instances).
2275 * @package core_tag
2276 * @deprecated since 3.1
2277 * @param string $record_type the record type for which we want to get the tags
2278 * @param int $record_id the record id for which we want to get the tags
2279 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2280 * @param int $userid (optional) only required for course tagging
2281 * @return array the array of tags
2283 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
2284 debugging('Method tag_get_tags() is deprecated and replaced with core_tag_tag::get_item_tags(). ' .
2285 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2286 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2287 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2288 $tags = core_tag_tag::get_item_tags(null, $record_type, $record_id, $standardonly, $userid);
2289 $rv = array();
2290 foreach ($tags as $id => $t) {
2291 $rv[$id] = $t->to_object();
2293 return $rv;
2297 * Get the array of tags display names, indexed by id.
2299 * @package core_tag
2300 * @deprecated since 3.1
2301 * @param string $record_type the record type for which we want to get the tags
2302 * @param int $record_id the record id for which we want to get the tags
2303 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2304 * @return array the array of tags (with the value returned by core_tag_tag::make_display_name), indexed by id
2306 function tag_get_tags_array($record_type, $record_id, $type=null) {
2307 debugging('Method tag_get_tags_array() is deprecated and replaced with core_tag_tag::get_item_tags_array(). ' .
2308 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2309 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2310 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2311 return core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly);
2315 * Get a comma-separated string of tags associated to a record.
2317 * Use {@link tag_get_tags()} to get the same information in an array.
2319 * @package core_tag
2320 * @deprecated since 3.1
2321 * @param string $record_type the record type for which we want to get the tags
2322 * @param int $record_id the record id for which we want to get the tags
2323 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
2324 * @param string $type either 'official' or 'default', if null, all tags are returned
2325 * @return string the comma-separated list of tags.
2327 function tag_get_tags_csv($record_type, $record_id, $html=null, $type=null) {
2328 global $CFG, $OUTPUT;
2329 debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' .
2330 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' .
2331 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2332 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2333 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2334 if ($html != TAG_RETURN_TEXT) {
2335 return $OUTPUT->tag_list(core_tag_tag::get_item_tags('', $record_type, $record_id, $standardonly), '');
2336 } else {
2337 return join(', ', core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false));
2342 * Get an array of tag ids associated to a record.
2344 * @package core_tag
2345 * @deprecated since 3.1
2346 * @param string $record_type the record type for which we want to get the tags
2347 * @param int $record_id the record id for which we want to get the tags
2348 * @return array tag ids, indexed and sorted by 'ordering'
2350 function tag_get_tags_ids($record_type, $record_id) {
2351 debugging('Method tag_get_tags_ids() is deprecated. Please consider using core_tag_tag::get_item_tags() or similar methods.', DEBUG_DEVELOPER);
2352 $tag_ids = array();
2353 $tagobjects = core_tag_tag::get_item_tags(null, $record_type, $record_id);
2354 foreach ($tagobjects as $tagobject) {
2355 $tag = $tagobject->to_object();
2356 if ( array_key_exists($tag->ordering, $tag_ids) ) {
2357 $tag->ordering++;
2359 $tag_ids[$tag->ordering] = $tag->id;
2361 ksort($tag_ids);
2362 return $tag_ids;
2366 * Returns the database ID of a set of tags.
2368 * @deprecated since 3.1
2369 * @param mixed $tags one tag, or array of tags, to look for.
2370 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
2371 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
2372 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
2373 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
2375 function tag_get_id($tags, $return_value = null) {
2376 global $CFG, $DB;
2377 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(). ' .
2378 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2380 if (!is_array($tags)) {
2381 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
2382 if ($tagobject = core_tag_tag::get_by_name(core_tag_collection::get_default(), $tags)) {
2383 return $tagobject->id;
2384 } else {
2385 return 0;
2388 $tags = array($tags);
2391 $records = core_tag_tag::get_by_name_bulk(core_tag_collection::get_default(), $tags,
2392 $return_value == TAG_RETURN_OBJECT ? '*' : 'id, name');
2393 foreach ($records as $name => $record) {
2394 if ($return_value != TAG_RETURN_OBJECT) {
2395 $records[$name] = $record->id ? $record->id : null;
2396 } else {
2397 $records[$name] = $record->to_object();
2400 return $records;
2404 * Change the "value" of a tag, and update the associated 'name'.
2406 * @package core_tag
2407 * @deprecated since 3.1
2408 * @param int $tagid the id of the tag to modify
2409 * @param string $newrawname the new rawname
2410 * @return bool true on success, false otherwise
2412 function tag_rename($tagid, $newrawname) {
2413 debugging('Function tag_rename() is deprecated and may be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2414 if ($tag = core_tag_tag::get($tagid, '*')) {
2415 return $tag->update(array('rawname' => $newrawname));
2417 return false;
2421 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
2423 * @package core_tag
2424 * @deprecated since 3.1
2425 * @param string $record_type the type of the record for which to remove the instance
2426 * @param int $record_id the id of the record for which to remove the instance
2427 * @param int $tagid the tagid that needs to be removed
2428 * @param int $userid (optional) the userid
2429 * @return bool true on success, false otherwise
2431 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
2432 debugging('Function tag_delete_instance() is deprecated and replaced with core_tag_tag::remove_item_tag() instead. ' .
2433 'Component is required for retrieving instances', DEBUG_DEVELOPER);
2434 $tag = core_tag_tag::get($tagid);
2435 core_tag_tag::remove_item_tag('', $record_type, $record_id, $tag->rawname, $userid);
2439 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
2441 * @package core_tag
2442 * @deprecated since 3.1
2443 * @category tag
2444 * @param string $tag tag to look for
2445 * @param string $type type to restrict search to. If null, every matching record will be returned
2446 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
2447 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
2448 * @return array of matching objects, indexed by record id, from the table containing the type requested
2450 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
2451 debugging('Function tag_find_records() is deprecated and replaced with core_tag_tag::get_by_name()->get_tagged_items(). '.
2452 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2454 if (!$tag || !$type) {
2455 return array();
2458 $tagobject = core_tag_tag::get_by_name(core_tag_area::get_collection('', $type), $tag);
2459 return $tagobject->get_tagged_items('', $type, $limitfrom, $limitnum);
2463 * Adds one or more tag in the database. This function should not be called directly : you should
2464 * use tag_set.
2466 * @package core_tag
2467 * @deprecated since 3.1
2468 * @param mixed $tags one tag, or an array of tags, to be created
2469 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
2470 * value at this time). An official tag is kept even if there are no records tagged with it.
2471 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
2472 * adding the tag.
2474 function tag_add($tags, $type="default") {
2475 debugging('Function tag_add() is deprecated. You can use core_tag_tag::create_if_missing(), however it should not be necessary ' .
2476 'since tags are created automatically when assigned to items', DEBUG_DEVELOPER);
2477 if (!is_array($tags)) {
2478 $tags = array($tags);
2480 $objects = core_tag_tag::create_if_missing(core_tag_collection::get_default(), $tags,
2481 $type === 'official');
2483 // New function returns the tags in different format, for BC we keep the format that this function used to have.
2484 $rv = array();
2485 foreach ($objects as $name => $tagobject) {
2486 if (isset($tagobject->id)) {
2487 $rv[$tagobject->name] = $tagobject->id;
2488 } else {
2489 $rv[$name] = false;
2492 return $rv;
2496 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
2498 * @package core_tag
2499 * @deprecated since 3.1
2500 * @param string $record_type the type of the record that will be tagged
2501 * @param int $record_id the id of the record that will be tagged
2502 * @param string $tagid the tag id to set on the record.
2503 * @param int $ordering the order of the instance for this record
2504 * @param int $userid (optional) only required for course tagging
2505 * @param string|null $component the component that was tagged
2506 * @param int|null $contextid the context id of where this tag was assigned
2507 * @return bool true on success, false otherwise
2509 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
2510 global $DB;
2511 $message = 'Function tag_assign() is deprecated. Use core_tag_tag::set_item_tags() or core_tag_tag::add_item_tag() instead. ' .
2512 'Tag instance ordering should not be set manually';
2513 if ($component === null || $contextid === null) {
2514 $message .= '. You should specify the component and contextid of the item being tagged in your call to tag_assign.';
2516 debugging($message, DEBUG_DEVELOPER);
2518 if ($contextid) {
2519 $context = context::instance_by_id($contextid);
2520 } else {
2521 $context = context_system::instance();
2524 // Get the tag.
2525 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
2527 $taginstanceid = core_tag_tag::add_item_tag($component, $record_type, $record_id, $context, $tag->rawname, $userid);
2529 // Alter the "ordering" of tag_instance. This should never be done manually and only remains here for the backward compatibility.
2530 $taginstance = new stdClass();
2531 $taginstance->id = $taginstanceid;
2532 $taginstance->ordering = $ordering;
2533 $taginstance->timemodified = time();
2535 $DB->update_record('tag_instance', $taginstance);
2537 return true;
2541 * Count how many records are tagged with a specific tag.
2543 * @package core_tag
2544 * @deprecated since 3.1
2545 * @param string $record_type record to look for ('post', 'user', etc.)
2546 * @param int $tagid is a single tag id
2547 * @return int number of mathing tags.
2549 function tag_record_count($record_type, $tagid) {
2550 debugging('Method tag_record_count() is deprecated and replaced with core_tag_tag::get($tagid)->count_tagged_items(). '.
2551 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2552 return core_tag_tag::get($tagid)->count_tagged_items('', $record_type);
2556 * Determine if a record is tagged with a specific tag
2558 * @package core_tag
2559 * @deprecated since 3.1
2560 * @param string $record_type the record type to look for
2561 * @param int $record_id the record id to look for
2562 * @param string $tag a tag name
2563 * @return bool/int true if it is tagged, 0 (false) otherwise
2565 function tag_record_tagged_with($record_type, $record_id, $tag) {
2566 debugging('Method tag_record_tagged_with() is deprecated and replaced with core_tag_tag::get($tagid)->is_item_tagged_with(). '.
2567 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2568 return core_tag_tag::is_item_tagged_with('', $record_type, $record_id, $tag);
2572 * Flag a tag as inappropriate.
2574 * @deprecated since 3.1
2575 * @param int|array $tagids a single tagid, or an array of tagids
2577 function tag_set_flag($tagids) {
2578 debugging('Function tag_set_flag() is deprecated and replaced with core_tag_tag::get($tagid)->flag().', DEBUG_DEVELOPER);
2579 $tagids = (array) $tagids;
2580 foreach ($tagids as $tagid) {
2581 if ($tag = core_tag_tag::get($tagid, '*')) {
2582 $tag->flag();
2588 * Remove the inappropriate flag on a tag.
2590 * @deprecated since 3.1
2591 * @param int|array $tagids a single tagid, or an array of tagids
2593 function tag_unset_flag($tagids) {
2594 debugging('Function tag_unset_flag() is deprecated and replaced with core_tag_tag::get($tagid)->reset_flag().', DEBUG_DEVELOPER);
2595 $tagids = (array) $tagids;
2596 foreach ($tagids as $tagid) {
2597 if ($tag = core_tag_tag::get($tagid, '*')) {
2598 $tag->reset_flag();
2604 * Prints or returns a HTML tag cloud with varying classes styles depending on the popularity and type of each tag.
2606 * @deprecated since 3.1
2608 * @param array $tagset Array of tags to display
2609 * @param int $nr_of_tags Limit for the number of tags to return/display, used if $tagset is null
2610 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2611 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
2612 * @return string|null a HTML string or null if this function does the output
2614 function tag_print_cloud($tagset=null, $nr_of_tags=150, $return=false, $sort='') {
2615 global $OUTPUT;
2617 debugging('Function tag_print_cloud() is deprecated and replaced with function core_tag_collection::get_tag_cloud(), '
2618 . 'templateable core_tag\output\tagcloud and template core_tag/tagcloud.', DEBUG_DEVELOPER);
2620 // Set up sort global - used to pass sort type into core_tag_collection::cloud_sort through usort() avoiding multiple sort functions.
2621 if ($sort == 'popularity') {
2622 $sort = 'count';
2623 } else if ($sort == 'date') {
2624 $sort = 'timemodified';
2625 } else {
2626 $sort = 'name';
2629 if (is_null($tagset)) {
2630 // No tag set received, so fetch tags from database.
2631 // Always add query by tagcollid even when it's not known to make use of the table index.
2632 $tagcloud = core_tag_collection::get_tag_cloud(0, false, $nr_of_tags, $sort);
2633 } else {
2634 $tagsincloud = $tagset;
2636 $etags = array();
2637 foreach ($tagsincloud as $tag) {
2638 $etags[] = $tag;
2641 core_tag_collection::$cloudsortfield = $sort;
2642 usort($tagsincloud, "core_tag_collection::cloud_sort");
2644 $tagcloud = new \core_tag\output\tagcloud($tagsincloud);
2647 $output = $OUTPUT->render_from_template('core_tag/tagcloud', $tagcloud->export_for_template($OUTPUT));
2648 if ($return) {
2649 return $output;
2650 } else {
2651 echo $output;
2656 * Function that returns tags that start with some text, for use by the autocomplete feature
2658 * @package core_tag
2659 * @deprecated since 3.0
2660 * @access private
2661 * @param string $text string that the tag names will be matched against
2662 * @return mixed an array of objects, or false if no records were found or an error occured.
2664 function tag_autocomplete($text) {
2665 debugging('Function tag_autocomplete() is deprecated without replacement. ' .
2666 'New form element "tags" does proper autocomplete.', DEBUG_DEVELOPER);
2667 global $DB;
2668 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
2669 FROM {tag} tg
2670 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
2674 * Prints a box with the description of a tag and its related tags
2676 * @package core_tag
2677 * @deprecated since 3.1
2678 * @param stdClass $tag_object
2679 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2680 * @return string/null a HTML box showing a description of the tag object and it's relationsips or null if output is done directly
2681 * in the function.
2683 function tag_print_description_box($tag_object, $return=false) {
2684 global $USER, $CFG, $OUTPUT;
2685 require_once($CFG->libdir.'/filelib.php');
2687 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2688 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2690 $relatedtags = array();
2691 if ($tag = core_tag_tag::get($tag_object->id)) {
2692 $relatedtags = $tag->get_related_tags();
2695 $content = !empty($tag_object->description);
2696 $output = '';
2698 if ($content) {
2699 $output .= $OUTPUT->box_start('generalbox tag-description');
2702 if (!empty($tag_object->description)) {
2703 $options = new stdClass();
2704 $options->para = false;
2705 $options->overflowdiv = true;
2706 $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', context_system::instance()->id, 'tag', 'description', $tag_object->id);
2707 $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options);
2710 if ($content) {
2711 $output .= $OUTPUT->box_end();
2714 if ($relatedtags) {
2715 $output .= $OUTPUT->tag_list($relatedtags, get_string('relatedtags', 'tag'), 'tag-relatedtags');
2718 if ($return) {
2719 return $output;
2720 } else {
2721 echo $output;
2726 * Prints a box that contains the management links of a tag
2728 * @deprecated since 3.1
2729 * @param core_tag_tag|stdClass $tag_object
2730 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2731 * @return string|null a HTML string or null if this function does the output
2733 function tag_print_management_box($tag_object, $return=false) {
2734 global $USER, $CFG, $OUTPUT;
2736 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2737 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2739 $tagname = core_tag_tag::make_display_name($tag_object);
2740 $output = '';
2742 if (!isguestuser()) {
2743 $output .= $OUTPUT->box_start('box','tag-management-box');
2744 $systemcontext = context_system::instance();
2745 $links = array();
2747 // Add a link for users to add/remove this from their interests
2748 if (core_tag_tag::is_enabled('core', 'user') && core_tag_area::get_collection('core', 'user') == $tag_object->tagcollid) {
2749 if (core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $tag_object->name)) {
2750 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=removeinterest&amp;sesskey='. sesskey() .
2751 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2752 get_string('removetagfrommyinterests', 'tag', $tagname) .'</a>';
2753 } else {
2754 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=addinterest&amp;sesskey='. sesskey() .
2755 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2756 get_string('addtagtomyinterests', 'tag', $tagname) .'</a>';
2760 // Flag as inappropriate link. Only people with moodle/tag:flag capability.
2761 if (has_capability('moodle/tag:flag', $systemcontext)) {
2762 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=flaginappropriate&amp;sesskey='.
2763 sesskey() . '&amp;id='. $tag_object->id . '">'. get_string('flagasinappropriate',
2764 'tag', rawurlencode($tagname)) .'</a>';
2767 // Edit tag: Only people with moodle/tag:edit capability who either have it as an interest or can manage tags
2768 if (has_capability('moodle/tag:edit', $systemcontext) ||
2769 has_capability('moodle/tag:manage', $systemcontext)) {
2770 $links[] = '<a href="' . $CFG->wwwroot . '/tag/edit.php?id=' . $tag_object->id . '">' .
2771 get_string('edittag', 'tag') . '</a>';
2774 $output .= implode(' | ', $links);
2775 $output .= $OUTPUT->box_end();
2778 if ($return) {
2779 return $output;
2780 } else {
2781 echo $output;
2786 * Prints the tag search box
2788 * @deprecated since 3.1
2789 * @param bool $return if true return html string
2790 * @return string|null a HTML string or null if this function does the output
2792 function tag_print_search_box($return=false) {
2793 global $CFG, $OUTPUT;
2795 debugging('Function tag_print_search_box() is deprecated without replacement. ' .
2796 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2798 $query = optional_param('query', '', PARAM_RAW);
2800 $output = $OUTPUT->box_start('','tag-search-box');
2801 $output .= '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
2802 $output .= '<div>';
2803 $output .= '<label class="accesshide" for="searchform_search">'.get_string('searchtags', 'tag').'</label>';
2804 $output .= '<input id="searchform_search" name="query" type="text" size="40" value="'.s($query).'" />';
2805 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
2806 $output .= '</div>';
2807 $output .= '</form>';
2808 $output .= $OUTPUT->box_end();
2810 if ($return) {
2811 return $output;
2813 else {
2814 echo $output;
2819 * Prints the tag search results
2821 * @deprecated since 3.1
2822 * @param string $query text that tag names will be matched against
2823 * @param int $page current page
2824 * @param int $perpage nr of users displayed per page
2825 * @param bool $return if true return html string
2826 * @return string|null a HTML string or null if this function does the output
2828 function tag_print_search_results($query, $page, $perpage, $return=false) {
2829 global $CFG, $USER, $OUTPUT;
2831 debugging('Function tag_print_search_results() is deprecated without replacement. ' .
2832 'In /tag/search.php the search results are printed using the core_tag/tagcloud template.', DEBUG_DEVELOPER);
2834 $query = clean_param($query, PARAM_TAG);
2836 $count = count(tag_find_tags($query, false));
2837 $tags = array();
2839 if ( $found_tags = tag_find_tags($query, true, $page * $perpage, $perpage) ) {
2840 $tags = array_values($found_tags);
2843 $baseurl = $CFG->wwwroot.'/tag/search.php?query='. rawurlencode($query);
2844 $output = '';
2846 // link "Add $query to my interests"
2847 $addtaglink = '';
2848 if (core_tag_tag::is_enabled('core', 'user') && !core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $query)) {
2849 $addtaglink = html_writer::link(new moodle_url('/tag/user.php', array('action' => 'addinterest', 'sesskey' => sesskey(),
2850 'tag' => $query)), get_string('addtagtomyinterests', 'tag', s($query)));
2853 if ( !empty($tags) ) { // there are results to display!!
2854 $output .= $OUTPUT->heading(get_string('searchresultsfor', 'tag', htmlspecialchars($query)) ." : {$count}", 3, 'main');
2856 //print a link "Add $query to my interests"
2857 if (!empty($addtaglink)) {
2858 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2861 $nr_of_lis_per_ul = 6;
2862 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul );
2864 $output .= '<ul id="tag-search-results">';
2865 for($i = 0; $i < $nr_of_uls; $i++) {
2866 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul) as $tag) {
2867 $output .= '<li>';
2868 $tag_link = html_writer::link(core_tag_tag::make_url($tag->tagcollid, $tag->rawname),
2869 core_tag_tag::make_display_name($tag));
2870 $output .= $tag_link;
2871 $output .= '</li>';
2874 $output .= '</ul>';
2875 $output .= '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
2877 $output .= $OUTPUT->paging_bar($count, $page, $perpage, $baseurl);
2879 else { //no results were found!!
2880 $output .= $OUTPUT->heading(get_string('noresultsfor', 'tag', htmlspecialchars($query)), 3, 'main');
2882 //print a link "Add $query to my interests"
2883 if (!empty($addtaglink)) {
2884 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2888 if ($return) {
2889 return $output;
2891 else {
2892 echo $output;
2897 * Prints a table of the users tagged with the tag passed as argument
2899 * @deprecated since 3.1
2900 * @param stdClass $tagobject the tag we wish to return data for
2901 * @param int $limitfrom (optional, required if $limitnum is set) prints users starting at this point.
2902 * @param int $limitnum (optional, required if $limitfrom is set) prints this many users.
2903 * @param bool $return if true return html string
2904 * @return string|null a HTML string or null if this function does the output
2906 function tag_print_tagged_users_table($tagobject, $limitfrom='', $limitnum='', $return=false) {
2908 debugging('Function tag_print_tagged_users_table() is deprecated without replacement. ' .
2909 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2911 //List of users with this tag
2912 $tagobject = core_tag_tag::get($tagobject->id);
2913 $userlist = $tagobject->get_tagged_items('core', 'user', $limitfrom, $limitnum);
2915 $output = tag_print_user_list($userlist, true);
2917 if ($return) {
2918 return $output;
2920 else {
2921 echo $output;
2926 * Prints an individual user box
2928 * @deprecated since 3.1
2929 * @param user_object $user (contains the following fields: id, firstname, lastname and picture)
2930 * @param bool $return if true return html string
2931 * @return string|null a HTML string or null if this function does the output
2933 function tag_print_user_box($user, $return=false) {
2934 global $CFG, $OUTPUT;
2936 debugging('Function tag_print_user_box() is deprecated without replacement. ' .
2937 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2939 $usercontext = context_user::instance($user->id);
2940 $profilelink = '';
2942 if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id))) {
2943 $profilelink = $CFG->wwwroot .'/user/view.php?id='. $user->id;
2946 $output = $OUTPUT->box_start('user-box', 'user'. $user->id);
2947 $fullname = fullname($user);
2948 $alt = '';
2950 if (!empty($profilelink)) {
2951 $output .= '<a href="'. $profilelink .'">';
2952 $alt = $fullname;
2955 $output .= $OUTPUT->user_picture($user, array('size'=>100));
2956 $output .= '<br />';
2958 if (!empty($profilelink)) {
2959 $output .= '</a>';
2962 //truncate name if it's too big
2963 if (core_text::strlen($fullname) > 26) {
2964 $fullname = core_text::substr($fullname, 0, 26) .'...';
2967 $output .= '<strong>'. $fullname .'</strong>';
2968 $output .= $OUTPUT->box_end();
2970 if ($return) {
2971 return $output;
2973 else {
2974 echo $output;
2979 * Prints a list of users
2981 * @deprecated since 3.1
2982 * @param array $userlist an array of user objects
2983 * @param bool $return if true return html string, otherwise output the result
2984 * @return string|null a HTML string or null if this function does the output
2986 function tag_print_user_list($userlist, $return=false) {
2988 debugging('Function tag_print_user_list() is deprecated without replacement. ' .
2989 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2991 $output = '<div><ul class="inline-list">';
2993 foreach ($userlist as $user){
2994 $output .= '<li>'. tag_print_user_box($user, true) ."</li>\n";
2996 $output .= "</ul></div>\n";
2998 if ($return) {
2999 return $output;
3001 else {
3002 echo $output;
3007 * Function that returns the name that should be displayed for a specific tag
3009 * @package core_tag
3010 * @category tag
3011 * @deprecated since 3.1
3012 * @param stdClass|core_tag_tag $tagobject a line out of tag table, as returned by the adobd functions
3013 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
3014 * @return string
3016 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
3017 debugging('Function tag_display_name() is deprecated. Use core_tag_tag::make_display_name().', DEBUG_DEVELOPER);
3018 if (!isset($tagobject->name)) {
3019 return '';
3021 return core_tag_tag::make_display_name($tagobject, $html != TAG_RETURN_TEXT);
3025 * Function that normalizes a list of tag names.
3027 * @package core_tag
3028 * @deprecated since 3.1
3029 * @param array/string $rawtags array of tags, or a single tag.
3030 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
3031 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
3032 * (Eg: 'Banana' => 'banana').
3034 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
3035 debugging('Function tag_normalize() is deprecated. Use core_tag_tag::normalize().', DEBUG_DEVELOPER);
3037 if ( !is_array($rawtags) ) {
3038 $rawtags = array($rawtags);
3041 return core_tag_tag::normalize($rawtags, $case == TAG_CASE_LOWER);
3045 * Get a comma-separated list of tags related to another tag.
3047 * @package core_tag
3048 * @deprecated since 3.1
3049 * @param array $related_tags the array returned by tag_get_related_tags
3050 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
3051 * @return string comma-separated list
3053 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
3054 global $OUTPUT;
3055 debugging('Method tag_get_related_tags_csv() is deprecated. Consider '
3056 . 'looping through array or using $OUTPUT->tag_list(core_tag_tag::get_item_tags())',
3057 DEBUG_DEVELOPER);
3058 if ($html != TAG_RETURN_TEXT) {
3059 return $OUTPUT->tag_list($related_tags, '');
3062 $tagsnames = array();
3063 foreach ($related_tags as $tag) {
3064 $tagsnames[] = core_tag_tag::make_display_name($tag, false);
3066 return implode(', ', $tagsnames);
3070 * Used to require that the return value from a function is an array.
3071 * Only used in the deprecated function {@link tag_get_id()}
3072 * @deprecated since 3.1
3074 define('TAG_RETURN_ARRAY', 0);
3076 * Used to require that the return value from a function is an object.
3077 * Only used in the deprecated function {@link tag_get_id()}
3078 * @deprecated since 3.1
3080 define('TAG_RETURN_OBJECT', 1);
3082 * Use to specify that HTML free text is expected to be returned from a function.
3083 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3084 * {@link tag_get_related_tags_csv()}
3085 * @deprecated since 3.1
3087 define('TAG_RETURN_TEXT', 2);
3089 * Use to specify that encoded HTML is expected to be returned from a function.
3090 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3091 * {@link tag_get_related_tags_csv()}
3092 * @deprecated since 3.1
3094 define('TAG_RETURN_HTML', 3);
3097 * Used to specify that we wish a lowercased string to be returned
3098 * Only used in deprecated function {@link tag_normalize()}
3099 * @deprecated since 3.1
3101 define('TAG_CASE_LOWER', 0);
3103 * Used to specify that we do not wish the case of the returned string to change
3104 * Only used in deprecated function {@link tag_normalize()}
3105 * @deprecated since 3.1
3107 define('TAG_CASE_ORIGINAL', 1);
3110 * Used to specify that we want all related tags returned, no matter how they are related.
3111 * Only used in deprecated function {@link tag_get_related_tags()}
3112 * @deprecated since 3.1
3114 define('TAG_RELATED_ALL', 0);
3116 * Used to specify that we only want back tags that were manually related.
3117 * Only used in deprecated function {@link tag_get_related_tags()}
3118 * @deprecated since 3.1
3120 define('TAG_RELATED_MANUAL', 1);
3122 * Used to specify that we only want back tags where the relationship was automatically correlated.
3123 * Only used in deprecated function {@link tag_get_related_tags()}
3124 * @deprecated since 3.1
3126 define('TAG_RELATED_CORRELATED', 2);
3129 * Set the tags assigned to a record. This overwrites the current tags.
3131 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
3133 * Due to API change $component and $contextid are now required. Instead of
3134 * calling this function you can use {@link core_tag_tag::set_item_tags()} or
3135 * {@link core_tag_tag::set_related_tags()}
3137 * @package core_tag
3138 * @deprecated since 3.1
3139 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
3140 * @param int $itemid the id of the record to tag
3141 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
3142 * @param string|null $component the component that was tagged
3143 * @param int|null $contextid the context id of where this tag was assigned
3144 * @return bool|null
3146 function tag_set($itemtype, $itemid, $tags, $component = null, $contextid = null) {
3147 debugging('Function tag_set() is deprecated. Use ' .
3148 ' core_tag_tag::set_item_tags() instead', DEBUG_DEVELOPER);
3150 if ($itemtype === 'tag') {
3151 return core_tag_tag::get($itemid, '*', MUST_EXIST)->set_related_tags($tags);
3152 } else {
3153 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3154 return core_tag_tag::set_item_tags($component, $itemtype, $itemid, $context, $tags);
3159 * Adds a tag to a record, without overwriting the current tags.
3161 * This function remains here for backward compatiblity. It is recommended to use
3162 * {@link core_tag_tag::add_item_tag()} or {@link core_tag_tag::add_related_tags()} instead
3164 * @package core_tag
3165 * @deprecated since 3.1
3166 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3167 * @param int $itemid the id of the record to tag
3168 * @param string $tag the tag to add
3169 * @param string|null $component the component that was tagged
3170 * @param int|null $contextid the context id of where this tag was assigned
3171 * @return bool|null
3173 function tag_set_add($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3174 debugging('Function tag_set_add() is deprecated. Use ' .
3175 ' core_tag_tag::add_item_tag() instead', DEBUG_DEVELOPER);
3177 if ($itemtype === 'tag') {
3178 return core_tag_tag::get($itemid, '*', MUST_EXIST)->add_related_tags(array($tag));
3179 } else {
3180 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3181 return core_tag_tag::add_item_tag($component, $itemtype, $itemid, $context, $tag);
3186 * Removes a tag from a record, without overwriting other current tags.
3188 * This function remains here for backward compatiblity. It is recommended to use
3189 * {@link core_tag_tag::remove_item_tag()} instead
3191 * @package core_tag
3192 * @deprecated since 3.1
3193 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3194 * @param int $itemid the id of the record to tag
3195 * @param string $tag the tag to delete
3196 * @param string|null $component the component that was tagged
3197 * @param int|null $contextid the context id of where this tag was assigned
3198 * @return bool|null
3200 function tag_set_delete($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3201 debugging('Function tag_set_delete() is deprecated. Use ' .
3202 ' core_tag_tag::remove_item_tag() instead', DEBUG_DEVELOPER);
3203 return core_tag_tag::remove_item_tag($component, $itemtype, $itemid, $tag);
3207 * Simple function to just return a single tag object when you know the name or something
3209 * See also {@link core_tag_tag::get()} and {@link core_tag_tag::get_by_name()}
3211 * @package core_tag
3212 * @deprecated since 3.1
3213 * @param string $field which field do we use to identify the tag: id, name or rawname
3214 * @param string $value the required value of the aforementioned field
3215 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
3216 * 'id', 'name', 'rawname' or '*' to include all fields.
3217 * @return mixed tag object
3219 function tag_get($field, $value, $returnfields='id, name, rawname, tagcollid') {
3220 global $DB;
3221 debugging('Function tag_get() is deprecated. Use ' .
3222 ' core_tag_tag::get() or core_tag_tag::get_by_name()',
3223 DEBUG_DEVELOPER);
3224 if ($field === 'id') {
3225 $tag = core_tag_tag::get((int)$value, $returnfields);
3226 } else if ($field === 'name') {
3227 $tag = core_tag_tag::get_by_name(0, $value, $returnfields);
3228 } else {
3229 $params = array($field => $value);
3230 return $DB->get_record('tag', $params, $returnfields);
3232 if ($tag) {
3233 return $tag->to_object();
3235 return null;
3239 * Returns tags related to a tag
3241 * Related tags of a tag come from two sources:
3242 * - manually added related tags, which are tag_instance entries for that tag
3243 * - correlated tags, which are calculated
3245 * @package core_tag
3246 * @deprecated since 3.1
3247 * @param string $tagid is a single **normalized** tag name or the id of a tag
3248 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
3249 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
3250 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
3251 * @return array an array of tag objects
3253 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
3254 debugging('Method tag_get_related_tags() is deprecated, '
3255 . 'use core_tag_tag::get_correlated_tags(), core_tag_tag::get_related_tags() or '
3256 . 'core_tag_tag::get_manual_related_tags()', DEBUG_DEVELOPER);
3257 $result = array();
3258 if ($tag = core_tag_tag::get($tagid)) {
3259 if ($type == TAG_RELATED_CORRELATED) {
3260 $tags = $tag->get_correlated_tags();
3261 } else if ($type == TAG_RELATED_MANUAL) {
3262 $tags = $tag->get_manual_related_tags();
3263 } else {
3264 $tags = $tag->get_related_tags();
3266 $tags = array_slice($tags, 0, $limitnum);
3267 foreach ($tags as $id => $tag) {
3268 $result[$id] = $tag->to_object();
3271 return $result;
3275 * Delete one or more tag, and all their instances if there are any left.
3277 * @package core_tag
3278 * @deprecated since 3.1
3279 * @param mixed $tagids one tagid (int), or one array of tagids to delete
3280 * @return bool true on success, false otherwise
3282 function tag_delete($tagids) {
3283 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_tags()',
3284 DEBUG_DEVELOPER);
3285 return core_tag_tag::delete_tags($tagids);
3289 * Deletes all the tag instances given a component and an optional contextid.
3291 * @deprecated since 3.1
3292 * @param string $component
3293 * @param int $contextid if null, then we delete all tag instances for the $component
3295 function tag_delete_instances($component, $contextid = null) {
3296 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_instances()',
3297 DEBUG_DEVELOPER);
3298 core_tag_tag::delete_instances($component, null, $contextid);
3302 * Clean up the tag tables, making sure all tagged object still exists.
3304 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
3305 * 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
3306 * call: don't run at peak time.
3308 * @package core_tag
3309 * @deprecated since 3.1
3311 function tag_cleanup() {
3312 debugging('Method tag_cleanup() is deprecated, use \core\task\tag_cron_task::cleanup()',
3313 DEBUG_DEVELOPER);
3315 $task = new \core\task\tag_cron_task();
3316 return $task->cleanup();
3320 * This function will delete numerous tag instances efficiently.
3321 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
3323 * @deprecated since 3.1
3324 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
3325 * (used for recording a delete event).
3327 function tag_bulk_delete_instances($instances) {
3328 debugging('Method tag_bulk_delete_instances() is deprecated, '
3329 . 'use \core\task\tag_cron_task::bulk_delete_instances()',
3330 DEBUG_DEVELOPER);
3332 $task = new \core\task\tag_cron_task();
3333 return $task->bulk_delete_instances($instances);
3337 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
3339 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
3341 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
3342 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
3344 * @package core_tag
3345 * @deprecated since 3.1
3346 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
3348 function tag_compute_correlations($mincorrelation = 2) {
3349 debugging('Method tag_compute_correlations() is deprecated, '
3350 . 'use \core\task\tag_cron_task::compute_correlations()',
3351 DEBUG_DEVELOPER);
3353 $task = new \core\task\tag_cron_task();
3354 return $task->compute_correlations($mincorrelation);
3358 * This function processes a tag correlation and makes changes in the database as required.
3360 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
3362 * @package core_tag
3363 * @deprecated since 3.1
3364 * @param stdClass $tagcorrelation
3365 * @return int/bool The id of the tag correlation that was just processed or false.
3367 function tag_process_computed_correlation(stdClass $tagcorrelation) {
3368 debugging('Method tag_process_computed_correlation() is deprecated, '
3369 . 'use \core\task\tag_cron_task::process_computed_correlation()',
3370 DEBUG_DEVELOPER);
3372 $task = new \core\task\tag_cron_task();
3373 return $task->process_computed_correlation($tagcorrelation);
3377 * Tasks that should be performed at cron time
3379 * @package core_tag
3380 * @deprecated since 3.1
3382 function tag_cron() {
3383 debugging('Method tag_cron() is deprecated, use \core\task\tag_cron_task::execute()',
3384 DEBUG_DEVELOPER);
3386 $task = new \core\task\tag_cron_task();
3387 $task->execute();
3391 * Search for tags with names that match some text
3393 * @package core_tag
3394 * @deprecated since 3.1
3395 * @param string $text escaped string that the tag names will be matched against
3396 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
3397 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
3398 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
3399 * @param int $tagcollid
3400 * @return array/boolean an array of objects, or false if no records were found or an error occured.
3402 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='', $tagcollid = null) {
3403 debugging('Method tag_find_tags() is deprecated without replacement', DEBUG_DEVELOPER);
3404 global $DB;
3406 $text = core_text::strtolower(clean_param($text, PARAM_TAG));
3408 list($sql, $params) = $DB->get_in_or_equal($tagcollid ? array($tagcollid) :
3409 array_keys(core_tag_collection::get_collections(true)));
3410 array_unshift($params, "%{$text}%");
3412 if ($ordered) {
3413 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid, COUNT(ti.id) AS count
3414 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
3415 WHERE tg.name LIKE ? AND tg.tagcollid $sql
3416 GROUP BY tg.id, tg.name, tg.rawname
3417 ORDER BY count DESC";
3418 } else {
3419 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid
3420 FROM {tag} tg
3421 WHERE tg.name LIKE ? AND tg.tagcollid $sql";
3423 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
3427 * Get the name of a tag
3429 * @package core_tag
3430 * @deprecated since 3.1
3431 * @param mixed $tagids the id of the tag, or an array of ids
3432 * @return mixed string name of one tag, or id-indexed array of strings
3434 function tag_get_name($tagids) {
3435 debugging('Method tag_get_name() is deprecated without replacement', DEBUG_DEVELOPER);
3436 global $DB;
3438 if (!is_array($tagids)) {
3439 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
3440 return $tag->name;
3442 return false;
3445 $tag_names = array();
3446 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
3447 $tag_names[$tag->id] = $tag->name;
3450 return $tag_names;
3454 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
3455 * empty and this function won't return anything.
3457 * Correlated tags are calculated in cron based on existing tag instances.
3459 * @package core_tag
3460 * @deprecated since 3.1
3461 * @param int $tagid is a single tag id
3462 * @param int $notused this argument is no longer used
3463 * @return array an array of tag objects or an empty if no correlated tags are found
3465 function tag_get_correlated($tagid, $notused = null) {
3466 debugging('Method tag_get_correlated() is deprecated, '
3467 . 'use core_tag_tag::get_correlated_tags()', DEBUG_DEVELOPER);
3468 $result = array();
3469 if ($tag = core_tag_tag::get($tagid)) {
3470 $tags = $tag->get_correlated_tags(true);
3471 // Convert to objects for backward-compatibility.
3472 foreach ($tags as $id => $tag) {
3473 $result[$id] = $tag->to_object();
3476 return $result;
3480 * This function is used by print_tag_cloud, to usort() the tags in the cloud. See php.net/usort for the parameters documentation.
3481 * This was originally in blocks/blog_tags/block_blog_tags.php, named blog_tags_sort().
3483 * @package core_tag
3484 * @deprecated since 3.1
3485 * @param string $a Tag name to compare against $b
3486 * @param string $b Tag name to compare against $a
3487 * @return int The result of the comparison/validation 1, 0 or -1
3489 function tag_cloud_sort($a, $b) {
3490 debugging('Method tag_cloud_sort() is deprecated, similar method can be found in core_tag_collection::cloud_sort()', DEBUG_DEVELOPER);
3491 global $CFG;
3493 if (empty($CFG->tagsort)) {
3494 $tagsort = 'name'; // by default, sort by name
3495 } else {
3496 $tagsort = $CFG->tagsort;
3499 if (is_numeric($a->$tagsort)) {
3500 return ($a->$tagsort == $b->$tagsort) ? 0 : ($a->$tagsort > $b->$tagsort) ? 1 : -1;
3501 } elseif (is_string($a->$tagsort)) {
3502 return strcmp($a->$tagsort, $b->$tagsort);
3503 } else {
3504 return 0;
3509 * Loads the events definitions for the component (from file). If no
3510 * events are defined for the component, we simply return an empty array.
3512 * @access protected To be used from eventslib only
3513 * @deprecated since Moodle 3.1
3514 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3515 * @return array Array of capabilities or empty array if not exists
3517 function events_load_def($component) {
3518 global $CFG;
3519 if ($component === 'unittest') {
3520 $defpath = $CFG->dirroot.'/lib/tests/fixtures/events.php';
3521 } else {
3522 $defpath = core_component::get_component_directory($component).'/db/events.php';
3525 $handlers = array();
3527 if (file_exists($defpath)) {
3528 require($defpath);
3531 // make sure the definitions are valid and complete; tell devs what is wrong
3532 foreach ($handlers as $eventname => $handler) {
3533 if ($eventname === 'reset') {
3534 debugging("'reset' can not be used as event name.");
3535 unset($handlers['reset']);
3536 continue;
3538 if (!is_array($handler)) {
3539 debugging("Handler of '$eventname' must be specified as array'");
3540 unset($handlers[$eventname]);
3541 continue;
3543 if (!isset($handler['handlerfile'])) {
3544 debugging("Handler of '$eventname' must include 'handlerfile' key'");
3545 unset($handlers[$eventname]);
3546 continue;
3548 if (!isset($handler['handlerfunction'])) {
3549 debugging("Handler of '$eventname' must include 'handlerfunction' key'");
3550 unset($handlers[$eventname]);
3551 continue;
3553 if (!isset($handler['schedule'])) {
3554 $handler['schedule'] = 'instant';
3556 if ($handler['schedule'] !== 'instant' and $handler['schedule'] !== 'cron') {
3557 debugging("Handler of '$eventname' must include valid 'schedule' type (instant or cron)'");
3558 unset($handlers[$eventname]);
3559 continue;
3561 if (!isset($handler['internal'])) {
3562 $handler['internal'] = 1;
3564 $handlers[$eventname] = $handler;
3567 return $handlers;
3571 * Puts a handler on queue
3573 * @access protected To be used from eventslib only
3574 * @deprecated since Moodle 3.1
3575 * @param stdClass $handler event handler object from db
3576 * @param stdClass $event event data object
3577 * @param string $errormessage The error message indicating the problem
3578 * @return int id number of new queue handler
3580 function events_queue_handler($handler, $event, $errormessage) {
3581 global $DB;
3583 if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id, 'handlerid'=>$handler->id))) {
3584 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
3585 return $qhandler->id;
3588 // make a new queue handler
3589 $qhandler = new stdClass();
3590 $qhandler->queuedeventid = $event->id;
3591 $qhandler->handlerid = $handler->id;
3592 $qhandler->errormessage = $errormessage;
3593 $qhandler->timemodified = time();
3594 if ($handler->schedule === 'instant' and $handler->status == 1) {
3595 $qhandler->status = 1; //already one failed attempt to dispatch this event
3596 } else {
3597 $qhandler->status = 0;
3600 return $DB->insert_record('events_queue_handlers', $qhandler);
3604 * trigger a single event with a specified handler
3606 * @access protected To be used from eventslib only
3607 * @deprecated since Moodle 3.1
3608 * @param stdClass $handler This shoudl be a row from the events_handlers table.
3609 * @param stdClass $eventdata An object containing information about the event
3610 * @param string $errormessage error message indicating problem
3611 * @return bool|null True means event processed, false means retry event later; may throw exception, NULL means internal error
3613 function events_dispatch($handler, $eventdata, &$errormessage) {
3614 global $CFG;
3616 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3618 $function = unserialize($handler->handlerfunction);
3620 if (is_callable($function)) {
3621 // oki, no need for includes
3623 } else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
3624 include_once($CFG->dirroot.$handler->handlerfile);
3626 } else {
3627 $errormessage = "Handler file of component $handler->component: $handler->handlerfile can not be found!";
3628 return null;
3631 // checks for handler validity
3632 if (is_callable($function)) {
3633 $result = call_user_func($function, $eventdata);
3634 if ($result === false) {
3635 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction requested resending of event!";
3636 return false;
3638 return true;
3640 } else {
3641 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction not callable function or class method!";
3642 return null;
3647 * given a queued handler, call the respective event handler to process the event
3649 * @access protected To be used from eventslib only
3650 * @deprecated since Moodle 3.1
3651 * @param stdClass $qhandler events_queued_handler row from db
3652 * @return boolean true means event processed, false means retry later, NULL means fatal failure
3654 function events_process_queued_handler($qhandler) {
3655 global $DB;
3657 // get handler
3658 if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid))) {
3659 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
3660 //irrecoverable error, remove broken queue handler
3661 events_dequeue($qhandler);
3662 return NULL;
3665 // get event object
3666 if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid))) {
3667 // can't proceed with no event object - might happen when two crons running at the same time
3668 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
3669 //irrecoverable error, remove broken queue handler
3670 events_dequeue($qhandler);
3671 return NULL;
3674 // call the function specified by the handler
3675 try {
3676 $errormessage = 'Unknown error';
3677 if (events_dispatch($handler, unserialize(base64_decode($event->eventdata)), $errormessage)) {
3678 //everything ok
3679 events_dequeue($qhandler);
3680 return true;
3682 } catch (Exception $e) {
3683 // the problem here is that we do not want one broken handler to stop all others,
3684 // cron handlers are very tricky because the needed data might have been deleted before the cron execution
3685 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction threw exception :" .
3686 $e->getMessage() . "\n" . format_backtrace($e->getTrace(), true);
3687 if (!empty($e->debuginfo)) {
3688 $errormessage .= $e->debuginfo;
3692 //dispatching failed
3693 $qh = new stdClass();
3694 $qh->id = $qhandler->id;
3695 $qh->errormessage = $errormessage;
3696 $qh->timemodified = time();
3697 $qh->status = $qhandler->status + 1;
3698 $DB->update_record('events_queue_handlers', $qh);
3700 debugging($errormessage);
3702 return false;
3706 * Updates all of the event definitions within the database.
3708 * Unfortunately this isn't as simple as removing them all and then readding
3709 * the updated event definitions. Chances are queued items are referencing the
3710 * existing definitions.
3712 * Note that the absence of the db/events.php event definition file
3713 * will cause any queued events for the component to be removed from
3714 * the database.
3716 * @category event
3717 * @deprecated since Moodle 3.1
3718 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3719 * @return boolean always returns true
3721 function events_update_definition($component='moodle') {
3722 global $DB;
3724 // load event definition from events.php
3725 $filehandlers = events_load_def($component);
3727 if ($filehandlers) {
3728 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3731 // load event definitions from db tables
3732 // if we detect an event being already stored, we discard from this array later
3733 // the remaining needs to be removed
3734 $cachedhandlers = events_get_cached($component);
3736 foreach ($filehandlers as $eventname => $filehandler) {
3737 if (!empty($cachedhandlers[$eventname])) {
3738 if ($cachedhandlers[$eventname]['handlerfile'] === $filehandler['handlerfile'] &&
3739 $cachedhandlers[$eventname]['handlerfunction'] === serialize($filehandler['handlerfunction']) &&
3740 $cachedhandlers[$eventname]['schedule'] === $filehandler['schedule'] &&
3741 $cachedhandlers[$eventname]['internal'] == $filehandler['internal']) {
3742 // exact same event handler already present in db, ignore this entry
3744 unset($cachedhandlers[$eventname]);
3745 continue;
3747 } else {
3748 // same event name matches, this event has been updated, update the datebase
3749 $handler = new stdClass();
3750 $handler->id = $cachedhandlers[$eventname]['id'];
3751 $handler->handlerfile = $filehandler['handlerfile'];
3752 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
3753 $handler->schedule = $filehandler['schedule'];
3754 $handler->internal = $filehandler['internal'];
3756 $DB->update_record('events_handlers', $handler);
3758 unset($cachedhandlers[$eventname]);
3759 continue;
3762 } else {
3763 // if we are here, this event handler is not present in db (new)
3764 // add it
3765 $handler = new stdClass();
3766 $handler->eventname = $eventname;
3767 $handler->component = $component;
3768 $handler->handlerfile = $filehandler['handlerfile'];
3769 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
3770 $handler->schedule = $filehandler['schedule'];
3771 $handler->status = 0;
3772 $handler->internal = $filehandler['internal'];
3774 $DB->insert_record('events_handlers', $handler);
3778 // clean up the left overs, the entries in cached events array at this points are deprecated event handlers
3779 // and should be removed, delete from db
3780 events_cleanup($component, $cachedhandlers);
3782 events_get_handlers('reset');
3784 return true;
3788 * Events cron will try to empty the events queue by processing all the queued events handlers
3790 * @access public Part of the public API
3791 * @deprecated since Moodle 3.1
3792 * @category event
3793 * @param string $eventname empty means all
3794 * @return int number of dispatched events
3796 function events_cron($eventname='') {
3797 global $DB;
3799 $failed = array();
3800 $processed = 0;
3802 if ($eventname) {
3803 $sql = "SELECT qh.*
3804 FROM {events_queue_handlers} qh, {events_handlers} h
3805 WHERE qh.handlerid = h.id AND h.eventname=?
3806 ORDER BY qh.id";
3807 $params = array($eventname);
3808 } else {
3809 $sql = "SELECT *
3810 FROM {events_queue_handlers}
3811 ORDER BY id";
3812 $params = array();
3815 $rs = $DB->get_recordset_sql($sql, $params);
3816 if ($rs->valid()) {
3817 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3820 foreach ($rs as $qhandler) {
3821 if (isset($failed[$qhandler->handlerid])) {
3822 // do not try to dispatch any later events when one already asked for retry or ended with exception
3823 continue;
3825 $status = events_process_queued_handler($qhandler);
3826 if ($status === false) {
3827 // handler is asking for retry, do not send other events to this handler now
3828 $failed[$qhandler->handlerid] = $qhandler->handlerid;
3829 } else if ($status === NULL) {
3830 // means completely broken handler, event data was purged
3831 $failed[$qhandler->handlerid] = $qhandler->handlerid;
3832 } else {
3833 $processed++;
3836 $rs->close();
3838 // remove events that do not have any handlers waiting
3839 $sql = "SELECT eq.id
3840 FROM {events_queue} eq
3841 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
3842 WHERE qh.id IS NULL";
3843 $rs = $DB->get_recordset_sql($sql);
3844 foreach ($rs as $event) {
3845 //debugging('Purging stale event '.$event->id);
3846 $DB->delete_records('events_queue', array('id'=>$event->id));
3848 $rs->close();
3850 return $processed;
3854 * Do not call directly, this is intended to be used from new event base only.
3856 * @private
3857 * @deprecated since Moodle 3.1
3858 * @param string $eventname name of the event
3859 * @param mixed $eventdata event data object
3860 * @return int number of failed events
3862 function events_trigger_legacy($eventname, $eventdata) {
3863 global $CFG, $USER, $DB;
3865 $failedcount = 0; // number of failed events.
3867 // pull out all registered event handlers
3868 if ($handlers = events_get_handlers($eventname)) {
3869 foreach ($handlers as $handler) {
3870 $errormessage = '';
3872 if ($handler->schedule === 'instant') {
3873 if ($handler->status) {
3874 //check if previous pending events processed
3875 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
3876 // ok, queue is empty, lets reset the status back to 0 == ok
3877 $handler->status = 0;
3878 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
3879 // reset static handler cache
3880 events_get_handlers('reset');
3884 // dispatch the event only if instant schedule and status ok
3885 if ($handler->status or (!$handler->internal and $DB->is_transaction_started())) {
3886 // increment the error status counter
3887 $handler->status++;
3888 $DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
3889 // reset static handler cache
3890 events_get_handlers('reset');
3892 } else {
3893 $errormessage = 'Unknown error';
3894 $result = events_dispatch($handler, $eventdata, $errormessage);
3895 if ($result === true) {
3896 // everything is fine - event dispatched
3897 continue;
3898 } else if ($result === false) {
3899 // retry later - set error count to 1 == send next instant into cron queue
3900 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
3901 // reset static handler cache
3902 events_get_handlers('reset');
3903 } else {
3904 // internal problem - ignore the event completely
3905 $failedcount ++;
3906 continue;
3910 // update the failed counter
3911 $failedcount ++;
3913 } else if ($handler->schedule === 'cron') {
3914 //ok - use queueing of events only
3916 } else {
3917 // unknown schedule - ignore event completely
3918 debugging("Unknown handler schedule type: $handler->schedule");
3919 $failedcount ++;
3920 continue;
3923 // if even type is not instant, or dispatch asked for retry, queue it
3924 $event = new stdClass();
3925 $event->userid = $USER->id;
3926 $event->eventdata = base64_encode(serialize($eventdata));
3927 $event->timecreated = time();
3928 if (debugging()) {
3929 $dump = '';
3930 $callers = debug_backtrace();
3931 foreach ($callers as $caller) {
3932 if (!isset($caller['line'])) {
3933 $caller['line'] = '?';
3935 if (!isset($caller['file'])) {
3936 $caller['file'] = '?';
3938 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
3939 if (isset($caller['function'])) {
3940 $dump .= ': call to ';
3941 if (isset($caller['class'])) {
3942 $dump .= $caller['class'] . $caller['type'];
3944 $dump .= $caller['function'] . '()';
3946 $dump .= "\n";
3948 $event->stackdump = $dump;
3949 } else {
3950 $event->stackdump = '';
3952 $event->id = $DB->insert_record('events_queue', $event);
3953 events_queue_handler($handler, $event, $errormessage);
3955 } else {
3956 // No handler found for this event name - this is ok!
3959 return $failedcount;
3963 * checks if an event is registered for this component
3965 * @access public Part of the public API
3966 * @deprecated since Moodle 3.1
3967 * @param string $eventname name of the event
3968 * @param string $component component name, can be mod/data or moodle
3969 * @return bool
3971 function events_is_registered($eventname, $component) {
3972 global $DB;
3974 debugging('events_is_registered() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3975 ' please use it instead.', DEBUG_DEVELOPER);
3977 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
3981 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
3983 * @access public Part of the public API
3984 * @deprecated since Moodle 3.1
3985 * @param string $eventname name of the event
3986 * @return int number of queued events
3988 function events_pending_count($eventname) {
3989 global $DB;
3991 debugging('events_pending_count() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3992 ' please use it instead.', DEBUG_DEVELOPER);
3994 $sql = "SELECT COUNT('x')
3995 FROM {events_queue_handlers} qh
3996 JOIN {events_handlers} h ON h.id = qh.handlerid
3997 WHERE h.eventname = ?";
3999 return $DB->count_records_sql($sql, array($eventname));
4003 * Emails admins about a clam outcome
4005 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
4006 * @param string $notice The body of the email to be sent.
4007 * @return void
4009 function clam_message_admins($notice) {
4010 debugging('clam_message_admins() is deprecated, please use message_admins() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
4012 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
4013 $antivirus->message_admins($notice);
4017 * Returns the string equivalent of a numeric clam error code
4019 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
4020 * @param int $returncode The numeric error code in question.
4021 * @return string The definition of the error code
4023 function get_clam_error_code($returncode) {
4024 debugging('get_clam_error_code() is deprecated, please use get_clam_error_code() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
4026 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
4027 return $antivirus->get_clam_error_code($returncode);
4031 * Returns the rename action.
4033 * @deprecated since 3.1
4034 * @param cm_info $mod The module to produce editing buttons for
4035 * @param int $sr The section to link back to (used for creating the links)
4036 * @return The markup for the rename action, or an empty string if not available.
4038 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
4039 global $COURSE, $OUTPUT;
4041 static $str;
4042 static $baseurl;
4044 debugging('Function course_get_cm_rename_action() is deprecated. Please use inplace_editable ' .
4045 'https://docs.moodle.org/dev/Inplace_editable', DEBUG_DEVELOPER);
4047 $modcontext = context_module::instance($mod->id);
4048 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
4050 if (!isset($str)) {
4051 $str = get_strings(array('edittitle'));
4054 if (!isset($baseurl)) {
4055 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
4058 if ($sr !== null) {
4059 $baseurl->param('sr', $sr);
4062 // AJAX edit title.
4063 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
4064 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
4065 // we will not display link if we are on some other-course page (where we should not see this module anyway)
4066 return html_writer::span(
4067 html_writer::link(
4068 new moodle_url($baseurl, array('update' => $mod->id)),
4069 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
4070 array(
4071 'class' => 'editing_title',
4072 'data-action' => 'edittitle',
4073 'title' => $str->edittitle,
4078 return '';
4082 * This function returns the number of activities using the given scale in the given course.
4084 * @deprecated since Moodle 3.1
4085 * @param int $courseid The course ID to check.
4086 * @param int $scaleid The scale ID to check
4087 * @return int
4089 function course_scale_used($courseid, $scaleid) {
4090 global $CFG, $DB;
4092 debugging('course_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4093 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4095 $return = 0;
4097 if (!empty($scaleid)) {
4098 if ($cms = get_course_mods($courseid)) {
4099 foreach ($cms as $cm) {
4100 // Check cm->name/lib.php exists.
4101 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
4102 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
4103 $functionname = $cm->modname.'_scale_used';
4104 if (function_exists($functionname)) {
4105 if ($functionname($cm->instance, $scaleid)) {
4106 $return++;
4113 // Check if any course grade item makes use of the scale.
4114 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
4116 // Check if any outcome in the course makes use of the scale.
4117 $return += $DB->count_records_sql("SELECT COUNT('x')
4118 FROM {grade_outcomes_courses} goc,
4119 {grade_outcomes} go
4120 WHERE go.id = goc.outcomeid
4121 AND go.scaleid = ? AND goc.courseid = ?",
4122 array($scaleid, $courseid));
4124 return $return;
4128 * This function returns the number of activities using scaleid in the entire site
4130 * @deprecated since Moodle 3.1
4131 * @param int $scaleid
4132 * @param array $courses
4133 * @return int
4135 function site_scale_used($scaleid, &$courses) {
4136 $return = 0;
4138 debugging('site_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4139 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4141 if (!is_array($courses) || count($courses) == 0) {
4142 $courses = get_courses("all", false, "c.id, c.shortname");
4145 if (!empty($scaleid)) {
4146 if (is_array($courses) && count($courses) > 0) {
4147 foreach ($courses as $course) {
4148 $return += course_scale_used($course->id, $scaleid);
4152 return $return;
4156 * Returns detailed function information
4158 * @deprecated since Moodle 3.1
4159 * @param string|object $function name of external function or record from external_function
4160 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4161 * MUST_EXIST means throw exception if no record or multiple records found
4162 * @return stdClass description or false if not found or exception thrown
4163 * @since Moodle 2.0
4165 function external_function_info($function, $strictness=MUST_EXIST) {
4166 debugging('external_function_info() is deprecated. Please use external_api::external_function_info() instead.',
4167 DEBUG_DEVELOPER);
4168 return external_api::external_function_info($function, $strictness);
4172 * Retrieves an array of records from a CSV file and places
4173 * them into a given table structure
4174 * This function is deprecated. Please use csv_import_reader() instead.
4176 * @deprecated since Moodle 3.2 MDL-55126
4177 * @todo MDL-55195 for final deprecation in Moodle 3.6
4178 * @see csv_import_reader::load_csv_content()
4179 * @global stdClass $CFG
4180 * @global moodle_database $DB
4181 * @param string $file The path to a CSV file
4182 * @param string $table The table to retrieve columns from
4183 * @return bool|array Returns an array of CSV records or false
4185 function get_records_csv($file, $table) {
4186 global $CFG, $DB;
4188 debugging('get_records_csv() is deprecated. Please use lib/csvlib.class.php csv_import_reader() instead.');
4190 if (!$metacolumns = $DB->get_columns($table)) {
4191 return false;
4194 if(!($handle = @fopen($file, 'r'))) {
4195 print_error('get_records_csv failed to open '.$file);
4198 $fieldnames = fgetcsv($handle, 4096);
4199 if(empty($fieldnames)) {
4200 fclose($handle);
4201 return false;
4204 $columns = array();
4206 foreach($metacolumns as $metacolumn) {
4207 $ord = array_search($metacolumn->name, $fieldnames);
4208 if(is_int($ord)) {
4209 $columns[$metacolumn->name] = $ord;
4213 $rows = array();
4215 while (($data = fgetcsv($handle, 4096)) !== false) {
4216 $item = new stdClass;
4217 foreach($columns as $name => $ord) {
4218 $item->$name = $data[$ord];
4220 $rows[] = $item;
4223 fclose($handle);
4224 return $rows;
4228 * Create a file with CSV contents
4229 * This function is deprecated. Please use download_as_dataformat() instead.
4231 * @deprecated since Moodle 3.2 MDL-55126
4232 * @todo MDL-55195 for final deprecation in Moodle 3.6
4233 * @see download_as_dataformat (lib/dataformatlib.php)
4234 * @global stdClass $CFG
4235 * @global moodle_database $DB
4236 * @param string $file The file to put the CSV content into
4237 * @param array $records An array of records to write to a CSV file
4238 * @param string $table The table to get columns from
4239 * @return bool success
4241 function put_records_csv($file, $records, $table = NULL) {
4242 global $CFG, $DB;
4244 debugging('put_records_csv() is deprecated. Please use lib/dataformatlib.php download_as_dataformat()');
4246 if (empty($records)) {
4247 return true;
4250 $metacolumns = NULL;
4251 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
4252 return false;
4255 echo "x";
4257 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
4258 print_error('put_records_csv failed to open '.$file);
4261 $proto = reset($records);
4262 if(is_object($proto)) {
4263 $fields_records = array_keys(get_object_vars($proto));
4265 else if(is_array($proto)) {
4266 $fields_records = array_keys($proto);
4268 else {
4269 return false;
4271 echo "x";
4273 if(!empty($metacolumns)) {
4274 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
4275 $fields = array_intersect($fields_records, $fields_table);
4277 else {
4278 $fields = $fields_records;
4281 fwrite($fp, implode(',', $fields));
4282 fwrite($fp, "\r\n");
4284 foreach($records as $record) {
4285 $array = (array)$record;
4286 $values = array();
4287 foreach($fields as $field) {
4288 if(strpos($array[$field], ',')) {
4289 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
4291 else {
4292 $values[] = $array[$field];
4295 fwrite($fp, implode(',', $values)."\r\n");
4298 fclose($fp);
4299 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
4300 return true;
4304 * Determines if the given value is a valid CSS colour.
4306 * A CSS colour can be one of the following:
4307 * - Hex colour: #AA66BB
4308 * - RGB colour: rgb(0-255, 0-255, 0-255)
4309 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
4310 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
4311 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
4313 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
4315 * @deprecated since Moodle 3.2
4316 * @todo MDL-56173 for final deprecation in Moodle 3.6
4317 * @param string $value The colour value to check
4318 * @return bool
4320 function css_is_colour($value) {
4321 debugging('css_is_colour() is deprecated without a replacement. Please copy the implementation '.
4322 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4324 $value = trim($value);
4326 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
4327 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
4328 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4329 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
4330 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4332 if (in_array(strtolower($value), array('inherit'))) {
4333 return true;
4334 } else if (preg_match($hex, $value)) {
4335 return true;
4336 } else if (in_array(strtolower($value), array_keys(css_optimiser::$htmlcolours))) {
4337 return true;
4338 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4339 // It is an RGB colour.
4340 return true;
4341 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4342 // It is an RGBA colour.
4343 return true;
4344 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4345 // It is an HSL colour.
4346 return true;
4347 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4348 // It is an HSLA colour.
4349 return true;
4351 // Doesn't look like a colour.
4352 return false;
4356 * Returns true is the passed value looks like a CSS width.
4357 * In order to pass this test the value must be purely numerical or end with a
4358 * valid CSS unit term.
4360 * @param string|int $value
4361 * @return boolean
4362 * @deprecated since Moodle 3.2
4363 * @todo MDL-56173 for final deprecation in Moodle 3.6
4365 function css_is_width($value) {
4366 debugging('css_is_width() is deprecated without a replacement. Please copy the implementation '.
4367 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4369 $value = trim($value);
4370 if (in_array(strtolower($value), array('auto', 'inherit'))) {
4371 return true;
4373 if ((string)$value === '0' || preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
4374 return true;
4376 return false;
4380 * A simple sorting function to sort two array values on the number of items they contain
4382 * @param array $a
4383 * @param array $b
4384 * @return int
4385 * @deprecated since Moodle 3.2
4386 * @todo MDL-56173 for final deprecation in Moodle 3.6
4388 function css_sort_by_count(array $a, array $b) {
4389 debugging('css_sort_by_count() is deprecated without a replacement. Please copy the implementation '.
4390 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4392 $a = count($a);
4393 $b = count($b);
4394 if ($a == $b) {
4395 return 0;
4397 return ($a > $b) ? -1 : 1;
4401 * A basic CSS optimiser that strips out unwanted things and then processes CSS organising and cleaning styles.
4402 * @deprecated since Moodle 3.2
4403 * @todo MDL-56173 for final deprecation in Moodle 3.6
4405 class css_optimiser {
4407 * An array of the common HTML colours that are supported by most browsers.
4409 * This reference table is used to allow us to unify colours, and will aid
4410 * us in identifying buggy CSS using unsupported colours.
4412 * @var string[]
4413 * @deprecated since Moodle 3.2
4414 * @todo MDL-56173 for final deprecation in Moodle 3.6
4416 public static $htmlcolours = array(
4417 'aliceblue' => '#F0F8FF',
4418 'antiquewhite' => '#FAEBD7',
4419 'aqua' => '#00FFFF',
4420 'aquamarine' => '#7FFFD4',
4421 'azure' => '#F0FFFF',
4422 'beige' => '#F5F5DC',
4423 'bisque' => '#FFE4C4',
4424 'black' => '#000000',
4425 'blanchedalmond' => '#FFEBCD',
4426 'blue' => '#0000FF',
4427 'blueviolet' => '#8A2BE2',
4428 'brown' => '#A52A2A',
4429 'burlywood' => '#DEB887',
4430 'cadetblue' => '#5F9EA0',
4431 'chartreuse' => '#7FFF00',
4432 'chocolate' => '#D2691E',
4433 'coral' => '#FF7F50',
4434 'cornflowerblue' => '#6495ED',
4435 'cornsilk' => '#FFF8DC',
4436 'crimson' => '#DC143C',
4437 'cyan' => '#00FFFF',
4438 'darkblue' => '#00008B',
4439 'darkcyan' => '#008B8B',
4440 'darkgoldenrod' => '#B8860B',
4441 'darkgray' => '#A9A9A9',
4442 'darkgrey' => '#A9A9A9',
4443 'darkgreen' => '#006400',
4444 'darkKhaki' => '#BDB76B',
4445 'darkmagenta' => '#8B008B',
4446 'darkolivegreen' => '#556B2F',
4447 'arkorange' => '#FF8C00',
4448 'darkorchid' => '#9932CC',
4449 'darkred' => '#8B0000',
4450 'darksalmon' => '#E9967A',
4451 'darkseagreen' => '#8FBC8F',
4452 'darkslateblue' => '#483D8B',
4453 'darkslategray' => '#2F4F4F',
4454 'darkslategrey' => '#2F4F4F',
4455 'darkturquoise' => '#00CED1',
4456 'darkviolet' => '#9400D3',
4457 'deeppink' => '#FF1493',
4458 'deepskyblue' => '#00BFFF',
4459 'dimgray' => '#696969',
4460 'dimgrey' => '#696969',
4461 'dodgerblue' => '#1E90FF',
4462 'firebrick' => '#B22222',
4463 'floralwhite' => '#FFFAF0',
4464 'forestgreen' => '#228B22',
4465 'fuchsia' => '#FF00FF',
4466 'gainsboro' => '#DCDCDC',
4467 'ghostwhite' => '#F8F8FF',
4468 'gold' => '#FFD700',
4469 'goldenrod' => '#DAA520',
4470 'gray' => '#808080',
4471 'grey' => '#808080',
4472 'green' => '#008000',
4473 'greenyellow' => '#ADFF2F',
4474 'honeydew' => '#F0FFF0',
4475 'hotpink' => '#FF69B4',
4476 'indianred ' => '#CD5C5C',
4477 'indigo ' => '#4B0082',
4478 'ivory' => '#FFFFF0',
4479 'khaki' => '#F0E68C',
4480 'lavender' => '#E6E6FA',
4481 'lavenderblush' => '#FFF0F5',
4482 'lawngreen' => '#7CFC00',
4483 'lemonchiffon' => '#FFFACD',
4484 'lightblue' => '#ADD8E6',
4485 'lightcoral' => '#F08080',
4486 'lightcyan' => '#E0FFFF',
4487 'lightgoldenrodyellow' => '#FAFAD2',
4488 'lightgray' => '#D3D3D3',
4489 'lightgrey' => '#D3D3D3',
4490 'lightgreen' => '#90EE90',
4491 'lightpink' => '#FFB6C1',
4492 'lightsalmon' => '#FFA07A',
4493 'lightseagreen' => '#20B2AA',
4494 'lightskyblue' => '#87CEFA',
4495 'lightslategray' => '#778899',
4496 'lightslategrey' => '#778899',
4497 'lightsteelblue' => '#B0C4DE',
4498 'lightyellow' => '#FFFFE0',
4499 'lime' => '#00FF00',
4500 'limegreen' => '#32CD32',
4501 'linen' => '#FAF0E6',
4502 'magenta' => '#FF00FF',
4503 'maroon' => '#800000',
4504 'mediumaquamarine' => '#66CDAA',
4505 'mediumblue' => '#0000CD',
4506 'mediumorchid' => '#BA55D3',
4507 'mediumpurple' => '#9370D8',
4508 'mediumseagreen' => '#3CB371',
4509 'mediumslateblue' => '#7B68EE',
4510 'mediumspringgreen' => '#00FA9A',
4511 'mediumturquoise' => '#48D1CC',
4512 'mediumvioletred' => '#C71585',
4513 'midnightblue' => '#191970',
4514 'mintcream' => '#F5FFFA',
4515 'mistyrose' => '#FFE4E1',
4516 'moccasin' => '#FFE4B5',
4517 'navajowhite' => '#FFDEAD',
4518 'navy' => '#000080',
4519 'oldlace' => '#FDF5E6',
4520 'olive' => '#808000',
4521 'olivedrab' => '#6B8E23',
4522 'orange' => '#FFA500',
4523 'orangered' => '#FF4500',
4524 'orchid' => '#DA70D6',
4525 'palegoldenrod' => '#EEE8AA',
4526 'palegreen' => '#98FB98',
4527 'paleturquoise' => '#AFEEEE',
4528 'palevioletred' => '#D87093',
4529 'papayawhip' => '#FFEFD5',
4530 'peachpuff' => '#FFDAB9',
4531 'peru' => '#CD853F',
4532 'pink' => '#FFC0CB',
4533 'plum' => '#DDA0DD',
4534 'powderblue' => '#B0E0E6',
4535 'purple' => '#800080',
4536 'red' => '#FF0000',
4537 'rosybrown' => '#BC8F8F',
4538 'royalblue' => '#4169E1',
4539 'saddlebrown' => '#8B4513',
4540 'salmon' => '#FA8072',
4541 'sandybrown' => '#F4A460',
4542 'seagreen' => '#2E8B57',
4543 'seashell' => '#FFF5EE',
4544 'sienna' => '#A0522D',
4545 'silver' => '#C0C0C0',
4546 'skyblue' => '#87CEEB',
4547 'slateblue' => '#6A5ACD',
4548 'slategray' => '#708090',
4549 'slategrey' => '#708090',
4550 'snow' => '#FFFAFA',
4551 'springgreen' => '#00FF7F',
4552 'steelblue' => '#4682B4',
4553 'tan' => '#D2B48C',
4554 'teal' => '#008080',
4555 'thistle' => '#D8BFD8',
4556 'tomato' => '#FF6347',
4557 'transparent' => 'transparent',
4558 'turquoise' => '#40E0D0',
4559 'violet' => '#EE82EE',
4560 'wheat' => '#F5DEB3',
4561 'white' => '#FFFFFF',
4562 'whitesmoke' => '#F5F5F5',
4563 'yellow' => '#FFFF00',
4564 'yellowgreen' => '#9ACD32'
4568 * Used to orocesses incoming CSS optimising it and then returning it. Now just returns
4569 * what is sent to it. Do not use.
4571 * @param string $css The raw CSS to optimise
4572 * @return string The optimised CSS
4573 * @deprecated since Moodle 3.2
4574 * @todo MDL-56173 for final deprecation in Moodle 3.6
4576 public function process($css) {
4577 debugging('class css_optimiser is deprecated and no longer does anything, '.
4578 'please consider using stylelint to optimise your css.', DEBUG_DEVELOPER);
4580 return $css;
4585 * Load the course contexts for all of the users courses
4587 * @deprecated since Moodle 3.2
4588 * @param array $courses array of course objects. The courses the user is enrolled in.
4589 * @return array of course contexts
4591 function message_get_course_contexts($courses) {
4592 debugging('message_get_course_contexts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4594 $coursecontexts = array();
4596 foreach($courses as $course) {
4597 $coursecontexts[$course->id] = context_course::instance($course->id);
4600 return $coursecontexts;
4604 * strip off action parameters like 'removecontact'
4606 * @deprecated since Moodle 3.2
4607 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
4608 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
4610 function message_remove_url_params($moodleurl) {
4611 debugging('message_remove_url_params() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4613 $newurl = new moodle_url($moodleurl);
4614 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
4615 return $newurl->out();
4619 * Count the number of messages with a field having a specified value.
4620 * if $field is empty then return count of the whole array
4621 * if $field is non-existent then return 0
4623 * @deprecated since Moodle 3.2
4624 * @param array $messagearray array of message objects
4625 * @param string $field the field to inspect on the message objects
4626 * @param string $value the value to test the field against
4628 function message_count_messages($messagearray, $field='', $value='') {
4629 debugging('message_count_messages() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4631 if (!is_array($messagearray)) return 0;
4632 if ($field == '' or empty($messagearray)) return count($messagearray);
4634 $count = 0;
4635 foreach ($messagearray as $message) {
4636 $count += ($message->$field == $value) ? 1 : 0;
4638 return $count;
4642 * Count the number of users blocked by $user1
4644 * @deprecated since Moodle 3.2
4645 * @param object $user1 user object
4646 * @return int the number of blocked users
4648 function message_count_blocked_users($user1=null) {
4649 debugging('message_count_blocked_users() is deprecated, please use \core_message\api::count_blocked_users() instead.',
4650 DEBUG_DEVELOPER);
4652 return \core_message\api::count_blocked_users($user1);
4656 * Print a message contact link
4658 * @deprecated since Moodle 3.2
4659 * @param int $userid the ID of the user to apply to action to
4660 * @param string $linktype can be add, remove, block or unblock
4661 * @param bool $return if true return the link as a string. If false echo the link.
4662 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4663 * @param bool $text include text next to the icons?
4664 * @param bool $icon include a graphical icon?
4665 * @return string if $return is true otherwise bool
4667 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
4668 debugging('message_contact_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4670 global $OUTPUT, $PAGE;
4672 //hold onto the strings as we're probably creating a bunch of links
4673 static $str;
4675 if (empty($script)) {
4676 //strip off previous action params like 'removecontact'
4677 $script = message_remove_url_params($PAGE->url);
4680 if (empty($str->blockcontact)) {
4681 $str = new stdClass();
4682 $str->blockcontact = get_string('blockcontact', 'message');
4683 $str->unblockcontact = get_string('unblockcontact', 'message');
4684 $str->removecontact = get_string('removecontact', 'message');
4685 $str->addcontact = get_string('addcontact', 'message');
4688 $command = $linktype.'contact';
4689 $string = $str->{$command};
4691 $safealttext = s($string);
4693 $safestring = '';
4694 if (!empty($text)) {
4695 $safestring = $safealttext;
4698 $img = '';
4699 if ($icon) {
4700 $iconpath = null;
4701 switch ($linktype) {
4702 case 'block':
4703 $iconpath = 't/block';
4704 break;
4705 case 'unblock':
4706 $iconpath = 't/unblock';
4707 break;
4708 case 'remove':
4709 $iconpath = 't/removecontact';
4710 break;
4711 case 'add':
4712 default:
4713 $iconpath = 't/addcontact';
4716 $img = $OUTPUT->pix_icon($iconpath, $safealttext);
4719 $output = '<span class="'.$linktype.'contact">'.
4720 '<a href="'.$script.'&amp;'.$command.'='.$userid.
4721 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
4722 $img.
4723 $safestring.'</a></span>';
4725 if ($return) {
4726 return $output;
4727 } else {
4728 echo $output;
4729 return true;
4734 * Get the users recent event notifications
4736 * @deprecated since Moodle 3.2
4737 * @param object $user the current user
4738 * @param int $limitfrom can be used for paging
4739 * @param int $limitto can be used for paging
4740 * @return array
4742 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
4743 debugging('message_get_recent_notifications() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4745 global $DB;
4747 $userfields = user_picture::fields('u', array('lastaccess'));
4748 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
4749 FROM {message_read} mr
4750 JOIN {user} u ON u.id=mr.useridfrom
4751 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
4752 ORDER BY mr.timecreated DESC";
4753 $params = array('userid1' => $user->id, 'notification' => 1);
4755 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
4756 return $notifications;
4760 * echo or return a link to take the user to the full message history between themselves and another user
4762 * @deprecated since Moodle 3.2
4763 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
4764 * @param int $userid2 the ID of the other user
4765 * @param bool $return true to return the link as a string. False to echo the link.
4766 * @param string $keywords any keywords to highlight in the message history
4767 * @param string $position anchor name to jump to within the message history
4768 * @param string $linktext optionally specify the link text
4769 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
4771 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
4772 debugging('message_history_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4774 global $OUTPUT, $PAGE;
4775 static $strmessagehistory;
4777 if (empty($strmessagehistory)) {
4778 $strmessagehistory = get_string('messagehistory', 'message');
4781 if ($position) {
4782 $position = "#$position";
4784 if ($keywords) {
4785 $keywords = "&search=".urlencode($keywords);
4788 if ($linktext == 'icon') { // Icon only
4789 $fulllink = $OUTPUT->pix_icon('t/messages', $strmessagehistory);
4790 } else if ($linktext == 'both') { // Icon and standard name
4791 $fulllink = $OUTPUT->pix_icon('t/messages', '');
4792 $fulllink .= '&nbsp;'.$strmessagehistory;
4793 } else if ($linktext) { // Custom name
4794 $fulllink = $linktext;
4795 } else { // Standard name only
4796 $fulllink = $strmessagehistory;
4799 $popupoptions = array(
4800 'height' => 500,
4801 'width' => 500,
4802 'menubar' => false,
4803 'location' => false,
4804 'status' => true,
4805 'scrollbars' => true,
4806 'resizable' => true);
4808 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
4809 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
4810 $link->param('viewing', $PAGE->url->get_param('viewing'));
4812 $action = null;
4813 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
4815 $str = '<span class="history">'.$str.'</span>';
4817 if ($return) {
4818 return $str;
4819 } else {
4820 echo $str;
4821 return true;
4826 * Search a user's messages
4828 * Returns a list of posts found using an array of search terms
4829 * eg word +word -word
4831 * @deprecated since Moodle 3.2
4832 * @param array $searchterms an array of search terms (strings)
4833 * @param bool $fromme include messages from the user?
4834 * @param bool $tome include messages to the user?
4835 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
4836 * @param int $userid the user ID of the current user
4837 * @return mixed An array of messages or false if no matching messages were found
4839 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
4840 debugging('message_search() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4842 global $CFG, $USER, $DB;
4844 // If user is searching all messages check they are allowed to before doing anything else.
4845 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
4846 print_error('accessdenied','admin');
4849 // If no userid sent then assume current user.
4850 if ($userid == 0) $userid = $USER->id;
4852 // Some differences in SQL syntax.
4853 if ($DB->sql_regex_supported()) {
4854 $REGEXP = $DB->sql_regex(true);
4855 $NOTREGEXP = $DB->sql_regex(false);
4858 $searchcond = array();
4859 $params = array();
4860 $i = 0;
4862 // Preprocess search terms to check whether we have at least 1 eligible search term.
4863 // If we do we can drop words around it like 'a'.
4864 $dropshortwords = false;
4865 foreach ($searchterms as $searchterm) {
4866 if (strlen($searchterm) >= 2) {
4867 $dropshortwords = true;
4871 foreach ($searchterms as $searchterm) {
4872 $i++;
4874 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
4876 if ($dropshortwords && strlen($searchterm) < 2) {
4877 continue;
4879 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
4880 if (!$DB->sql_regex_supported()) {
4881 if (substr($searchterm, 0, 1) == '-') {
4882 $NOT = true;
4884 $searchterm = trim($searchterm, '+-');
4887 if (substr($searchterm,0,1) == "+") {
4888 $searchterm = substr($searchterm,1);
4889 $searchterm = preg_quote($searchterm, '|');
4890 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
4891 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
4893 } else if (substr($searchterm,0,1) == "-") {
4894 $searchterm = substr($searchterm,1);
4895 $searchterm = preg_quote($searchterm, '|');
4896 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
4897 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
4899 } else {
4900 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
4901 $params['ss'.$i] = "%$searchterm%";
4905 if (empty($searchcond)) {
4906 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
4907 $params['ss1'] = "%";
4908 } else {
4909 $searchcond = implode(" AND ", $searchcond);
4912 // There are several possibilities
4913 // 1. courseid = SITEID : The admin is searching messages by all users
4914 // 2. courseid = ?? : A teacher is searching messages by users in
4915 // one of their courses - currently disabled
4916 // 3. courseid = none : User is searching their own messages;
4917 // a. Messages from user
4918 // b. Messages to user
4919 // c. Messages to and from user
4921 if ($fromme && $tome) {
4922 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
4923 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
4924 $params['useridto'] = $userid;
4925 $params['useridfrom'] = $userid;
4926 } else if ($fromme) {
4927 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
4928 $params['useridfrom'] = $userid;
4929 } else if ($tome) {
4930 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
4931 $params['useridto'] = $userid;
4933 if ($courseid == SITEID) { // Admin is searching all messages.
4934 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4935 FROM {message_read} m
4936 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
4937 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4938 FROM {message} m
4939 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
4941 } else if ($courseid !== 'none') {
4942 // This has not been implemented due to security concerns.
4943 $m_read = array();
4944 $m_unread = array();
4946 } else {
4948 if ($fromme and $tome) {
4949 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
4950 $params['userid1'] = $userid;
4951 $params['userid2'] = $userid;
4953 } else if ($fromme) {
4954 $searchcond .= " AND m.useridfrom=:userid";
4955 $params['userid'] = $userid;
4957 } else if ($tome) {
4958 $searchcond .= " AND m.useridto=:userid";
4959 $params['userid'] = $userid;
4962 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4963 FROM {message_read} m
4964 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
4965 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4966 FROM {message} m
4967 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
4971 /// The keys may be duplicated in $m_read and $m_unread so we can't
4972 /// do a simple concatenation
4973 $messages = array();
4974 foreach ($m_read as $m) {
4975 $messages[] = $m;
4977 foreach ($m_unread as $m) {
4978 $messages[] = $m;
4981 return (empty($messages)) ? false : $messages;
4985 * Given a message object that we already know has a long message
4986 * this function truncates the message nicely to the first
4987 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
4989 * @deprecated since Moodle 3.2
4990 * @param string $message the message
4991 * @param int $minlength the minimum length to trim the message to
4992 * @return string the shortened message
4994 function message_shorten_message($message, $minlength = 0) {
4995 debugging('message_shorten_message() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4997 $i = 0;
4998 $tag = false;
4999 $length = strlen($message);
5000 $count = 0;
5001 $stopzone = false;
5002 $truncate = 0;
5003 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
5006 for ($i=0; $i<$length; $i++) {
5007 $char = $message[$i];
5009 switch ($char) {
5010 case "<":
5011 $tag = true;
5012 break;
5013 case ">":
5014 $tag = false;
5015 break;
5016 default:
5017 if (!$tag) {
5018 if ($stopzone) {
5019 if ($char == '.' or $char == ' ') {
5020 $truncate = $i+1;
5021 break 2;
5024 $count++;
5026 break;
5028 if (!$stopzone) {
5029 if ($count > $minlength) {
5030 $stopzone = true;
5035 if (!$truncate) {
5036 $truncate = $i;
5039 return substr($message, 0, $truncate);
5043 * Given a string and an array of keywords, this function looks
5044 * for the first keyword in the string, and then chops out a
5045 * small section from the text that shows that word in context.
5047 * @deprecated since Moodle 3.2
5048 * @param string $message the text to search
5049 * @param array $keywords array of keywords to find
5051 function message_get_fragment($message, $keywords) {
5052 debugging('message_get_fragment() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5054 $fullsize = 160;
5055 $halfsize = (int)($fullsize/2);
5057 $message = strip_tags($message);
5059 foreach ($keywords as $keyword) { // Just get the first one
5060 if ($keyword !== '') {
5061 break;
5064 if (empty($keyword)) { // None found, so just return start of message
5065 return message_shorten_message($message, 30);
5068 $leadin = $leadout = '';
5070 /// Find the start of the fragment
5071 $start = 0;
5072 $length = strlen($message);
5074 $pos = strpos($message, $keyword);
5075 if ($pos > $halfsize) {
5076 $start = $pos - $halfsize;
5077 $leadin = '...';
5079 /// Find the end of the fragment
5080 $end = $start + $fullsize;
5081 if ($end > $length) {
5082 $end = $length;
5083 } else {
5084 $leadout = '...';
5087 /// Pull out the fragment and format it
5089 $fragment = substr($message, $start, $end - $start);
5090 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
5091 return $fragment;
5095 * Retrieve the messages between two users
5097 * @deprecated since Moodle 3.2
5098 * @param object $user1 the current user
5099 * @param object $user2 the other user
5100 * @param int $limitnum the maximum number of messages to retrieve
5101 * @param bool $viewingnewmessages are we currently viewing new messages?
5103 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
5104 debugging('message_get_history() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5106 global $DB, $CFG;
5108 $messages = array();
5110 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
5111 //desc to get the last $limitnum messages then flip the order in php
5112 $sort = 'asc';
5113 if ($limitnum>0) {
5114 $sort = 'desc';
5117 $notificationswhere = null;
5118 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
5119 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
5120 $notificationswhere = 'AND notification=0';
5123 //prevent notifications of your own actions appearing in your own message history
5124 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
5126 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
5127 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
5128 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
5129 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
5130 "timecreated $sort", '*', 0, $limitnum)) {
5131 foreach ($messages_read as $message) {
5132 $messages[] = $message;
5135 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
5136 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
5137 "timecreated $sort", '*', 0, $limitnum)) {
5138 foreach ($messages_new as $message) {
5139 $messages[] = $message;
5143 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
5145 //if we only want the last $limitnum messages
5146 $messagecount = count($messages);
5147 if ($limitnum > 0 && $messagecount > $limitnum) {
5148 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
5151 return $messages;
5155 * Constructs the add/remove contact link to display next to other users
5157 * @deprecated since Moodle 3.2
5158 * @param bool $incontactlist is the user a contact
5159 * @param bool $isblocked is the user blocked
5160 * @param stdClass $contact contact object
5161 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5162 * @param bool $text include text next to the icons?
5163 * @param bool $icon include a graphical icon?
5164 * @return string
5166 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5167 debugging('message_get_contact_add_remove_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5169 $strcontact = '';
5171 if($incontactlist){
5172 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
5173 } else if ($isblocked) {
5174 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
5175 } else{
5176 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
5179 return $strcontact;
5183 * Constructs the block contact link to display next to other users
5185 * @deprecated since Moodle 3.2
5186 * @param bool $incontactlist is the user a contact?
5187 * @param bool $isblocked is the user blocked?
5188 * @param stdClass $contact contact object
5189 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5190 * @param bool $text include text next to the icons?
5191 * @param bool $icon include a graphical icon?
5192 * @return string
5194 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5195 debugging('message_get_contact_block_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5197 $strblock = '';
5199 //commented out to allow the user to block a contact without having to remove them first
5200 /*if ($incontactlist) {
5201 //$strblock = '';
5202 } else*/
5203 if ($isblocked) {
5204 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
5205 } else{
5206 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
5209 return $strblock;
5213 * marks ALL messages being sent from $fromuserid to $touserid as read
5215 * @deprecated since Moodle 3.2
5216 * @param int $touserid the id of the message recipient
5217 * @param int $fromuserid the id of the message sender
5218 * @return void
5220 function message_mark_messages_read($touserid, $fromuserid) {
5221 debugging('message_mark_messages_read() is deprecated and is no longer used, please use
5222 \core_message\api::mark_all_read_for_user() instead.', DEBUG_DEVELOPER);
5224 \core_message\api::mark_all_read_for_user($touserid, $fromuserid);
5228 * Return a list of page types
5230 * @deprecated since Moodle 3.2
5231 * @param string $pagetype current page type
5232 * @param stdClass $parentcontext Block's parent context
5233 * @param stdClass $currentcontext Current context of block
5235 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
5236 debugging('message_page_type_list() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5238 return array('messages-*'=>get_string('page-message-x', 'message'));
5242 * Determines if a user is permitted to send another user a private message.
5243 * If no sender is provided then it defaults to the logged in user.
5245 * @deprecated since Moodle 3.2
5246 * @param object $recipient User object.
5247 * @param object $sender User object.
5248 * @return bool true if user is permitted, false otherwise.
5250 function message_can_post_message($recipient, $sender = null) {
5251 debugging('message_can_post_message() is deprecated and is no longer used, please use
5252 \core_message\api::can_post_message() instead.', DEBUG_DEVELOPER);
5254 return \core_message\api::can_post_message($recipient, $sender);
5258 * Checks if the recipient is allowing messages from users that aren't a
5259 * contact. If not then it checks to make sure the sender is in the
5260 * recipient's contacts.
5262 * @deprecated since Moodle 3.2
5263 * @param object $recipient User object.
5264 * @param object $sender User object.
5265 * @return bool true if $sender is blocked, false otherwise.
5267 function message_is_user_non_contact_blocked($recipient, $sender = null) {
5268 debugging('message_is_user_non_contact_blocked() is deprecated and is no longer used, please use
5269 \core_message\api::is_user_non_contact_blocked() instead.', DEBUG_DEVELOPER);
5271 return \core_message\api::is_user_non_contact_blocked($recipient, $sender);
5275 * Checks if the recipient has specifically blocked the sending user.
5277 * Note: This function will always return false if the sender has the
5278 * readallmessages capability at the system context level.
5280 * @deprecated since Moodle 3.2
5281 * @param object $recipient User object.
5282 * @param object $sender User object.
5283 * @return bool true if $sender is blocked, false otherwise.
5285 function message_is_user_blocked($recipient, $sender = null) {
5286 debugging('message_is_user_blocked() is deprecated and is no longer used, please use
5287 \core_message\api::is_user_blocked() instead.', DEBUG_DEVELOPER);
5289 $senderid = null;
5290 if ($sender !== null && isset($sender->id)) {
5291 $senderid = $sender->id;
5293 return \core_message\api::is_user_blocked($recipient->id, $senderid);
5297 * Display logs.
5299 * @deprecated since 3.2
5301 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5302 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5303 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5305 global $CFG, $DB, $OUTPUT;
5307 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
5308 $modname, $modid, $modaction, $groupid)) {
5309 echo $OUTPUT->notification("No logs found!");
5310 echo $OUTPUT->footer();
5311 exit;
5314 $courses = array();
5316 if ($course->id == SITEID) {
5317 $courses[0] = '';
5318 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5319 foreach ($ccc as $cc) {
5320 $courses[$cc->id] = $cc->shortname;
5323 } else {
5324 $courses[$course->id] = $course->shortname;
5327 $totalcount = $logs['totalcount'];
5328 $ldcache = array();
5330 $strftimedatetime = get_string("strftimedatetime");
5332 echo "<div class=\"info\">\n";
5333 print_string("displayingrecords", "", $totalcount);
5334 echo "</div>\n";
5336 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5338 $table = new html_table();
5339 $table->classes = array('logtable','generaltable');
5340 $table->align = array('right', 'left', 'left');
5341 $table->head = array(
5342 get_string('time'),
5343 get_string('ip_address'),
5344 get_string('fullnameuser'),
5345 get_string('action'),
5346 get_string('info')
5348 $table->data = array();
5350 if ($course->id == SITEID) {
5351 array_unshift($table->align, 'left');
5352 array_unshift($table->head, get_string('course'));
5355 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
5356 if (empty($logs['logs'])) {
5357 $logs['logs'] = array();
5360 foreach ($logs['logs'] as $log) {
5362 if (isset($ldcache[$log->module][$log->action])) {
5363 $ld = $ldcache[$log->module][$log->action];
5364 } else {
5365 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5366 $ldcache[$log->module][$log->action] = $ld;
5368 if ($ld && is_numeric($log->info)) {
5369 // ugly hack to make sure fullname is shown correctly
5370 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
5371 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5372 } else {
5373 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5377 //Filter log->info
5378 $log->info = format_string($log->info);
5380 // If $log->url has been trimmed short by the db size restriction
5381 // code in add_to_log, keep a note so we don't add a link to a broken url
5382 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
5384 $row = array();
5385 if ($course->id == SITEID) {
5386 if (empty($log->course)) {
5387 $row[] = get_string('site');
5388 } else {
5389 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
5393 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
5395 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5396 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
5398 $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))));
5400 $displayaction="$log->module $log->action";
5401 if ($brokenurl) {
5402 $row[] = $displayaction;
5403 } else {
5404 $link = make_log_url($log->module,$log->url);
5405 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
5407 $row[] = $log->info;
5408 $table->data[] = $row;
5411 echo html_writer::table($table);
5412 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5416 * Display MNET logs.
5418 * @deprecated since 3.2
5420 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5421 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5422 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5424 global $CFG, $DB, $OUTPUT;
5426 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
5427 $modname, $modid, $modaction, $groupid)) {
5428 echo $OUTPUT->notification("No logs found!");
5429 echo $OUTPUT->footer();
5430 exit;
5433 if ($course->id == SITEID) {
5434 $courses[0] = '';
5435 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
5436 foreach ($ccc as $cc) {
5437 $courses[$cc->id] = $cc->shortname;
5442 $totalcount = $logs['totalcount'];
5443 $ldcache = array();
5445 $strftimedatetime = get_string("strftimedatetime");
5447 echo "<div class=\"info\">\n";
5448 print_string("displayingrecords", "", $totalcount);
5449 echo "</div>\n";
5451 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5453 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
5454 echo "<tr>";
5455 if ($course->id == SITEID) {
5456 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
5458 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
5459 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
5460 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
5461 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
5462 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
5463 echo "</tr>\n";
5465 if (empty($logs['logs'])) {
5466 echo "</table>\n";
5467 return;
5470 $row = 1;
5471 foreach ($logs['logs'] as $log) {
5473 $log->info = $log->coursename;
5474 $row = ($row + 1) % 2;
5476 if (isset($ldcache[$log->module][$log->action])) {
5477 $ld = $ldcache[$log->module][$log->action];
5478 } else {
5479 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5480 $ldcache[$log->module][$log->action] = $ld;
5482 if (0 && $ld && !empty($log->info)) {
5483 // ugly hack to make sure fullname is shown correctly
5484 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5485 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5486 } else {
5487 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5491 //Filter log->info
5492 $log->info = format_string($log->info);
5494 echo '<tr class="r'.$row.'">';
5495 if ($course->id == SITEID) {
5496 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
5497 echo "<td class=\"r$row c0\" >\n";
5498 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
5499 echo "</td>\n";
5501 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
5502 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
5503 echo "<td class=\"r$row c2\" >\n";
5504 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5505 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
5506 echo "</td>\n";
5507 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
5508 echo "<td class=\"r$row c3\" >\n";
5509 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
5510 echo "</td>\n";
5511 echo "<td class=\"r$row c4\">\n";
5512 echo $log->action .': '.$log->module;
5513 echo "</td>\n";
5514 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
5515 echo "</tr>\n";
5517 echo "</table>\n";
5519 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5523 * Display logs in CSV format.
5525 * @deprecated since 3.2
5527 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
5528 $modid, $modaction, $groupid) {
5529 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5531 global $DB, $CFG;
5533 require_once($CFG->libdir . '/csvlib.class.php');
5535 $csvexporter = new csv_export_writer('tab');
5537 $header = array();
5538 $header[] = get_string('course');
5539 $header[] = get_string('time');
5540 $header[] = get_string('ip_address');
5541 $header[] = get_string('fullnameuser');
5542 $header[] = get_string('action');
5543 $header[] = get_string('info');
5545 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5546 $modname, $modid, $modaction, $groupid)) {
5547 return false;
5550 $courses = array();
5552 if ($course->id == SITEID) {
5553 $courses[0] = '';
5554 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5555 foreach ($ccc as $cc) {
5556 $courses[$cc->id] = $cc->shortname;
5559 } else {
5560 $courses[$course->id] = $course->shortname;
5563 $count=0;
5564 $ldcache = array();
5565 $tt = getdate(time());
5566 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5568 $strftimedatetime = get_string("strftimedatetime");
5570 $csvexporter->set_filename('logs', '.txt');
5571 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
5572 $csvexporter->add_data($title);
5573 $csvexporter->add_data($header);
5575 if (empty($logs['logs'])) {
5576 return true;
5579 foreach ($logs['logs'] as $log) {
5580 if (isset($ldcache[$log->module][$log->action])) {
5581 $ld = $ldcache[$log->module][$log->action];
5582 } else {
5583 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5584 $ldcache[$log->module][$log->action] = $ld;
5586 if ($ld && is_numeric($log->info)) {
5587 // ugly hack to make sure fullname is shown correctly
5588 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5589 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5590 } else {
5591 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5595 //Filter log->info
5596 $log->info = format_string($log->info);
5597 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5599 $coursecontext = context_course::instance($course->id);
5600 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
5601 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5602 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5603 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
5604 $csvexporter->add_data($row);
5606 $csvexporter->download_file();
5607 return true;
5611 * Display logs in XLS format.
5613 * @deprecated since 3.2
5615 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
5616 $modid, $modaction, $groupid) {
5617 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5619 global $CFG, $DB;
5621 require_once("$CFG->libdir/excellib.class.php");
5623 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5624 $modname, $modid, $modaction, $groupid)) {
5625 return false;
5628 $courses = array();
5630 if ($course->id == SITEID) {
5631 $courses[0] = '';
5632 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5633 foreach ($ccc as $cc) {
5634 $courses[$cc->id] = $cc->shortname;
5637 } else {
5638 $courses[$course->id] = $course->shortname;
5641 $count=0;
5642 $ldcache = array();
5643 $tt = getdate(time());
5644 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5646 $strftimedatetime = get_string("strftimedatetime");
5648 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5649 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5650 $filename .= '.xls';
5652 $workbook = new MoodleExcelWorkbook('-');
5653 $workbook->send($filename);
5655 $worksheet = array();
5656 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5657 get_string('fullnameuser'), get_string('action'), get_string('info'));
5659 // Creating worksheets
5660 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5661 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5662 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5663 $worksheet[$wsnumber]->set_column(1, 1, 30);
5664 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5665 userdate(time(), $strftimedatetime));
5666 $col = 0;
5667 foreach ($headers as $item) {
5668 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5669 $col++;
5673 if (empty($logs['logs'])) {
5674 $workbook->close();
5675 return true;
5678 $formatDate =& $workbook->add_format();
5679 $formatDate->set_num_format(get_string('log_excel_date_format'));
5681 $row = FIRSTUSEDEXCELROW;
5682 $wsnumber = 1;
5683 $myxls =& $worksheet[$wsnumber];
5684 foreach ($logs['logs'] as $log) {
5685 if (isset($ldcache[$log->module][$log->action])) {
5686 $ld = $ldcache[$log->module][$log->action];
5687 } else {
5688 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5689 $ldcache[$log->module][$log->action] = $ld;
5691 if ($ld && is_numeric($log->info)) {
5692 // ugly hack to make sure fullname is shown correctly
5693 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5694 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5695 } else {
5696 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5700 // Filter log->info
5701 $log->info = format_string($log->info);
5702 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5704 if ($nroPages>1) {
5705 if ($row > EXCELROWS) {
5706 $wsnumber++;
5707 $myxls =& $worksheet[$wsnumber];
5708 $row = FIRSTUSEDEXCELROW;
5712 $coursecontext = context_course::instance($course->id);
5714 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
5715 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
5716 $myxls->write($row, 2, $log->ip, '');
5717 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5718 $myxls->write($row, 3, $fullname, '');
5719 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5720 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
5721 $myxls->write($row, 5, $log->info, '');
5723 $row++;
5726 $workbook->close();
5727 return true;
5731 * Display logs in ODS format.
5733 * @deprecated since 3.2
5735 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
5736 $modid, $modaction, $groupid) {
5737 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5739 global $CFG, $DB;
5741 require_once("$CFG->libdir/odslib.class.php");
5743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5744 $modname, $modid, $modaction, $groupid)) {
5745 return false;
5748 $courses = array();
5750 if ($course->id == SITEID) {
5751 $courses[0] = '';
5752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5753 foreach ($ccc as $cc) {
5754 $courses[$cc->id] = $cc->shortname;
5757 } else {
5758 $courses[$course->id] = $course->shortname;
5761 $ldcache = array();
5763 $strftimedatetime = get_string("strftimedatetime");
5765 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5766 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5767 $filename .= '.ods';
5769 $workbook = new MoodleODSWorkbook('-');
5770 $workbook->send($filename);
5772 $worksheet = array();
5773 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5774 get_string('fullnameuser'), get_string('action'), get_string('info'));
5776 // Creating worksheets
5777 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5778 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5779 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5780 $worksheet[$wsnumber]->set_column(1, 1, 30);
5781 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5782 userdate(time(), $strftimedatetime));
5783 $col = 0;
5784 foreach ($headers as $item) {
5785 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5786 $col++;
5790 if (empty($logs['logs'])) {
5791 $workbook->close();
5792 return true;
5795 $formatDate =& $workbook->add_format();
5796 $formatDate->set_num_format(get_string('log_excel_date_format'));
5798 $row = FIRSTUSEDEXCELROW;
5799 $wsnumber = 1;
5800 $myxls =& $worksheet[$wsnumber];
5801 foreach ($logs['logs'] as $log) {
5802 if (isset($ldcache[$log->module][$log->action])) {
5803 $ld = $ldcache[$log->module][$log->action];
5804 } else {
5805 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5806 $ldcache[$log->module][$log->action] = $ld;
5808 if ($ld && is_numeric($log->info)) {
5809 // ugly hack to make sure fullname is shown correctly
5810 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5811 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5812 } else {
5813 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5817 // Filter log->info
5818 $log->info = format_string($log->info);
5819 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5821 if ($nroPages>1) {
5822 if ($row > EXCELROWS) {
5823 $wsnumber++;
5824 $myxls =& $worksheet[$wsnumber];
5825 $row = FIRSTUSEDEXCELROW;
5829 $coursecontext = context_course::instance($course->id);
5831 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
5832 $myxls->write_date($row, 1, $log->time);
5833 $myxls->write_string($row, 2, $log->ip);
5834 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5835 $myxls->write_string($row, 3, $fullname);
5836 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5837 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
5838 $myxls->write_string($row, 5, $log->info);
5840 $row++;
5843 $workbook->close();
5844 return true;
5848 * Build an array of logs.
5850 * @deprecated since 3.2
5852 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
5853 $modname="", $modid=0, $modaction="", $groupid=0) {
5854 global $DB, $SESSION, $USER;
5856 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5857 // It is assumed that $date is the GMT time of midnight for that day,
5858 // and so the next 86400 seconds worth of logs are printed.
5860 // Setup for group handling.
5862 // If the group mode is separate, and this user does not have editing privileges,
5863 // then only the user's group can be viewed.
5864 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
5865 if (isset($SESSION->currentgroup[$course->id])) {
5866 $groupid = $SESSION->currentgroup[$course->id];
5867 } else {
5868 $groupid = groups_get_all_groups($course->id, $USER->id);
5869 if (is_array($groupid)) {
5870 $groupid = array_shift(array_keys($groupid));
5871 $SESSION->currentgroup[$course->id] = $groupid;
5872 } else {
5873 $groupid = 0;
5877 // If this course doesn't have groups, no groupid can be specified.
5878 else if (!$course->groupmode) {
5879 $groupid = 0;
5882 $joins = array();
5883 $params = array();
5885 if ($course->id != SITEID || $modid != 0) {
5886 $joins[] = "l.course = :courseid";
5887 $params['courseid'] = $course->id;
5890 if ($modname) {
5891 $joins[] = "l.module = :modname";
5892 $params['modname'] = $modname;
5895 if ('site_errors' === $modid) {
5896 $joins[] = "( l.action='error' OR l.action='infected' )";
5897 } else if ($modid) {
5898 $joins[] = "l.cmid = :modid";
5899 $params['modid'] = $modid;
5902 if ($modaction) {
5903 $firstletter = substr($modaction, 0, 1);
5904 if ($firstletter == '-') {
5905 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
5906 $params['modaction'] = '%'.substr($modaction, 1).'%';
5907 } else {
5908 $joins[] = $DB->sql_like('l.action', ':modaction', false);
5909 $params['modaction'] = '%'.$modaction.'%';
5914 /// Getting all members of a group.
5915 if ($groupid and !$user) {
5916 if ($gusers = groups_get_members($groupid)) {
5917 $gusers = array_keys($gusers);
5918 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
5919 } else {
5920 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
5923 else if ($user) {
5924 $joins[] = "l.userid = :userid";
5925 $params['userid'] = $user;
5928 if ($date) {
5929 $enddate = $date + 86400;
5930 $joins[] = "l.time > :date AND l.time < :enddate";
5931 $params['date'] = $date;
5932 $params['enddate'] = $enddate;
5935 $selector = implode(' AND ', $joins);
5937 $totalcount = 0; // Initialise
5938 $result = array();
5939 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
5940 $result['totalcount'] = $totalcount;
5941 return $result;
5945 * Select all log records for a given course and user.
5947 * @deprecated since 3.2
5948 * @param int $userid The id of the user as found in the 'user' table.
5949 * @param int $courseid The id of the course as found in the 'course' table.
5950 * @param string $coursestart unix timestamp representing course start date and time.
5951 * @return array
5953 function get_logs_usercourse($userid, $courseid, $coursestart) {
5954 global $DB;
5956 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5958 $params = array();
5960 $courseselect = '';
5961 if ($courseid) {
5962 $courseselect = "AND course = :courseid";
5963 $params['courseid'] = $courseid;
5965 $params['userid'] = $userid;
5966 // We have to sanitize this param ourselves here instead of relying on DB.
5967 // Postgres complains if you use name parameter or column alias in GROUP BY.
5968 // See MDL-27696 and 51c3e85 for details.
5969 $coursestart = (int)$coursestart;
5971 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
5972 FROM {log}
5973 WHERE userid = :userid
5974 AND time > $coursestart $courseselect
5975 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
5979 * Select all log records for a given course, user, and day.
5981 * @deprecated since 3.2
5982 * @param int $userid The id of the user as found in the 'user' table.
5983 * @param int $courseid The id of the course as found in the 'course' table.
5984 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
5985 * @return array
5987 function get_logs_userday($userid, $courseid, $daystart) {
5988 global $DB;
5990 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5992 $params = array('userid'=>$userid);
5994 $courseselect = '';
5995 if ($courseid) {
5996 $courseselect = "AND course = :courseid";
5997 $params['courseid'] = $courseid;
5999 // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
6000 $daystart = (int) $daystart;
6002 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
6003 FROM {log}
6004 WHERE userid = :userid
6005 AND time > $daystart $courseselect
6006 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
6010 * Select all log records based on SQL criteria.
6012 * @deprecated since 3.2
6013 * @param string $select SQL select criteria
6014 * @param array $params named sql type params
6015 * @param string $order SQL order by clause to sort the records returned
6016 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
6017 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
6018 * @param int $totalcount Passed in by reference.
6019 * @return array
6021 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
6022 global $DB;
6024 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6026 if ($order) {
6027 $order = "ORDER BY $order";
6030 if ($select) {
6031 $select = "WHERE $select";
6034 $sql = "SELECT COUNT(*)
6035 FROM {log} l
6036 $select";
6038 $totalcount = $DB->count_records_sql($sql, $params);
6039 $allnames = get_all_user_name_fields(true, 'u');
6040 $sql = "SELECT l.*, $allnames, u.picture
6041 FROM {log} l
6042 LEFT JOIN {user} u ON l.userid = u.id
6043 $select
6044 $order";
6046 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
6050 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
6052 * @deprecated since Moodle 3.2 MDL-53048
6054 function prevent_form_autofill_password() {
6055 debugging('prevent_form_autofill_password has been deprecated and is no longer in use.', DEBUG_DEVELOPER);
6056 return '';
6060 * Get the users recent conversations meaning all the people they've recently
6061 * sent or received a message from plus the most recent message sent to or received from each other user
6063 * @deprecated since Moodle 3.3 MDL-57370
6064 * @param object|int $userorid the current user or user id
6065 * @param int $limitfrom can be used for paging
6066 * @param int $limitto can be used for paging
6067 * @return array
6069 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
6070 global $DB;
6072 debugging('message_get_recent_conversations() is deprecated. Please use \core_message\api::get_conversations() instead.', DEBUG_DEVELOPER);
6074 if (is_object($userorid)) {
6075 $user = $userorid;
6076 } else {
6077 $userid = $userorid;
6078 $user = new stdClass();
6079 $user->id = $userid;
6082 $userfields = user_picture::fields('otheruser', array('lastaccess'));
6084 // This query retrieves the most recent message received from or sent to
6085 // seach other user.
6087 // If two messages have the same timecreated, we take the one with the
6088 // larger id.
6090 // There is a separate query for read and unread messages as they are stored
6091 // in different tables. They were originally retrieved in one query but it
6092 // was so large that it was difficult to be confident in its correctness.
6093 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
6094 $sql = "SELECT $uniquefield, $userfields,
6095 message.id as mid, message.notification, message.useridfrom, message.useridto,
6096 message.smallmessage, message.fullmessage, message.fullmessagehtml,
6097 message.fullmessageformat, message.timecreated,
6098 contact.id as contactlistid, contact.blocked
6099 FROM {message_read} message
6100 JOIN (
6101 SELECT MAX(id) AS messageid,
6102 matchedmessage.useridto,
6103 matchedmessage.useridfrom
6104 FROM {message_read} matchedmessage
6105 INNER JOIN (
6106 SELECT MAX(recentmessages.timecreated) timecreated,
6107 recentmessages.useridfrom,
6108 recentmessages.useridto
6109 FROM {message_read} recentmessages
6110 WHERE (
6111 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
6112 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
6114 GROUP BY recentmessages.useridfrom, recentmessages.useridto
6115 ) recent ON matchedmessage.useridto = recent.useridto
6116 AND matchedmessage.useridfrom = recent.useridfrom
6117 AND matchedmessage.timecreated = recent.timecreated
6118 WHERE (
6119 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
6120 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
6122 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
6123 ) messagesubset ON messagesubset.messageid = message.id
6124 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
6125 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
6126 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.contactid = otheruser.id
6127 WHERE otheruser.deleted = 0 AND message.notification = 0
6128 ORDER BY message.timecreated DESC";
6129 $params = array(
6130 'userid1' => $user->id,
6131 'userid2' => $user->id,
6132 'userid3' => $user->id,
6133 'userid4' => $user->id,
6134 'userid5' => $user->id,
6135 'userid6' => $user->id,
6136 'userid7' => $user->id
6138 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
6140 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
6141 // exact same query as the one above, except for the table we are querying. So, simply replace references to
6142 // the 'message_read' table with the 'message' table.
6143 $sql = str_replace('{message_read}', '{message}', $sql);
6144 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
6146 $unreadcountssql = 'SELECT useridfrom, count(*) as count
6147 FROM {message}
6148 WHERE useridto = :userid
6149 AND timeusertodeleted = 0
6150 AND notification = 0
6151 GROUP BY useridfrom';
6152 $unreadcounts = $DB->get_records_sql($unreadcountssql, array('userid' => $user->id));
6154 // Union the 2 result sets together looking for the message with the most
6155 // recent timecreated for each other user.
6156 // $conversation->id (the array key) is the other user's ID.
6157 $conversations = array();
6158 $conversation_arrays = array($unread, $read);
6159 foreach ($conversation_arrays as $conversation_array) {
6160 foreach ($conversation_array as $conversation) {
6161 // Only consider it unread if $user has unread messages.
6162 if (isset($unreadcounts[$conversation->useridfrom])) {
6163 $conversation->isread = 0;
6164 $conversation->unreadcount = $unreadcounts[$conversation->useridfrom]->count;
6165 } else {
6166 $conversation->isread = 1;
6169 if (!isset($conversations[$conversation->id])) {
6170 $conversations[$conversation->id] = $conversation;
6171 } else {
6172 $current = $conversations[$conversation->id];
6173 // We need to maintain the isread and unreadcount values from existing
6174 // parts of the conversation if we're replacing it.
6175 $conversation->isread = ($conversation->isread && $current->isread);
6176 if (isset($current->unreadcount) && !isset($conversation->unreadcount)) {
6177 $conversation->unreadcount = $current->unreadcount;
6180 if ($current->timecreated < $conversation->timecreated) {
6181 $conversations[$conversation->id] = $conversation;
6182 } else if ($current->timecreated == $conversation->timecreated) {
6183 if ($current->mid < $conversation->mid) {
6184 $conversations[$conversation->id] = $conversation;
6191 // Sort the conversations by $conversation->timecreated, newest to oldest
6192 // There may be multiple conversations with the same timecreated
6193 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
6194 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
6195 $conversations = array_reverse($conversations);
6197 return $conversations;
6201 * Display calendar preference button.
6203 * @param stdClass $course course object
6204 * @deprecated since Moodle 3.2
6205 * @return string return preference button in html
6207 function calendar_preferences_button(stdClass $course) {
6208 debugging('This should no longer be used, the calendar preferences are now linked to the user preferences page.');
6210 global $OUTPUT;
6212 // Guests have no preferences.
6213 if (!isloggedin() || isguestuser()) {
6214 return '';
6217 return $OUTPUT->single_button(new moodle_url('/user/calendar.php'), get_string("preferences", "calendar"));
6221 * Return the name of the weekday
6223 * @deprecated since 3.3
6224 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6225 * @param string $englishname
6226 * @return string of the weekeday
6228 function calendar_wday_name($englishname) {
6229 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
6230 return get_string(strtolower($englishname), 'calendar');
6234 * Get the upcoming event block.
6236 * @deprecated since 3.3
6237 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6238 * @param array $events list of events
6239 * @param moodle_url|string $linkhref link to event referer
6240 * @param boolean $showcourselink whether links to courses should be shown
6241 * @return string|null $content html block content
6243 function calendar_get_block_upcoming($events, $linkhref = null, $showcourselink = false) {
6244 global $CFG;
6246 debugging(__FUNCTION__ . '() is deprecated, please use block_calendar_upcoming::get_upcoming_content() instead.',
6247 DEBUG_DEVELOPER);
6249 require_once($CFG->dirroot . '/blocks/moodleblock.class.php');
6250 require_once($CFG->dirroot . '/blocks/calendar_upcoming/block_calendar_upcoming.php');
6251 return block_calendar_upcoming::get_upcoming_content($events, $linkhref, $showcourselink);
6255 * Display month selector options.
6257 * @deprecated since 3.3
6258 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6259 * @param string $name for the select element
6260 * @param string|array $selected options for select elements
6262 function calendar_print_month_selector($name, $selected) {
6263 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
6264 $months = array();
6265 for ($i = 1; $i <= 12; $i++) {
6266 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
6268 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
6269 echo html_writer::select($months, $name, $selected, false);
6273 * Update calendar subscriptions.
6275 * @deprecated since 3.3
6276 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6277 * @return bool
6279 function calendar_cron() {
6280 debugging(__FUNCTION__ . '() is deprecated and should not be used. Please use the core\task\calendar_cron_task instead.',
6281 DEBUG_DEVELOPER);
6283 global $CFG, $DB;
6285 require_once($CFG->dirroot . '/calendar/lib.php');
6286 // In order to execute this we need bennu.
6287 require_once($CFG->libdir.'/bennu/bennu.inc.php');
6289 mtrace('Updating calendar subscriptions:');
6290 cron_trace_time_and_memory();
6292 $time = time();
6293 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0
6294 AND lastupdated + pollinterval < ?', array($time));
6295 foreach ($subscriptions as $sub) {
6296 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
6297 try {
6298 $log = calendar_update_subscription_events($sub->id);
6299 mtrace(trim(strip_tags($log)));
6300 } catch (moodle_exception $ex) {
6301 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
6305 mtrace('Finished updating calendar subscriptions.');
6307 return true;
6311 * Previous internal API, it was not supposed to be used anywhere.
6313 * @access private
6314 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6315 * @param int $userid the id of the user
6316 * @param context_course $coursecontext course context
6317 * @param array $accessdata accessdata array (modified)
6318 * @return void modifies $accessdata parameter
6320 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
6321 throw new coding_exception('load_course_context() is removed. Do not use private functions or data structures.');
6325 * Previous internal API, it was not supposed to be used anywhere.
6327 * @access private
6328 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6329 * @param int $roleid the id of the user
6330 * @param context $context needs path!
6331 * @param array $accessdata accessdata array (is modified)
6332 * @return array
6334 function load_role_access_by_context($roleid, context $context, &$accessdata) {
6335 throw new coding_exception('load_role_access_by_context() is removed. Do not use private functions or data structures.');
6339 * Previous internal API, it was not supposed to be used anywhere.
6341 * @access private
6342 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6343 * @return void
6345 function dedupe_user_access() {
6346 throw new coding_exception('dedupe_user_access() is removed. Do not use private functions or data structures.');
6350 * Previous internal API, it was not supposed to be used anywhere.
6351 * Return a nested array showing role assignments
6352 * and all relevant role capabilities for the user.
6354 * [ra] => [/path][roleid]=roleid
6355 * [rdef] => ["$contextpath:$roleid"][capability]=permission
6357 * @access private
6358 * @deprecated since Moodle 3.4. MDL-49398.
6359 * @param int $userid - the id of the user
6360 * @return array access info array
6362 function get_user_access_sitewide($userid) {
6363 debugging('get_user_access_sitewide() is deprecated. Do not use private functions or data structures.', DEBUG_DEVELOPER);
6365 $accessdata = get_user_accessdata($userid);
6366 $accessdata['rdef'] = array();
6367 $roles = array();
6369 foreach ($accessdata['ra'] as $path => $pathroles) {
6370 $roles = array_merge($pathroles, $roles);
6373 $rdefs = get_role_definitions($roles);
6375 foreach ($rdefs as $roleid => $rdef) {
6376 foreach ($rdef as $path => $caps) {
6377 $accessdata['rdef']["$path:$roleid"] = $caps;
6381 return $accessdata;
6385 * Generates the HTML for a miniature calendar.
6387 * @param array $courses list of course to list events from
6388 * @param array $groups list of group
6389 * @param array $users user's info
6390 * @param int|bool $calmonth calendar month in numeric, default is set to false
6391 * @param int|bool $calyear calendar month in numeric, default is set to false
6392 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
6393 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
6394 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
6395 * and $calyear to support multiple calendars
6396 * @return string $content return html table for mini calendar
6397 * @deprecated since Moodle 3.4. MDL-59333
6399 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
6400 $courseid = false, $time = 0) {
6401 global $PAGE;
6403 debugging('calendar_get_mini() has been deprecated. Please update your code to use calendar_get_view.',
6404 DEBUG_DEVELOPER);
6406 if (!empty($calmonth) && !empty($calyear)) {
6407 // Do this check for backwards compatibility.
6408 // The core should be passing a timestamp rather than month and year.
6409 // If a month and year are passed they will be in Gregorian.
6410 // Ensure it is a valid date, else we will just set it to the current timestamp.
6411 if (checkdate($calmonth, 1, $calyear)) {
6412 $time = make_timestamp($calyear, $calmonth, 1);
6413 } else {
6414 $time = time();
6416 } else if (empty($time)) {
6417 // Get the current date in the calendar type being used.
6418 $time = time();
6421 if ($courseid == SITEID) {
6422 $course = get_site();
6423 } else {
6424 $course = get_course($courseid);
6426 $calendar = new calendar_information(0, 0, 0, $time);
6427 $calendar->prepare_for_view($course, $courses);
6429 $renderer = $PAGE->get_renderer('core_calendar');
6430 list($data, $template) = calendar_get_view($calendar, 'mini');
6431 return $renderer->render_from_template($template, $data);