3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * deprecatedlib.php - Old functions retained only for backward compatibility
21 * Old functions retained only for backward compatibility. New code should not
22 * use any of these functions.
25 * @subpackage deprecated
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') ||
die();
33 /* === Functions that needs to be kept longer in deprecated lib than normal time period === */
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
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);
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);
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) {
94 // NOTE: do not add any other debugging here, keep forever.
96 $subsystems = core_component
::get_core_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) {
110 $subsystems[$k] = substr($v, $dlength+
1);
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) {
127 // NOTE: do not add any other debugging here, keep forever.
129 $types = core_component
::get_plugin_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';
144 $types[$k] = substr($v, $dlength+
1);
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 === '') {
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 === '') {
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;
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)) {
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.');
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
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().
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.
483 function reset_login_count() {
484 throw new coding_exception('reset_login_count() is removed, all calls need to be removed');
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
);
526 $path = str_replace('//', '/', $path);
527 $path = trim($path, '/'); // no leading and trailing slashes
532 $url = $CFG->wwwroot
."/question/exportfile.php";
535 $url = $CFG->wwwroot
."/rss/file.php";
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;
554 $path = rawurlencode('/'.$path);
555 $ffurl = $url.'?file='.$path;
556 $separator = '&';
560 foreach ($options as $name=>$value) {
561 $ffurl = $ffurl.$separator.$name.'='.$value;
562 $separator = '&';
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.');
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.
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
621 if (empty($zipfilename)) {
625 //If no extension, error
626 if (empty($extension)) {
631 $zipfile = cleardoubleslashes($zipfile);
633 //Check zipfile exists
634 if (!file_exists($zipfile)) {
638 //If no destination, passed let's go with the same directory
639 if (empty($destination)) {
640 $destination = $zippath;
644 $destpath = rtrim(cleardoubleslashes($destination), "/");
646 //Check destination path exists
647 if (!is_dir($destpath)) {
651 $packer = get_file_packer('application/zip');
653 $result = $packer->extract_to_pathname($zipfile, $destpath);
655 if ($result === false) {
659 foreach ($result as $status) {
660 if ($status !== true) {
669 * Zip an array of files/dirs to a destination zip file
670 * Both parameters must be FULL paths to the files/dirs
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
690 if (empty($destfilename)) {
694 //If no extension, add it
695 if (empty($extension)) {
697 $destfilename = $destfilename.'.'.$extension;
700 //Check destination path exists
701 if (!is_dir($destpath)) {
705 //Check destination path is writable. TODO!!
707 //Clean destination filename
708 $destfilename = clean_filename($destfilename);
710 //Now check and prepare every file
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
725 //See if the file/dir is in the same directory than the rest
726 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
729 //Add the file to the array
730 $files[] = $tempfile;
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');
809 function formerr($error) {
810 throw new coding_exception('formerr() is removed. Please change your code to use $OUTPUT->error_text($string).');
814 * @deprecated use $OUTPUT->skip_link_target() in instead.
816 function skip_main_destination() {
817 throw new coding_exception('skip_main_destination() can not be used any more, please use $OUTPUT->skip_link_target() instead.');
821 * @deprecated use $OUTPUT->container() instead.
823 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
824 throw new coding_exception('print_container() can not be used any more. Please use $OUTPUT->container() instead.');
828 * @deprecated use $OUTPUT->container_start() instead.
830 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
831 throw new coding_exception('print_container_start() can not be used any more. Please use $OUTPUT->container_start() instead.');
835 * @deprecated use $OUTPUT->container_end() instead.
837 function print_container_end($return=false) {
838 throw new coding_exception('print_container_end() can not be used any more. Please use $OUTPUT->container_end() instead.');
842 * @deprecated since Moodle 2.0 MDL-19077 - use $OUTPUT->notification instead.
845 throw new coding_exception('notify() is removed, please use $OUTPUT->notification() instead');
849 * @deprecated use $OUTPUT->continue_button() instead.
851 function print_continue($link, $return = false) {
852 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
856 * @deprecated use $PAGE methods instead.
858 function print_header($title='', $heading='', $navigation='', $focus='',
859 $meta='', $cache=true, $button=' ', $menu=null,
860 $usexml=false, $bodytags='', $return=false) {
862 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
866 * @deprecated use $PAGE methods instead.
868 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
869 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
871 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
875 * @deprecated use $OUTPUT->block() instead.
877 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
878 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
882 * Prints a basic textarea field.
884 * @deprecated since Moodle 2.0
886 * When using this function, you should
889 * @param bool $unused No longer used.
890 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
891 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
892 * @param null $width (Deprecated) Width of the element; if a value is passed, the minimum value for $cols will be 65. Value is otherwise ignored.
893 * @param null $height (Deprecated) Height of the element; if a value is passe, the minimum value for $rows will be 10. Value is otherwise ignored.
894 * @param string $name Name to use for the textarea element.
895 * @param string $value Initial content to display in the textarea.
896 * @param int $obsolete deprecated
897 * @param bool $return If false, will output string. If true, will return string value.
898 * @param string $id CSS ID to add to the textarea element.
899 * @return string|void depending on the value of $return
901 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
902 /// $width and height are legacy fields and no longer used as pixels like they used to be.
903 /// However, you can set them to zero to override the mincols and minrows values below.
905 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
906 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
918 if ($height && ($rows < $minrows)) {
921 if ($width && ($cols < $mincols)) {
925 editors_head_setup();
926 $editor = editors_get_preferred_editor(FORMAT_HTML
);
927 $editor->set_text($value);
928 $editor->use_editor($id, array('legacy'=>true));
930 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
931 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
932 $str .= '</textarea>'."\n";
941 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
942 * provide this function with the language strings for sortasc and sortdesc.
944 * @deprecated use $OUTPUT->arrow() instead.
945 * @todo final deprecation of this function once MDL-45448 is resolved
947 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
950 * @param string $direction 'up' or 'down'
951 * @param string $strsort The language string used for the alt attribute of this image
952 * @param bool $return Whether to print directly or return the html string
953 * @return string|void depending on $return
956 function print_arrow($direction='up', $strsort=null, $return=false) {
959 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER
);
961 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
967 switch ($direction) {
982 // Prepare language string
984 if (empty($strsort) && !empty($sortdir)) {
985 $strsort = get_string('sort' . $sortdir, 'grades');
988 $return = ' ' . $OUTPUT->pix_icon('t/' . $direction, $strsort) . ' ';
998 * @deprecated since Moodle 2.0
1000 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1001 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1002 $id='', $listbox=false, $multiple=false, $class='') {
1003 throw new coding_exception('choose_from_menu() is removed. Please change your code to use html_writer::select().');
1008 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1010 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1011 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1012 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1016 * @deprecated use html_writer::checkbox() instead.
1018 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1019 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1023 * Prints the 'update this xxx' button that appears on module pages.
1025 * @deprecated since Moodle 3.2
1027 * @param string $cmid the course_module id.
1028 * @param string $ignored not used any more. (Used to be courseid.)
1029 * @param string $string the module name - get_string('modulename', 'xxx')
1030 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1032 function update_module_button($cmid, $ignored, $string) {
1033 global $CFG, $OUTPUT;
1035 debugging('update_module_button() has been deprecated and should not be used anymore. Activity modules should not add the ' .
1036 'edit module button, the link is already available in the Administration block. Themes can choose to display the link ' .
1037 'in the buttons row consistently for all module types.', DEBUG_DEVELOPER
);
1039 if (has_capability('moodle/course:manageactivities', context_module
::instance($cmid))) {
1040 $string = get_string('updatethis', '', $string);
1042 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1043 return $OUTPUT->single_button($url, $string);
1050 * @deprecated use $OUTPUT->navbar() instead
1052 function print_navigation ($navigation, $separator=0, $return=false) {
1053 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1057 * @deprecated Please use $PAGE->navabar methods instead.
1059 function build_navigation($extranavlinks, $cm = null) {
1060 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1064 * @deprecated not relevant with global navigation in Moodle 2.x+
1066 function navmenu($course, $cm=NULL, $targetwindow='self') {
1067 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1070 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1074 * @deprecated please use calendar_event::create() instead.
1076 function add_event($event) {
1077 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1081 * @deprecated please calendar_event->update() instead.
1083 function update_event($event) {
1084 throw new coding_exception('update_event() is removed, please use calendar_event->update() instead.');
1088 * @deprecated please use calendar_event->delete() instead.
1090 function delete_event($id) {
1091 throw new coding_exception('delete_event() can not be used any more, please use '.
1092 'calendar_event->delete() instead.');
1096 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1098 function hide_event($event) {
1099 throw new coding_exception('hide_event() can not be used any more, please use '.
1100 'calendar_event->toggle_visibility(false) instead.');
1104 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1106 function show_event($event) {
1107 throw new coding_exception('show_event() can not be used any more, please use '.
1108 'calendar_event->toggle_visibility(true) instead.');
1112 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1115 function textlib_get_instance() {
1116 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1117 'core_text::functioname() instead.');
1121 * @deprecated since 2.4
1122 * @see get_section_name()
1123 * @see format_base::get_section_name()
1126 function get_generic_section_name($format, stdClass
$section) {
1127 throw new coding_exception('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base');
1131 * Returns an array of sections for the requested course id
1133 * It is usually not recommended to display the list of sections used
1134 * in course because the course format may have it's own way to do it.
1136 * If you need to just display the name of the section please call:
1137 * get_section_name($course, $section)
1138 * {@link get_section_name()}
1139 * from 2.4 $section may also be just the field course_sections.section
1141 * If you need the list of all sections it is more efficient to get this data by calling
1142 * $modinfo = get_fast_modinfo($courseorid);
1143 * $sections = $modinfo->get_section_info_all()
1144 * {@link get_fast_modinfo()}
1145 * {@link course_modinfo::get_section_info_all()}
1147 * Information about one section (instance of section_info):
1148 * get_fast_modinfo($courseorid)->get_sections_info($section)
1149 * {@link course_modinfo::get_section_info()}
1151 * @deprecated since 2.4
1153 function get_all_sections($courseid) {
1155 throw new coding_exception('get_all_sections() is removed. See phpdocs for this function');
1159 * This function is deprecated, please use {@link course_add_cm_to_section()}
1160 * Note that course_add_cm_to_section() also updates field course_modules.section and
1161 * calls rebuild_course_cache()
1163 * @deprecated since 2.4
1165 function add_mod_to_section($mod, $beforemod = null) {
1166 throw new coding_exception('Function add_mod_to_section() is removed, please use course_add_cm_to_section()');
1170 * Returns a number of useful structures for course displays
1172 * Function get_all_mods() is deprecated in 2.4
1175 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1179 * $mods = get_fast_modinfo($courseorid)->get_cms();
1180 * $modnames = get_module_types_names();
1181 * $modnamesplural = get_module_types_names(true);
1182 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1185 * @deprecated since 2.4
1187 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1188 throw new coding_exception('Function get_all_mods() is removed. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details');
1192 * Returns course section - creates new if does not exist yet
1194 * This function is deprecated. To create a course section call:
1195 * course_create_sections_if_missing($courseorid, $sections);
1196 * to get the section call:
1197 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1199 * @see course_create_sections_if_missing()
1200 * @see get_fast_modinfo()
1201 * @deprecated since 2.4
1203 function get_course_section($section, $courseid) {
1204 throw new coding_exception('Function get_course_section() is removed. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.');
1208 * @deprecated since 2.4
1209 * @see format_weeks::get_section_dates()
1211 function format_weeks_get_section_dates($section, $course) {
1212 throw new coding_exception('Function format_weeks_get_section_dates() is removed. It is not recommended to'.
1213 ' use it outside of format_weeks plugin');
1217 * Deprecated. Instead of:
1218 * list($content, $name) = get_print_section_cm_text($cm, $course);
1220 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1221 * $name = $cm->get_formatted_name();
1223 * @deprecated since 2.5
1224 * @see cm_info::get_formatted_content()
1225 * @see cm_info::get_formatted_name()
1227 function get_print_section_cm_text(cm_info
$cm, $course) {
1228 throw new coding_exception('Function get_print_section_cm_text() is removed. Please use '.
1229 'cm_info::get_formatted_content() and cm_info::get_formatted_name()');
1233 * Deprecated. Please use:
1234 * $courserenderer = $PAGE->get_renderer('core', 'course');
1235 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1236 * array('inblock' => $vertical));
1239 * @deprecated since 2.5
1240 * @see core_course_renderer::course_section_add_cm_control()
1242 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1243 throw new coding_exception('Function print_section_add_menus() is removed. Please use course renderer '.
1244 'function course_section_add_cm_control()');
1248 * Deprecated. Please use:
1249 * $courserenderer = $PAGE->get_renderer('core', 'course');
1250 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1251 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1253 * @deprecated since 2.5
1254 * @see course_get_cm_edit_actions()
1255 * @see core_course_renderer->course_section_cm_edit_actions()
1257 function make_editing_buttons(stdClass
$mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1258 throw new coding_exception('Function make_editing_buttons() is removed, please see PHPdocs in '.
1259 'lib/deprecatedlib.php on how to replace it');
1263 * Deprecated. Please use:
1264 * $courserenderer = $PAGE->get_renderer('core', 'course');
1265 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1266 * array('hidecompletion' => $hidecompletion));
1268 * @deprecated since 2.5
1269 * @see core_course_renderer::course_section_cm_list()
1271 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1272 throw new coding_exception('Function print_section() is removed. Please use course renderer function '.
1273 'course_section_cm_list() instead.');
1277 * @deprecated since 2.5
1279 function print_overview($courses, array $remote_courses=array()) {
1280 throw new coding_exception('Function print_overview() is removed. Use block course_overview to display this information');
1284 * @deprecated since 2.5
1286 function print_recent_activity($course) {
1287 throw new coding_exception('Function print_recent_activity() is removed. It is not recommended to'.
1288 ' use it outside of block_recent_activity');
1292 * @deprecated since 2.5
1294 function delete_course_module($id) {
1295 throw new coding_exception('Function delete_course_module() is removed. Please use course_delete_module() instead.');
1299 * @deprecated since 2.5
1301 function update_category_button($categoryid = 0) {
1302 throw new coding_exception('Function update_category_button() is removed. Pages to view '.
1303 'and edit courses are now separate and no longer depend on editing mode.');
1307 * This function is deprecated! For list of categories use
1308 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
1309 * For parents of one particular category use
1310 * coursecat::get($id)->get_parents()
1312 * @deprecated since 2.5
1314 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1315 $excludeid = 0, $category = NULL, $path = "") {
1316 throw new coding_exception('Global function make_categories_list() is removed. Please use '.
1317 'coursecat::make_categories_list() and coursecat::get_parents()');
1321 * @deprecated since 2.5
1323 function category_delete_move($category, $newparentid, $showfeedback=true) {
1324 throw new coding_exception('Function category_delete_move() is removed. Please use coursecat::delete_move() instead.');
1328 * @deprecated since 2.5
1330 function category_delete_full($category, $showfeedback=true) {
1331 throw new coding_exception('Function category_delete_full() is removed. Please use coursecat::delete_full() instead.');
1335 * This function is deprecated. Please use
1336 * $coursecat = coursecat::get($category->id);
1337 * if ($coursecat->can_change_parent($newparentcat->id)) {
1338 * $coursecat->change_parent($newparentcat->id);
1341 * Alternatively you can use
1342 * $coursecat->update(array('parent' => $newparentcat->id));
1344 * @see coursecat::change_parent()
1345 * @see coursecat::update()
1346 * @deprecated since 2.5
1348 function move_category($category, $newparentcat) {
1349 throw new coding_exception('Function move_category() is removed. Please use coursecat::change_parent() instead.');
1353 * This function is deprecated. Please use
1354 * coursecat::get($category->id)->hide();
1356 * @see coursecat::hide()
1357 * @deprecated since 2.5
1359 function course_category_hide($category) {
1360 throw new coding_exception('Function course_category_hide() is removed. Please use coursecat::hide() instead.');
1364 * This function is deprecated. Please use
1365 * coursecat::get($category->id)->show();
1367 * @see coursecat::show()
1368 * @deprecated since 2.5
1370 function course_category_show($category) {
1371 throw new coding_exception('Function course_category_show() is removed. Please use coursecat::show() instead.');
1375 * This function is deprecated.
1376 * To get the category with the specified it please use:
1377 * coursecat::get($catid, IGNORE_MISSING);
1379 * coursecat::get($catid, MUST_EXIST);
1381 * To get the first available category please use
1382 * coursecat::get_default();
1384 * @deprecated since 2.5
1386 function get_course_category($catid=0) {
1387 throw new coding_exception('Function get_course_category() is removed. Please use coursecat::get(), see phpdocs for more details');
1391 * This function is deprecated. It is replaced with the method create() in class coursecat.
1392 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
1394 * @deprecated since 2.5
1396 function create_course_category($category) {
1397 throw new coding_exception('Function create_course_category() is removed. Please use coursecat::create(), see phpdocs for more details');
1401 * This function is deprecated.
1403 * To get visible children categories of the given category use:
1404 * coursecat::get($categoryid)->get_children();
1405 * This function will return the array or coursecat objects, on each of them
1406 * you can call get_children() again
1408 * @see coursecat::get()
1409 * @see coursecat::get_children()
1411 * @deprecated since 2.5
1413 function get_all_subcategories($catid) {
1414 throw new coding_exception('Function get_all_subcategories() is removed. Please use appropriate methods() of coursecat
1415 class. See phpdocs for more details');
1419 * This function is deprecated. Please use functions in class coursecat:
1420 * - coursecat::get($parentid)->has_children()
1421 * tells if the category has children (visible or not to the current user)
1423 * - coursecat::get($parentid)->get_children()
1424 * returns an array of coursecat objects, each of them represents a children category visible
1425 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
1427 * - coursecat::get($parentid)->get_children_count()
1428 * returns number of children categories visible to the current user
1430 * - coursecat::count_all()
1431 * returns total count of all categories in the system (both visible and not)
1433 * - coursecat::get_default()
1434 * returns the first category (usually to be used if count_all() == 1)
1436 * @deprecated since 2.5
1438 function get_child_categories($parentid) {
1439 throw new coding_exception('Function get_child_categories() is removed. Use coursecat::get_children() or see phpdocs for
1445 * @deprecated since 2.5
1447 * This function is deprecated. Use appropriate functions from class coursecat.
1450 * coursecat::get($categoryid)->get_children()
1451 * - returns all children of the specified category as instances of class
1452 * coursecat, which means on each of them method get_children() can be called again.
1453 * Only categories visible to the current user are returned.
1455 * coursecat::get(0)->get_children()
1456 * - returns all top-level categories visible to the current user.
1458 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
1460 * coursecat::make_categories_list()
1461 * - returns an array of all categories id/names in the system.
1462 * Also only returns categories visible to current user and can additionally be
1463 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
1465 * make_categories_options()
1466 * - Returns full course categories tree to be used in html_writer::select()
1468 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
1469 * {@link coursecat::get_default()}
1471 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1472 throw new coding_exception('Function get_categories() is removed. Please use coursecat::get_children() or see phpdocs for other alternatives');
1476 * This function is deprecated, please use course renderer:
1477 * $renderer = $PAGE->get_renderer('core', 'course');
1478 * echo $renderer->course_search_form($value, $format);
1480 * @deprecated since 2.5
1482 function print_course_search($value="", $return=false, $format="plain") {
1483 throw new coding_exception('Function print_course_search() is removed, please use course renderer');
1487 * This function is deprecated, please use:
1488 * $renderer = $PAGE->get_renderer('core', 'course');
1489 * echo $renderer->frontpage_my_courses()
1491 * @deprecated since 2.5
1493 function print_my_moodle() {
1494 throw new coding_exception('Function print_my_moodle() is removed, please use course renderer function frontpage_my_courses()');
1498 * This function is deprecated, it is replaced with protected function
1499 * {@link core_course_renderer::frontpage_remote_course()}
1500 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1502 * @deprecated since 2.5
1504 function print_remote_course($course, $width="100%") {
1505 throw new coding_exception('Function print_remote_course() is removed, please use course renderer');
1509 * This function is deprecated, it is replaced with protected function
1510 * {@link core_course_renderer::frontpage_remote_host()}
1511 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1513 * @deprecated since 2.5
1515 function print_remote_host($host, $width="100%") {
1516 throw new coding_exception('Function print_remote_host() is removed, please use course renderer');
1520 * @deprecated since 2.5
1522 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1524 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1525 throw new coding_exception('Function print_whole_category_list() is removed, please use course renderer');
1529 * @deprecated since 2.5
1531 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1532 throw new coding_exception('Function print_category_info() is removed, please use course renderer');
1536 * @deprecated since 2.5
1538 * This function is not used any more in moodle core and course renderer does not have render function for it.
1539 * Combo list on the front page is displayed as:
1540 * $renderer = $PAGE->get_renderer('core', 'course');
1541 * echo $renderer->frontpage_combo_list()
1543 * The new class {@link coursecat} stores the information about course category tree
1544 * To get children categories use:
1545 * coursecat::get($id)->get_children()
1546 * To get list of courses use:
1547 * coursecat::get($id)->get_courses()
1549 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1551 function get_course_category_tree($id = 0, $depth = 0) {
1552 throw new coding_exception('Function get_course_category_tree() is removed, please use course renderer or coursecat class,
1553 see function phpdocs for more info');
1557 * @deprecated since 2.5
1559 * To print a generic list of courses use:
1560 * $renderer = $PAGE->get_renderer('core', 'course');
1561 * echo $renderer->courses_list($courses);
1563 * To print list of all courses:
1564 * $renderer = $PAGE->get_renderer('core', 'course');
1565 * echo $renderer->frontpage_available_courses();
1567 * To print list of courses inside category:
1568 * $renderer = $PAGE->get_renderer('core', 'course');
1569 * echo $renderer->course_category($category); // this will also print subcategories
1571 function print_courses($category) {
1572 throw new coding_exception('Function print_courses() is removed, please use course renderer');
1576 * @deprecated since 2.5
1578 * Please use course renderer to display a course information box.
1579 * $renderer = $PAGE->get_renderer('core', 'course');
1580 * echo $renderer->courses_list($courses); // will print list of courses
1581 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
1583 function print_course($course, $highlightterms = '') {
1584 throw new coding_exception('Function print_course() is removed, please use course renderer');
1588 * @deprecated since 2.5
1590 * This function is not used any more in moodle core and course renderer does not have render function for it.
1591 * Combo list on the front page is displayed as:
1592 * $renderer = $PAGE->get_renderer('core', 'course');
1593 * echo $renderer->frontpage_combo_list()
1595 * The new class {@link coursecat} stores the information about course category tree
1596 * To get children categories use:
1597 * coursecat::get($id)->get_children()
1598 * To get list of courses use:
1599 * coursecat::get($id)->get_courses()
1601 function get_category_courses_array($categoryid = 0) {
1602 throw new coding_exception('Function get_category_courses_array() is removed, please use methods of coursecat class');
1606 * @deprecated since 2.5
1608 function get_category_courses_array_recursively(array &$flattened, $category) {
1609 throw new coding_exception('Function get_category_courses_array_recursively() is removed, please use methods of coursecat class', DEBUG_DEVELOPER
);
1613 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
1615 function blog_get_context_url($context=null) {
1616 throw new coding_exception('Function blog_get_context_url() is removed, getting params from context is not reliable for blogs.');
1620 * @deprecated since 2.5
1622 * To get list of all courses with course contacts ('managers') use
1623 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
1625 * To get list of courses inside particular category use
1626 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
1628 * Additionally you can specify sort order, offset and maximum number of courses,
1629 * see {@link coursecat::get_courses()}
1631 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
1632 throw new coding_exception('Function get_courses_wmanagers() is removed, please use coursecat::get_courses()');
1636 * @deprecated since 2.5
1638 function convert_tree_to_html($tree, $row=0) {
1639 throw new coding_exception('Function convert_tree_to_html() is removed. Consider using class tabtree and core_renderer::render_tabtree()');
1643 * @deprecated since 2.5
1645 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
1646 throw new coding_exception('Function convert_tabrows_to_tree() is removed. Consider using class tabtree');
1650 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
1652 function can_use_rotated_text() {
1653 debugging('can_use_rotated_text() is removed. JS feature detection is used automatically.');
1657 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
1658 * @see context::instance_by_id($id)
1660 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING
) {
1661 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
1665 * Returns system context or null if can not be created yet.
1667 * @see context_system::instance()
1668 * @deprecated since 2.2
1669 * @param bool $cache use caching
1670 * @return context system context (null if context table not created yet)
1672 function get_system_context($cache = true) {
1673 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER
);
1674 return context_system
::instance(0, IGNORE_MISSING
, $cache);
1678 * @see context::get_parent_context_ids()
1679 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
1681 function get_parent_contexts(context
$context, $includeself = false) {
1682 throw new coding_exception('get_parent_contexts() is removed, please use $context->get_parent_context_ids() instead.');
1686 * @deprecated since Moodle 2.2
1687 * @see context::get_parent_context()
1689 function get_parent_contextid(context
$context) {
1690 throw new coding_exception('get_parent_contextid() is removed, please use $context->get_parent_context() instead.');
1694 * @see context::get_child_contexts()
1695 * @deprecated since 2.2
1697 function get_child_contexts(context
$context) {
1698 throw new coding_exception('get_child_contexts() is removed, please use $context->get_child_contexts() instead.');
1702 * @see context_helper::create_instances()
1703 * @deprecated since 2.2
1705 function create_contexts($contextlevel = null, $buildpaths = true) {
1706 throw new coding_exception('create_contexts() is removed, please use context_helper::create_instances() instead.');
1710 * @see context_helper::cleanup_instances()
1711 * @deprecated since 2.2
1713 function cleanup_contexts() {
1714 throw new coding_exception('cleanup_contexts() is removed, please use context_helper::cleanup_instances() instead.');
1718 * Populate context.path and context.depth where missing.
1720 * @deprecated since 2.2
1722 function build_context_path($force = false) {
1723 throw new coding_exception('build_context_path() is removed, please use context_helper::build_all_paths() instead.');
1727 * @deprecated since 2.2
1729 function rebuild_contexts(array $fixcontexts) {
1730 throw new coding_exception('rebuild_contexts() is removed, please use $context->reset_paths(true) instead.');
1734 * @deprecated since Moodle 2.2
1735 * @see context_helper::preload_course()
1737 function preload_course_contexts($courseid) {
1738 throw new coding_exception('preload_course_contexts() is removed, please use context_helper::preload_course() instead.');
1742 * @deprecated since Moodle 2.2
1743 * @see context::update_moved()
1745 function context_moved(context
$context, context
$newparent) {
1746 throw new coding_exception('context_moved() is removed, please use context::update_moved() instead.');
1750 * @see context::get_capabilities()
1751 * @deprecated since 2.2
1753 function fetch_context_capabilities(context
$context) {
1754 throw new coding_exception('fetch_context_capabilities() is removed, please use $context->get_capabilities() instead.');
1758 * @deprecated since 2.2
1759 * @see context_helper::preload_from_record()
1761 function context_instance_preload(stdClass
$rec) {
1762 throw new coding_exception('context_instance_preload() is removed, please use context_helper::preload_from_record() instead.');
1766 * Returns context level name
1768 * @deprecated since 2.2
1769 * @see context_helper::get_level_name()
1771 function get_contextlevel_name($contextlevel) {
1772 throw new coding_exception('get_contextlevel_name() is removed, please use context_helper::get_level_name() instead.');
1776 * @deprecated since 2.2
1777 * @see context::get_context_name()
1779 function print_context_name(context
$context, $withprefix = true, $short = false) {
1780 throw new coding_exception('print_context_name() is removed, please use $context->get_context_name() instead.');
1784 * @deprecated since 2.2, use $context->mark_dirty() instead
1785 * @see context::mark_dirty()
1787 function mark_context_dirty($path) {
1788 throw new coding_exception('mark_context_dirty() is removed, please use $context->mark_dirty() instead.');
1792 * @deprecated since Moodle 2.2
1793 * @see context_helper::delete_instance() or context::delete_content()
1795 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1796 if ($deleterecord) {
1797 throw new coding_exception('delete_context() is removed, please use context_helper::delete_instance() instead.');
1799 throw new coding_exception('delete_context() is removed, please use $context->delete_content() instead.');
1804 * @deprecated since 2.2
1805 * @see context::get_url()
1807 function get_context_url(context
$context) {
1808 throw new coding_exception('get_context_url() is removed, please use $context->get_url() instead.');
1812 * @deprecated since 2.2
1813 * @see context::get_course_context()
1815 function get_course_context(context
$context) {
1816 throw new coding_exception('get_course_context() is removed, please use $context->get_course_context(true) instead.');
1820 * @deprecated since 2.2
1821 * @see enrol_get_users_courses()
1823 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1825 throw new coding_exception('get_user_courses_bycap() is removed, please use enrol_get_users_courses() instead.');
1829 * @deprecated since Moodle 2.2
1831 function get_role_context_caps($roleid, context
$context) {
1832 throw new coding_exception('get_role_context_caps() is removed, it is really slow. Don\'t use it.');
1836 * @see context::get_course_context()
1837 * @deprecated since 2.2
1839 function get_courseid_from_context(context
$context) {
1840 throw new coding_exception('get_courseid_from_context() is removed, please use $context->get_course_context(false) instead.');
1844 * If you are using this methid, you should have something like this:
1846 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1848 * To prevent the use of this deprecated function, replace the line above with something similar to this:
1850 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1852 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1854 * $params = array('contextlevel' => CONTEXT_COURSE);
1856 * @see context_helper:;get_preload_record_columns_sql()
1857 * @deprecated since 2.2
1859 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
1860 throw new coding_exception('context_instance_preload_sql() is removed, please use context_helper::get_preload_record_columns_sql() instead.');
1864 * @deprecated since 2.2
1865 * @see context::get_parent_context_ids()
1867 function get_related_contexts_string(context
$context) {
1868 throw new coding_exception('get_related_contexts_string() is removed, please use $context->get_parent_context_ids(true) instead.');
1872 * @deprecated since 2.6
1873 * @see core_component::get_plugin_list_with_file()
1875 function get_plugin_list_with_file($plugintype, $file, $include = false) {
1876 throw new coding_exception('get_plugin_list_with_file() is removed, please use core_component::get_plugin_list_with_file() instead.');
1880 * @deprecated since 2.6
1882 function check_browser_operating_system($brand) {
1883 throw new coding_exception('check_browser_operating_system is removed, please update your code to use core_useragent instead.');
1887 * @deprecated since 2.6
1889 function check_browser_version($brand, $version = null) {
1890 throw new coding_exception('check_browser_version is removed, please update your code to use core_useragent instead.');
1894 * @deprecated since 2.6
1896 function get_device_type() {
1897 throw new coding_exception('get_device_type is removed, please update your code to use core_useragent instead.');
1901 * @deprecated since 2.6
1903 function get_device_type_list($incusertypes = true) {
1904 throw new coding_exception('get_device_type_list is removed, please update your code to use core_useragent instead.');
1908 * @deprecated since 2.6
1910 function get_selected_theme_for_device_type($devicetype = null) {
1911 throw new coding_exception('get_selected_theme_for_device_type is removed, please update your code to use core_useragent instead.');
1915 * @deprecated since 2.6
1917 function get_device_cfg_var_name($devicetype = null) {
1918 throw new coding_exception('get_device_cfg_var_name is removed, please update your code to use core_useragent instead.');
1922 * @deprecated since 2.6
1924 function set_user_device_type($newdevice) {
1925 throw new coding_exception('set_user_device_type is removed, please update your code to use core_useragent instead.');
1929 * @deprecated since 2.6
1931 function get_user_device_type() {
1932 throw new coding_exception('get_user_device_type is removed, please update your code to use core_useragent instead.');
1936 * @deprecated since 2.6
1938 function get_browser_version_classes() {
1939 throw new coding_exception('get_browser_version_classes is removed, please update your code to use core_useragent instead.');
1943 * @deprecated since Moodle 2.6
1944 * @see core_user::get_support_user()
1946 function generate_email_supportuser() {
1947 throw new coding_exception('generate_email_supportuser is removed, please use core_user::get_support_user');
1951 * @deprecated since Moodle 2.6
1953 function badges_get_issued_badge_info($hash) {
1954 throw new coding_exception('Function badges_get_issued_badge_info() is removed. Please use core_badges_assertion class and methods to generate badge assertion.');
1958 * @deprecated since 2.6
1960 function can_use_html_editor() {
1961 throw new coding_exception('can_use_html_editor is removed, please update your code to assume it returns true.');
1966 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
1968 function count_login_failures($mode, $username, $lastlogin) {
1969 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
1973 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
1975 function ajaxenabled(array $browsers = null) {
1976 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
1980 * @deprecated Since Moodle 2.7 MDL-44070
1982 function coursemodule_visible_for_user($cm, $userid=0) {
1983 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
1984 please use \core_availability\info_module::is_user_visible()');
1988 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
1990 function enrol_cohort_get_cohorts(course_enrolment_manager
$manager) {
1991 throw new coding_exception('Function enrol_cohort_get_cohorts() is removed, use enrol_cohort_search_cohorts() or '.
1992 'cohort_get_available_cohorts() instead');
1996 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
1997 * takes into account current context
1999 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
2001 function enrol_cohort_can_view_cohort($cohortid) {
2002 throw new coding_exception('Function enrol_cohort_can_view_cohort() is removed, use cohort_can_view_cohort() instead');
2006 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
2008 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
2010 function cohort_get_visible_list($course, $onlyenrolled=true) {
2011 throw new coding_exception('Function cohort_get_visible_list() is removed. Please use function cohort_get_available_cohorts() ".
2012 "that correctly checks capabilities.');
2016 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2018 function enrol_cohort_enrol_all_users(course_enrolment_manager
$manager, $cohortid, $roleid) {
2019 throw new coding_exception('enrol_cohort_enrol_all_users() is removed. This functionality is moved to enrol_manual.');
2023 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2025 function enrol_cohort_search_cohorts(course_enrolment_manager
$manager, $offset = 0, $limit = 25, $search = '') {
2026 throw new coding_exception('enrol_cohort_search_cohorts() is removed. This functionality is moved to enrol_manual.');
2029 /* === Apis deprecated in since Moodle 2.9 === */
2032 * Is $USER one of the supplied users?
2034 * $user2 will be null if viewing a user's recent conversations
2036 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
2038 function message_current_user_is_involved($user1, $user2) {
2039 throw new coding_exception('message_current_user_is_involved() can not be used any more.');
2043 * Print badges on user profile page.
2045 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
2047 function profile_display_badges($userid, $courseid = 0) {
2048 throw new coding_exception('profile_display_badges() can not be used any more.');
2052 * Adds user preferences elements to user edit form.
2054 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
2056 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
2057 throw new coding_exception('useredit_shared_definition_preferences() can not be used any more.');
2062 * Convert region timezone to php supported timezone
2064 * @deprecated since Moodle 2.9
2066 function calendar_normalize_tz($tz) {
2067 throw new coding_exception('calendar_normalize_tz() can not be used any more, please use core_date::normalise_timezone() instead.');
2071 * Returns a float which represents the user's timezone difference from GMT in hours
2072 * Checks various settings and picks the most dominant of those which have a value
2073 * @deprecated since Moodle 2.9
2075 function get_user_timezone_offset($tz = 99) {
2076 throw new coding_exception('get_user_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2081 * Returns an int which represents the systems's timezone difference from GMT in seconds
2082 * @deprecated since Moodle 2.9
2084 function get_timezone_offset($tz) {
2085 throw new coding_exception('get_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2089 * Returns a list of timezones in the current language.
2090 * @deprecated since Moodle 2.9
2092 function get_list_of_timezones() {
2093 throw new coding_exception('get_list_of_timezones() can not be used any more, please use core_date::get_list_of_timezones() instead');
2097 * Previous internal API, it was not supposed to be used anywhere.
2098 * @deprecated since Moodle 2.9
2100 function update_timezone_records($timezones) {
2101 throw new coding_exception('update_timezone_records() can not be used any more, please use standard PHP DateTime class instead');
2105 * Previous internal API, it was not supposed to be used anywhere.
2106 * @deprecated since Moodle 2.9
2108 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2109 throw new coding_exception('calculate_user_dst_table() can not be used any more, please use standard PHP DateTime class instead');
2113 * Previous internal API, it was not supposed to be used anywhere.
2114 * @deprecated since Moodle 2.9
2116 function dst_changes_for_year($year, $timezone) {
2117 throw new coding_exception('dst_changes_for_year() can not be used any more, please use standard DateTime class instead');
2121 * Previous internal API, it was not supposed to be used anywhere.
2122 * @deprecated since Moodle 2.9
2124 function get_timezone_record($timezonename) {
2125 throw new coding_exception('get_timezone_record() can not be used any more, please use standard PHP DateTime class instead');
2128 /* === Apis deprecated since Moodle 3.0 === */
2130 * @deprecated since Moodle 3.0 MDL-49360 - please do not use this function any more.
2132 function get_referer($stripquery = true) {
2133 throw new coding_exception('get_referer() can not be used any more. Please use get_local_referer() instead.');
2137 * @deprecated since Moodle 3.0 use \core_useragent::is_web_crawler instead.
2139 function is_web_crawler() {
2140 throw new coding_exception('is_web_crawler() can not be used any more. Please use core_useragent::is_web_crawler() instead.');
2144 * @deprecated since Moodle 3.0 MDL-50287 - please do not use this function any more.
2146 function completion_cron() {
2147 throw new coding_exception('completion_cron() can not be used any more. Functionality has been moved to scheduled tasks.');
2151 * @deprecated since 3.0
2153 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $unused = '') {
2154 throw new coding_exception('Function coursetag_get_tags() can not be used any more. Userid is no longer used for tagging courses.');
2158 * @deprecated since 3.0
2160 function coursetag_get_all_tags($unused='', $numtags=0) {
2161 throw new coding_exception('Function coursetag_get_all_tag() can not be used any more. Userid is no longer used for tagging courses.');
2165 * @deprecated since 3.0
2167 function coursetag_get_jscript() {
2168 throw new coding_exception('Function coursetag_get_jscript() can not be used any more and is obsolete.');
2172 * @deprecated since 3.0
2174 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
2175 throw new coding_exception('Function coursetag_get_jscript_links() can not be used any more and is obsolete.');
2179 * @deprecated since 3.0
2181 function coursetag_get_records($courseid, $userid) {
2182 throw new coding_exception('Function coursetag_get_records() can not be used any more. Userid is no longer used for tagging courses.');
2186 * @deprecated since 3.0
2188 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
2189 throw new coding_exception('Function coursetag_store_keywords() can not be used any more. Userid is no longer used for tagging courses.');
2193 * @deprecated since 3.0
2195 function coursetag_delete_keyword($tagid, $userid, $courseid) {
2196 throw new coding_exception('Function coursetag_delete_keyword() can not be used any more. Userid is no longer used for tagging courses.');
2200 * @deprecated since 3.0
2202 function coursetag_get_tagged_courses($tagid) {
2203 throw new coding_exception('Function coursetag_get_tagged_courses() can not be used any more. Userid is no longer used for tagging courses.');
2207 * @deprecated since 3.0
2209 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
2210 throw new coding_exception('Function coursetag_delete_course_tags() is deprecated. Use core_tag_tag::remove_all_item_tags().');
2214 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
2215 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
2218 * @deprecated since 3.1
2219 * @param string $tagid tagid to modify
2220 * @param string $type either 'default' or 'official'
2221 * @return bool true on success, false otherwise
2223 function tag_type_set($tagid, $type) {
2224 debugging('Function tag_type_set() is deprecated and can be replaced with use core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER
);
2225 if ($tag = core_tag_tag
::get($tagid, '*')) {
2226 return $tag->update(array('isstandard' => ($type === 'official') ?
1 : 0));
2232 * Set the description of a tag
2235 * @deprecated since 3.1
2236 * @param int $tagid the id of the tag
2237 * @param string $description the tag's description string to be set
2238 * @param int $descriptionformat the moodle text format of the description
2239 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
2240 * @return bool true on success, false otherwise
2242 function tag_description_set($tagid, $description, $descriptionformat) {
2243 debugging('Function tag_type_set() is deprecated and can be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER
);
2244 if ($tag = core_tag_tag
::get($tagid, '*')) {
2245 return $tag->update(array('description' => $description, 'descriptionformat' => $descriptionformat));
2251 * Get the array of db record of tags associated to a record (instances).
2254 * @deprecated since 3.1
2255 * @param string $record_type the record type for which we want to get the tags
2256 * @param int $record_id the record id for which we want to get the tags
2257 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2258 * @param int $userid (optional) only required for course tagging
2259 * @return array the array of tags
2261 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
2262 debugging('Method tag_get_tags() is deprecated and replaced with core_tag_tag::get_item_tags(). ' .
2263 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER
);
2264 $standardonly = ($type === 'official' ? core_tag_tag
::STANDARD_ONLY
:
2265 (!empty($type) ? core_tag_tag
::NOT_STANDARD_ONLY
: core_tag_tag
::BOTH_STANDARD_AND_NOT
));
2266 $tags = core_tag_tag
::get_item_tags(null, $record_type, $record_id, $standardonly, $userid);
2268 foreach ($tags as $id => $t) {
2269 $rv[$id] = $t->to_object();
2275 * Get the array of tags display names, indexed by id.
2278 * @deprecated since 3.1
2279 * @param string $record_type the record type for which we want to get the tags
2280 * @param int $record_id the record id for which we want to get the tags
2281 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2282 * @return array the array of tags (with the value returned by core_tag_tag::make_display_name), indexed by id
2284 function tag_get_tags_array($record_type, $record_id, $type=null) {
2285 debugging('Method tag_get_tags_array() is deprecated and replaced with core_tag_tag::get_item_tags_array(). ' .
2286 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER
);
2287 $standardonly = ($type === 'official' ? core_tag_tag
::STANDARD_ONLY
:
2288 (!empty($type) ? core_tag_tag
::NOT_STANDARD_ONLY
: core_tag_tag
::BOTH_STANDARD_AND_NOT
));
2289 return core_tag_tag
::get_item_tags_array('', $record_type, $record_id, $standardonly);
2293 * Get a comma-separated string of tags associated to a record.
2295 * Use {@link tag_get_tags()} to get the same information in an array.
2298 * @deprecated since 3.1
2299 * @param string $record_type the record type for which we want to get the tags
2300 * @param int $record_id the record id for which we want to get the tags
2301 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
2302 * @param string $type either 'official' or 'default', if null, all tags are returned
2303 * @return string the comma-separated list of tags.
2305 function tag_get_tags_csv($record_type, $record_id, $html=null, $type=null) {
2306 global $CFG, $OUTPUT;
2307 debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' .
2308 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' .
2309 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER
);
2310 $standardonly = ($type === 'official' ? core_tag_tag
::STANDARD_ONLY
:
2311 (!empty($type) ? core_tag_tag
::NOT_STANDARD_ONLY
: core_tag_tag
::BOTH_STANDARD_AND_NOT
));
2312 if ($html != TAG_RETURN_TEXT
) {
2313 return $OUTPUT->tag_list(core_tag_tag
::get_item_tags('', $record_type, $record_id, $standardonly), '');
2315 return join(', ', core_tag_tag
::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false));
2320 * Get an array of tag ids associated to a record.
2323 * @deprecated since 3.1
2324 * @param string $record_type the record type for which we want to get the tags
2325 * @param int $record_id the record id for which we want to get the tags
2326 * @return array tag ids, indexed and sorted by 'ordering'
2328 function tag_get_tags_ids($record_type, $record_id) {
2329 debugging('Method tag_get_tags_ids() is deprecated. Please consider using core_tag_tag::get_item_tags() or similar methods.', DEBUG_DEVELOPER
);
2331 $tagobjects = core_tag_tag
::get_item_tags(null, $record_type, $record_id);
2332 foreach ($tagobjects as $tagobject) {
2333 $tag = $tagobject->to_object();
2334 if ( array_key_exists($tag->ordering
, $tag_ids) ) {
2337 $tag_ids[$tag->ordering
] = $tag->id
;
2344 * Returns the database ID of a set of tags.
2346 * @deprecated since 3.1
2347 * @param mixed $tags one tag, or array of tags, to look for.
2348 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
2349 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
2350 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
2351 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
2353 function tag_get_id($tags, $return_value = null) {
2355 debugging('Method tag_get_id() is deprecated and can be replaced with core_tag_tag::get_by_name() or core_tag_tag::get_by_name_bulk(). ' .
2356 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER
);
2358 if (!is_array($tags)) {
2359 if(is_null($return_value) ||
$return_value == TAG_RETURN_OBJECT
) {
2360 if ($tagobject = core_tag_tag
::get_by_name(core_tag_collection
::get_default(), $tags)) {
2361 return $tagobject->id
;
2366 $tags = array($tags);
2369 $records = core_tag_tag
::get_by_name_bulk(core_tag_collection
::get_default(), $tags,
2370 $return_value == TAG_RETURN_OBJECT ?
'*' : 'id, name');
2371 foreach ($records as $name => $record) {
2372 if ($return_value != TAG_RETURN_OBJECT
) {
2373 $records[$name] = $record->id ?
$record->id
: null;
2375 $records[$name] = $record->to_object();
2382 * Change the "value" of a tag, and update the associated 'name'.
2385 * @deprecated since 3.1
2386 * @param int $tagid the id of the tag to modify
2387 * @param string $newrawname the new rawname
2388 * @return bool true on success, false otherwise
2390 function tag_rename($tagid, $newrawname) {
2391 debugging('Function tag_rename() is deprecated and may be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER
);
2392 if ($tag = core_tag_tag
::get($tagid, '*')) {
2393 return $tag->update(array('rawname' => $newrawname));
2399 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
2402 * @deprecated since 3.1
2403 * @param string $record_type the type of the record for which to remove the instance
2404 * @param int $record_id the id of the record for which to remove the instance
2405 * @param int $tagid the tagid that needs to be removed
2406 * @param int $userid (optional) the userid
2407 * @return bool true on success, false otherwise
2409 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
2410 debugging('Function tag_delete_instance() is deprecated and replaced with core_tag_tag::remove_item_tag() instead. ' .
2411 'Component is required for retrieving instances', DEBUG_DEVELOPER
);
2412 $tag = core_tag_tag
::get($tagid);
2413 core_tag_tag
::remove_item_tag('', $record_type, $record_id, $tag->rawname
, $userid);
2417 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
2420 * @deprecated since 3.1
2422 * @param string $tag tag to look for
2423 * @param string $type type to restrict search to. If null, every matching record will be returned
2424 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
2425 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
2426 * @return array of matching objects, indexed by record id, from the table containing the type requested
2428 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
2429 debugging('Function tag_find_records() is deprecated and replaced with core_tag_tag::get_by_name()->get_tagged_items(). '.
2430 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER
);
2432 if (!$tag ||
!$type) {
2436 $tagobject = core_tag_tag
::get_by_name(core_tag_area
::get_collection('', $type), $tag);
2437 return $tagobject->get_tagged_items('', $type, $limitfrom, $limitnum);
2441 * Adds one or more tag in the database. This function should not be called directly : you should
2445 * @deprecated since 3.1
2446 * @param mixed $tags one tag, or an array of tags, to be created
2447 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
2448 * value at this time). An official tag is kept even if there are no records tagged with it.
2449 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
2452 function tag_add($tags, $type="default") {
2453 debugging('Function tag_add() is deprecated. You can use core_tag_tag::create_if_missing(), however it should not be necessary ' .
2454 'since tags are created automatically when assigned to items', DEBUG_DEVELOPER
);
2455 if (!is_array($tags)) {
2456 $tags = array($tags);
2458 $objects = core_tag_tag
::create_if_missing(core_tag_collection
::get_default(), $tags,
2459 $type === 'official');
2461 // New function returns the tags in different format, for BC we keep the format that this function used to have.
2463 foreach ($objects as $name => $tagobject) {
2464 if (isset($tagobject->id
)) {
2465 $rv[$tagobject->name
] = $tagobject->id
;
2474 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
2477 * @deprecated since 3.1
2478 * @param string $record_type the type of the record that will be tagged
2479 * @param int $record_id the id of the record that will be tagged
2480 * @param string $tagid the tag id to set on the record.
2481 * @param int $ordering the order of the instance for this record
2482 * @param int $userid (optional) only required for course tagging
2483 * @param string|null $component the component that was tagged
2484 * @param int|null $contextid the context id of where this tag was assigned
2485 * @return bool true on success, false otherwise
2487 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
2489 $message = 'Function tag_assign() is deprecated. Use core_tag_tag::set_item_tags() or core_tag_tag::add_item_tag() instead. ' .
2490 'Tag instance ordering should not be set manually';
2491 if ($component === null ||
$contextid === null) {
2492 $message .= '. You should specify the component and contextid of the item being tagged in your call to tag_assign.';
2494 debugging($message, DEBUG_DEVELOPER
);
2497 $context = context
::instance_by_id($contextid);
2499 $context = context_system
::instance();
2503 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST
);
2505 $taginstanceid = core_tag_tag
::add_item_tag($component, $record_type, $record_id, $context, $tag->rawname
, $userid);
2507 // Alter the "ordering" of tag_instance. This should never be done manually and only remains here for the backward compatibility.
2508 $taginstance = new stdClass();
2509 $taginstance->id
= $taginstanceid;
2510 $taginstance->ordering
= $ordering;
2511 $taginstance->timemodified
= time();
2513 $DB->update_record('tag_instance', $taginstance);
2519 * Count how many records are tagged with a specific tag.
2522 * @deprecated since 3.1
2523 * @param string $record_type record to look for ('post', 'user', etc.)
2524 * @param int $tagid is a single tag id
2525 * @return int number of mathing tags.
2527 function tag_record_count($record_type, $tagid) {
2528 debugging('Method tag_record_count() is deprecated and replaced with core_tag_tag::get($tagid)->count_tagged_items(). '.
2529 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER
);
2530 return core_tag_tag
::get($tagid)->count_tagged_items('', $record_type);
2534 * Determine if a record is tagged with a specific tag
2537 * @deprecated since 3.1
2538 * @param string $record_type the record type to look for
2539 * @param int $record_id the record id to look for
2540 * @param string $tag a tag name
2541 * @return bool/int true if it is tagged, 0 (false) otherwise
2543 function tag_record_tagged_with($record_type, $record_id, $tag) {
2544 debugging('Method tag_record_tagged_with() is deprecated and replaced with core_tag_tag::get($tagid)->is_item_tagged_with(). '.
2545 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER
);
2546 return core_tag_tag
::is_item_tagged_with('', $record_type, $record_id, $tag);
2550 * Flag a tag as inappropriate.
2552 * @deprecated since 3.1
2553 * @param int|array $tagids a single tagid, or an array of tagids
2555 function tag_set_flag($tagids) {
2556 debugging('Function tag_set_flag() is deprecated and replaced with core_tag_tag::get($tagid)->flag().', DEBUG_DEVELOPER
);
2557 $tagids = (array) $tagids;
2558 foreach ($tagids as $tagid) {
2559 if ($tag = core_tag_tag
::get($tagid, '*')) {
2566 * Remove the inappropriate flag on a tag.
2568 * @deprecated since 3.1
2569 * @param int|array $tagids a single tagid, or an array of tagids
2571 function tag_unset_flag($tagids) {
2572 debugging('Function tag_unset_flag() is deprecated and replaced with core_tag_tag::get($tagid)->reset_flag().', DEBUG_DEVELOPER
);
2573 $tagids = (array) $tagids;
2574 foreach ($tagids as $tagid) {
2575 if ($tag = core_tag_tag
::get($tagid, '*')) {
2582 * Prints or returns a HTML tag cloud with varying classes styles depending on the popularity and type of each tag.
2584 * @deprecated since 3.1
2586 * @param array $tagset Array of tags to display
2587 * @param int $nr_of_tags Limit for the number of tags to return/display, used if $tagset is null
2588 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2589 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
2590 * @return string|null a HTML string or null if this function does the output
2592 function tag_print_cloud($tagset=null, $nr_of_tags=150, $return=false, $sort='') {
2595 debugging('Function tag_print_cloud() is deprecated and replaced with function core_tag_collection::get_tag_cloud(), '
2596 . 'templateable core_tag\output\tagcloud and template core_tag/tagcloud.', DEBUG_DEVELOPER
);
2598 // Set up sort global - used to pass sort type into core_tag_collection::cloud_sort through usort() avoiding multiple sort functions.
2599 if ($sort == 'popularity') {
2601 } else if ($sort == 'date') {
2602 $sort = 'timemodified';
2607 if (is_null($tagset)) {
2608 // No tag set received, so fetch tags from database.
2609 // Always add query by tagcollid even when it's not known to make use of the table index.
2610 $tagcloud = core_tag_collection
::get_tag_cloud(0, false, $nr_of_tags, $sort);
2612 $tagsincloud = $tagset;
2615 foreach ($tagsincloud as $tag) {
2619 core_tag_collection
::$cloudsortfield = $sort;
2620 usort($tagsincloud, "core_tag_collection::cloud_sort");
2622 $tagcloud = new \core_tag\output\tagcloud
($tagsincloud);
2625 $output = $OUTPUT->render_from_template('core_tag/tagcloud', $tagcloud->export_for_template($OUTPUT));
2634 * Function that returns tags that start with some text, for use by the autocomplete feature
2637 * @deprecated since 3.0
2639 * @param string $text string that the tag names will be matched against
2640 * @return mixed an array of objects, or false if no records were found or an error occured.
2642 function tag_autocomplete($text) {
2643 debugging('Function tag_autocomplete() is deprecated without replacement. ' .
2644 'New form element "tags" does proper autocomplete.', DEBUG_DEVELOPER
);
2646 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
2648 WHERE tg.name LIKE ?", array(core_text
::strtolower($text)."%"));
2652 * Prints a box with the description of a tag and its related tags
2655 * @deprecated since 3.1
2656 * @param stdClass $tag_object
2657 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2658 * @return string/null a HTML box showing a description of the tag object and it's relationsips or null if output is done directly
2661 function tag_print_description_box($tag_object, $return=false) {
2662 global $USER, $CFG, $OUTPUT;
2663 require_once($CFG->libdir
.'/filelib.php');
2665 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2666 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER
);
2668 $relatedtags = array();
2669 if ($tag = core_tag_tag
::get($tag_object->id
)) {
2670 $relatedtags = $tag->get_related_tags();
2673 $content = !empty($tag_object->description
);
2677 $output .= $OUTPUT->box_start('generalbox tag-description');
2680 if (!empty($tag_object->description
)) {
2681 $options = new stdClass();
2682 $options->para
= false;
2683 $options->overflowdiv
= true;
2684 $tag_object->description
= file_rewrite_pluginfile_urls($tag_object->description
, 'pluginfile.php', context_system
::instance()->id
, 'tag', 'description', $tag_object->id
);
2685 $output .= format_text($tag_object->description
, $tag_object->descriptionformat
, $options);
2689 $output .= $OUTPUT->box_end();
2693 $output .= $OUTPUT->tag_list($relatedtags, get_string('relatedtags', 'tag'), 'tag-relatedtags');
2704 * Prints a box that contains the management links of a tag
2706 * @deprecated since 3.1
2707 * @param core_tag_tag|stdClass $tag_object
2708 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2709 * @return string|null a HTML string or null if this function does the output
2711 function tag_print_management_box($tag_object, $return=false) {
2712 global $USER, $CFG, $OUTPUT;
2714 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2715 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER
);
2717 $tagname = core_tag_tag
::make_display_name($tag_object);
2720 if (!isguestuser()) {
2721 $output .= $OUTPUT->box_start('box','tag-management-box');
2722 $systemcontext = context_system
::instance();
2725 // Add a link for users to add/remove this from their interests
2726 if (core_tag_tag
::is_enabled('core', 'user') && core_tag_area
::get_collection('core', 'user') == $tag_object->tagcollid
) {
2727 if (core_tag_tag
::is_item_tagged_with('core', 'user', $USER->id
, $tag_object->name
)) {
2728 $links[] = '<a href="'. $CFG->wwwroot
.'/tag/user.php?action=removeinterest&sesskey='. sesskey() .
2729 '&tag='. rawurlencode($tag_object->name
) .'">'.
2730 get_string('removetagfrommyinterests', 'tag', $tagname) .'</a>';
2732 $links[] = '<a href="'. $CFG->wwwroot
.'/tag/user.php?action=addinterest&sesskey='. sesskey() .
2733 '&tag='. rawurlencode($tag_object->name
) .'">'.
2734 get_string('addtagtomyinterests', 'tag', $tagname) .'</a>';
2738 // Flag as inappropriate link. Only people with moodle/tag:flag capability.
2739 if (has_capability('moodle/tag:flag', $systemcontext)) {
2740 $links[] = '<a href="'. $CFG->wwwroot
.'/tag/user.php?action=flaginappropriate&sesskey='.
2741 sesskey() . '&id='. $tag_object->id
. '">'. get_string('flagasinappropriate',
2742 'tag', rawurlencode($tagname)) .'</a>';
2745 // Edit tag: Only people with moodle/tag:edit capability who either have it as an interest or can manage tags
2746 if (has_capability('moodle/tag:edit', $systemcontext) ||
2747 has_capability('moodle/tag:manage', $systemcontext)) {
2748 $links[] = '<a href="' . $CFG->wwwroot
. '/tag/edit.php?id=' . $tag_object->id
. '">' .
2749 get_string('edittag', 'tag') . '</a>';
2752 $output .= implode(' | ', $links);
2753 $output .= $OUTPUT->box_end();
2764 * Prints the tag search box
2766 * @deprecated since 3.1
2767 * @param bool $return if true return html string
2768 * @return string|null a HTML string or null if this function does the output
2770 function tag_print_search_box($return=false) {
2771 global $CFG, $OUTPUT;
2773 debugging('Function tag_print_search_box() is deprecated without replacement. ' .
2774 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER
);
2776 $query = optional_param('query', '', PARAM_RAW
);
2778 $output = $OUTPUT->box_start('','tag-search-box');
2779 $output .= '<form action="'.$CFG->wwwroot
.'/tag/search.php" style="display:inline">';
2781 $output .= '<label class="accesshide" for="searchform_search">'.get_string('searchtags', 'tag').'</label>';
2782 $output .= '<input id="searchform_search" name="query" type="text" size="40" value="'.s($query).'" />';
2783 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
2784 $output .= '</div>';
2785 $output .= '</form>';
2786 $output .= $OUTPUT->box_end();
2797 * Prints the tag search results
2799 * @deprecated since 3.1
2800 * @param string $query text that tag names will be matched against
2801 * @param int $page current page
2802 * @param int $perpage nr of users displayed per page
2803 * @param bool $return if true return html string
2804 * @return string|null a HTML string or null if this function does the output
2806 function tag_print_search_results($query, $page, $perpage, $return=false) {
2807 global $CFG, $USER, $OUTPUT;
2809 debugging('Function tag_print_search_results() is deprecated without replacement. ' .
2810 'In /tag/search.php the search results are printed using the core_tag/tagcloud template.', DEBUG_DEVELOPER
);
2812 $query = clean_param($query, PARAM_TAG
);
2814 $count = count(tag_find_tags($query, false));
2817 if ( $found_tags = tag_find_tags($query, true, $page * $perpage, $perpage) ) {
2818 $tags = array_values($found_tags);
2821 $baseurl = $CFG->wwwroot
.'/tag/search.php?query='. rawurlencode($query);
2824 // link "Add $query to my interests"
2826 if (core_tag_tag
::is_enabled('core', 'user') && !core_tag_tag
::is_item_tagged_with('core', 'user', $USER->id
, $query)) {
2827 $addtaglink = html_writer
::link(new moodle_url('/tag/user.php', array('action' => 'addinterest', 'sesskey' => sesskey(),
2828 'tag' => $query)), get_string('addtagtomyinterests', 'tag', s($query)));
2831 if ( !empty($tags) ) { // there are results to display!!
2832 $output .= $OUTPUT->heading(get_string('searchresultsfor', 'tag', htmlspecialchars($query)) ." : {$count}", 3, 'main');
2834 //print a link "Add $query to my interests"
2835 if (!empty($addtaglink)) {
2836 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2839 $nr_of_lis_per_ul = 6;
2840 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul );
2842 $output .= '<ul id="tag-search-results">';
2843 for($i = 0; $i < $nr_of_uls; $i++
) {
2844 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul) as $tag) {
2846 $tag_link = html_writer
::link(core_tag_tag
::make_url($tag->tagcollid
, $tag->rawname
),
2847 core_tag_tag
::make_display_name($tag));
2848 $output .= $tag_link;
2853 $output .= '<div> </div>'; // <-- small layout hack in order to look good in Firefox
2855 $output .= $OUTPUT->paging_bar($count, $page, $perpage, $baseurl);
2857 else { //no results were found!!
2858 $output .= $OUTPUT->heading(get_string('noresultsfor', 'tag', htmlspecialchars($query)), 3, 'main');
2860 //print a link "Add $query to my interests"
2861 if (!empty($addtaglink)) {
2862 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2875 * Prints a table of the users tagged with the tag passed as argument
2877 * @deprecated since 3.1
2878 * @param stdClass $tagobject the tag we wish to return data for
2879 * @param int $limitfrom (optional, required if $limitnum is set) prints users starting at this point.
2880 * @param int $limitnum (optional, required if $limitfrom is set) prints this many users.
2881 * @param bool $return if true return html string
2882 * @return string|null a HTML string or null if this function does the output
2884 function tag_print_tagged_users_table($tagobject, $limitfrom='', $limitnum='', $return=false) {
2886 debugging('Function tag_print_tagged_users_table() is deprecated without replacement. ' .
2887 'See core_user_renderer for similar code.', DEBUG_DEVELOPER
);
2889 //List of users with this tag
2890 $tagobject = core_tag_tag
::get($tagobject->id
);
2891 $userlist = $tagobject->get_tagged_items('core', 'user', $limitfrom, $limitnum);
2893 $output = tag_print_user_list($userlist, true);
2904 * Prints an individual user box
2906 * @deprecated since 3.1
2907 * @param user_object $user (contains the following fields: id, firstname, lastname and picture)
2908 * @param bool $return if true return html string
2909 * @return string|null a HTML string or null if this function does the output
2911 function tag_print_user_box($user, $return=false) {
2912 global $CFG, $OUTPUT;
2914 debugging('Function tag_print_user_box() is deprecated without replacement. ' .
2915 'See core_user_renderer for similar code.', DEBUG_DEVELOPER
);
2917 $usercontext = context_user
::instance($user->id
);
2920 if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) ||
has_coursecontact_role($user->id
))) {
2921 $profilelink = $CFG->wwwroot
.'/user/view.php?id='. $user->id
;
2924 $output = $OUTPUT->box_start('user-box', 'user'. $user->id
);
2925 $fullname = fullname($user);
2928 if (!empty($profilelink)) {
2929 $output .= '<a href="'. $profilelink .'">';
2933 $output .= $OUTPUT->user_picture($user, array('size'=>100));
2934 $output .= '<br />';
2936 if (!empty($profilelink)) {
2940 //truncate name if it's too big
2941 if (core_text
::strlen($fullname) > 26) {
2942 $fullname = core_text
::substr($fullname, 0, 26) .'...';
2945 $output .= '<strong>'. $fullname .'</strong>';
2946 $output .= $OUTPUT->box_end();
2957 * Prints a list of users
2959 * @deprecated since 3.1
2960 * @param array $userlist an array of user objects
2961 * @param bool $return if true return html string, otherwise output the result
2962 * @return string|null a HTML string or null if this function does the output
2964 function tag_print_user_list($userlist, $return=false) {
2966 debugging('Function tag_print_user_list() is deprecated without replacement. ' .
2967 'See core_user_renderer for similar code.', DEBUG_DEVELOPER
);
2969 $output = '<div><ul class="inline-list">';
2971 foreach ($userlist as $user){
2972 $output .= '<li>'. tag_print_user_box($user, true) ."</li>\n";
2974 $output .= "</ul></div>\n";
2985 * Function that returns the name that should be displayed for a specific tag
2989 * @deprecated since 3.1
2990 * @param stdClass|core_tag_tag $tagobject a line out of tag table, as returned by the adobd functions
2991 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
2994 function tag_display_name($tagobject, $html=TAG_RETURN_HTML
) {
2995 debugging('Function tag_display_name() is deprecated. Use core_tag_tag::make_display_name().', DEBUG_DEVELOPER
);
2996 if (!isset($tagobject->name
)) {
2999 return core_tag_tag
::make_display_name($tagobject, $html != TAG_RETURN_TEXT
);
3003 * Function that normalizes a list of tag names.
3006 * @deprecated since 3.1
3007 * @param array/string $rawtags array of tags, or a single tag.
3008 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
3009 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
3010 * (Eg: 'Banana' => 'banana').
3012 function tag_normalize($rawtags, $case = TAG_CASE_LOWER
) {
3013 debugging('Function tag_normalize() is deprecated. Use core_tag_tag::normalize().', DEBUG_DEVELOPER
);
3015 if ( !is_array($rawtags) ) {
3016 $rawtags = array($rawtags);
3019 return core_tag_tag
::normalize($rawtags, $case == TAG_CASE_LOWER
);
3023 * Get a comma-separated list of tags related to another tag.
3026 * @deprecated since 3.1
3027 * @param array $related_tags the array returned by tag_get_related_tags
3028 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
3029 * @return string comma-separated list
3031 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML
) {
3033 debugging('Method tag_get_related_tags_csv() is deprecated. Consider '
3034 . 'looping through array or using $OUTPUT->tag_list(core_tag_tag::get_item_tags())',
3036 if ($html != TAG_RETURN_TEXT
) {
3037 return $OUTPUT->tag_list($related_tags, '');
3040 $tagsnames = array();
3041 foreach ($related_tags as $tag) {
3042 $tagsnames[] = core_tag_tag
::make_display_name($tag, false);
3044 return implode(', ', $tagsnames);
3048 * Used to require that the return value from a function is an array.
3049 * Only used in the deprecated function {@link tag_get_id()}
3050 * @deprecated since 3.1
3052 define('TAG_RETURN_ARRAY', 0);
3054 * Used to require that the return value from a function is an object.
3055 * Only used in the deprecated function {@link tag_get_id()}
3056 * @deprecated since 3.1
3058 define('TAG_RETURN_OBJECT', 1);
3060 * Use to specify that HTML free text is expected to be returned from a function.
3061 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3062 * {@link tag_get_related_tags_csv()}
3063 * @deprecated since 3.1
3065 define('TAG_RETURN_TEXT', 2);
3067 * Use to specify that encoded HTML is expected to be returned from a function.
3068 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3069 * {@link tag_get_related_tags_csv()}
3070 * @deprecated since 3.1
3072 define('TAG_RETURN_HTML', 3);
3075 * Used to specify that we wish a lowercased string to be returned
3076 * Only used in deprecated function {@link tag_normalize()}
3077 * @deprecated since 3.1
3079 define('TAG_CASE_LOWER', 0);
3081 * Used to specify that we do not wish the case of the returned string to change
3082 * Only used in deprecated function {@link tag_normalize()}
3083 * @deprecated since 3.1
3085 define('TAG_CASE_ORIGINAL', 1);
3088 * Used to specify that we want all related tags returned, no matter how they are related.
3089 * Only used in deprecated function {@link tag_get_related_tags()}
3090 * @deprecated since 3.1
3092 define('TAG_RELATED_ALL', 0);
3094 * Used to specify that we only want back tags that were manually related.
3095 * Only used in deprecated function {@link tag_get_related_tags()}
3096 * @deprecated since 3.1
3098 define('TAG_RELATED_MANUAL', 1);
3100 * Used to specify that we only want back tags where the relationship was automatically correlated.
3101 * Only used in deprecated function {@link tag_get_related_tags()}
3102 * @deprecated since 3.1
3104 define('TAG_RELATED_CORRELATED', 2);
3107 * Set the tags assigned to a record. This overwrites the current tags.
3109 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
3111 * Due to API change $component and $contextid are now required. Instead of
3112 * calling this function you can use {@link core_tag_tag::set_item_tags()} or
3113 * {@link core_tag_tag::set_related_tags()}
3116 * @deprecated since 3.1
3117 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
3118 * @param int $itemid the id of the record to tag
3119 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
3120 * @param string|null $component the component that was tagged
3121 * @param int|null $contextid the context id of where this tag was assigned
3124 function tag_set($itemtype, $itemid, $tags, $component = null, $contextid = null) {
3125 debugging('Function tag_set() is deprecated. Use ' .
3126 ' core_tag_tag::set_item_tags() instead', DEBUG_DEVELOPER
);
3128 if ($itemtype === 'tag') {
3129 return core_tag_tag
::get($itemid, '*', MUST_EXIST
)->set_related_tags($tags);
3131 $context = $contextid ? context
::instance_by_id($contextid) : context_system
::instance();
3132 return core_tag_tag
::set_item_tags($component, $itemtype, $itemid, $context, $tags);
3137 * Adds a tag to a record, without overwriting the current tags.
3139 * This function remains here for backward compatiblity. It is recommended to use
3140 * {@link core_tag_tag::add_item_tag()} or {@link core_tag_tag::add_related_tags()} instead
3143 * @deprecated since 3.1
3144 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3145 * @param int $itemid the id of the record to tag
3146 * @param string $tag the tag to add
3147 * @param string|null $component the component that was tagged
3148 * @param int|null $contextid the context id of where this tag was assigned
3151 function tag_set_add($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3152 debugging('Function tag_set_add() is deprecated. Use ' .
3153 ' core_tag_tag::add_item_tag() instead', DEBUG_DEVELOPER
);
3155 if ($itemtype === 'tag') {
3156 return core_tag_tag
::get($itemid, '*', MUST_EXIST
)->add_related_tags(array($tag));
3158 $context = $contextid ? context
::instance_by_id($contextid) : context_system
::instance();
3159 return core_tag_tag
::add_item_tag($component, $itemtype, $itemid, $context, $tag);
3164 * Removes a tag from a record, without overwriting other current tags.
3166 * This function remains here for backward compatiblity. It is recommended to use
3167 * {@link core_tag_tag::remove_item_tag()} instead
3170 * @deprecated since 3.1
3171 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3172 * @param int $itemid the id of the record to tag
3173 * @param string $tag the tag to delete
3174 * @param string|null $component the component that was tagged
3175 * @param int|null $contextid the context id of where this tag was assigned
3178 function tag_set_delete($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3179 debugging('Function tag_set_delete() is deprecated. Use ' .
3180 ' core_tag_tag::remove_item_tag() instead', DEBUG_DEVELOPER
);
3181 return core_tag_tag
::remove_item_tag($component, $itemtype, $itemid, $tag);
3185 * Simple function to just return a single tag object when you know the name or something
3187 * See also {@link core_tag_tag::get()} and {@link core_tag_tag::get_by_name()}
3190 * @deprecated since 3.1
3191 * @param string $field which field do we use to identify the tag: id, name or rawname
3192 * @param string $value the required value of the aforementioned field
3193 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
3194 * 'id', 'name', 'rawname' or '*' to include all fields.
3195 * @return mixed tag object
3197 function tag_get($field, $value, $returnfields='id, name, rawname, tagcollid') {
3199 debugging('Function tag_get() is deprecated. Use ' .
3200 ' core_tag_tag::get() or core_tag_tag::get_by_name()',
3202 if ($field === 'id') {
3203 $tag = core_tag_tag
::get((int)$value, $returnfields);
3204 } else if ($field === 'name') {
3205 $tag = core_tag_tag
::get_by_name(0, $value, $returnfields);
3207 $params = array($field => $value);
3208 return $DB->get_record('tag', $params, $returnfields);
3211 return $tag->to_object();
3217 * Returns tags related to a tag
3219 * Related tags of a tag come from two sources:
3220 * - manually added related tags, which are tag_instance entries for that tag
3221 * - correlated tags, which are calculated
3224 * @deprecated since 3.1
3225 * @param string $tagid is a single **normalized** tag name or the id of a tag
3226 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
3227 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
3228 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
3229 * @return array an array of tag objects
3231 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL
, $limitnum=10) {
3232 debugging('Method tag_get_related_tags() is deprecated, '
3233 . 'use core_tag_tag::get_correlated_tags(), core_tag_tag::get_related_tags() or '
3234 . 'core_tag_tag::get_manual_related_tags()', DEBUG_DEVELOPER
);
3236 if ($tag = core_tag_tag
::get($tagid)) {
3237 if ($type == TAG_RELATED_CORRELATED
) {
3238 $tags = $tag->get_correlated_tags();
3239 } else if ($type == TAG_RELATED_MANUAL
) {
3240 $tags = $tag->get_manual_related_tags();
3242 $tags = $tag->get_related_tags();
3244 $tags = array_slice($tags, 0, $limitnum);
3245 foreach ($tags as $id => $tag) {
3246 $result[$id] = $tag->to_object();
3253 * Delete one or more tag, and all their instances if there are any left.
3256 * @deprecated since 3.1
3257 * @param mixed $tagids one tagid (int), or one array of tagids to delete
3258 * @return bool true on success, false otherwise
3260 function tag_delete($tagids) {
3261 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_tags()',
3263 return core_tag_tag
::delete_tags($tagids);
3267 * Deletes all the tag instances given a component and an optional contextid.
3269 * @deprecated since 3.1
3270 * @param string $component
3271 * @param int $contextid if null, then we delete all tag instances for the $component
3273 function tag_delete_instances($component, $contextid = null) {
3274 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_instances()',
3276 core_tag_tag
::delete_instances($component, null, $contextid);
3280 * Clean up the tag tables, making sure all tagged object still exists.
3282 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
3283 * done once in a while, perhaps on an occasional cron run. On a site with lots of tags, this could become an expensive function to
3284 * call: don't run at peak time.
3287 * @deprecated since 3.1
3289 function tag_cleanup() {
3290 debugging('Method tag_cleanup() is deprecated, use \core\task\tag_cron_task::cleanup()',
3293 $task = new \core\task\tag_cron_task
();
3294 return $task->cleanup();
3298 * This function will delete numerous tag instances efficiently.
3299 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
3301 * @deprecated since 3.1
3302 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
3303 * (used for recording a delete event).
3305 function tag_bulk_delete_instances($instances) {
3306 debugging('Method tag_bulk_delete_instances() is deprecated, '
3307 . 'use \core\task\tag_cron_task::bulk_delete_instances()',
3310 $task = new \core\task\tag_cron_task
();
3311 return $task->bulk_delete_instances($instances);
3315 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
3317 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
3319 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
3320 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
3323 * @deprecated since 3.1
3324 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
3326 function tag_compute_correlations($mincorrelation = 2) {
3327 debugging('Method tag_compute_correlations() is deprecated, '
3328 . 'use \core\task\tag_cron_task::compute_correlations()',
3331 $task = new \core\task\tag_cron_task
();
3332 return $task->compute_correlations($mincorrelation);
3336 * This function processes a tag correlation and makes changes in the database as required.
3338 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
3341 * @deprecated since 3.1
3342 * @param stdClass $tagcorrelation
3343 * @return int/bool The id of the tag correlation that was just processed or false.
3345 function tag_process_computed_correlation(stdClass
$tagcorrelation) {
3346 debugging('Method tag_process_computed_correlation() is deprecated, '
3347 . 'use \core\task\tag_cron_task::process_computed_correlation()',
3350 $task = new \core\task\tag_cron_task
();
3351 return $task->process_computed_correlation($tagcorrelation);
3355 * Tasks that should be performed at cron time
3358 * @deprecated since 3.1
3360 function tag_cron() {
3361 debugging('Method tag_cron() is deprecated, use \core\task\tag_cron_task::execute()',
3364 $task = new \core\task\tag_cron_task
();
3369 * Search for tags with names that match some text
3372 * @deprecated since 3.1
3373 * @param string $text escaped string that the tag names will be matched against
3374 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
3375 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
3376 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
3377 * @param int $tagcollid
3378 * @return array/boolean an array of objects, or false if no records were found or an error occured.
3380 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='', $tagcollid = null) {
3381 debugging('Method tag_find_tags() is deprecated without replacement', DEBUG_DEVELOPER
);
3384 $text = core_text
::strtolower(clean_param($text, PARAM_TAG
));
3386 list($sql, $params) = $DB->get_in_or_equal($tagcollid ?
array($tagcollid) :
3387 array_keys(core_tag_collection
::get_collections(true)));
3388 array_unshift($params, "%{$text}%");
3391 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid, COUNT(ti.id) AS count
3392 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
3393 WHERE tg.name LIKE ? AND tg.tagcollid $sql
3394 GROUP BY tg.id, tg.name, tg.rawname
3395 ORDER BY count DESC";
3397 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid
3399 WHERE tg.name LIKE ? AND tg.tagcollid $sql";
3401 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
3405 * Get the name of a tag
3408 * @deprecated since 3.1
3409 * @param mixed $tagids the id of the tag, or an array of ids
3410 * @return mixed string name of one tag, or id-indexed array of strings
3412 function tag_get_name($tagids) {
3413 debugging('Method tag_get_name() is deprecated without replacement', DEBUG_DEVELOPER
);
3416 if (!is_array($tagids)) {
3417 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
3423 $tag_names = array();
3424 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
3425 $tag_names[$tag->id
] = $tag->name
;
3432 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
3433 * empty and this function won't return anything.
3435 * Correlated tags are calculated in cron based on existing tag instances.
3438 * @deprecated since 3.1
3439 * @param int $tagid is a single tag id
3440 * @param int $notused this argument is no longer used
3441 * @return array an array of tag objects or an empty if no correlated tags are found
3443 function tag_get_correlated($tagid, $notused = null) {
3444 debugging('Method tag_get_correlated() is deprecated, '
3445 . 'use core_tag_tag::get_correlated_tags()', DEBUG_DEVELOPER
);
3447 if ($tag = core_tag_tag
::get($tagid)) {
3448 $tags = $tag->get_correlated_tags(true);
3449 // Convert to objects for backward-compatibility.
3450 foreach ($tags as $id => $tag) {
3451 $result[$id] = $tag->to_object();
3458 * This function is used by print_tag_cloud, to usort() the tags in the cloud. See php.net/usort for the parameters documentation.
3459 * This was originally in blocks/blog_tags/block_blog_tags.php, named blog_tags_sort().
3462 * @deprecated since 3.1
3463 * @param string $a Tag name to compare against $b
3464 * @param string $b Tag name to compare against $a
3465 * @return int The result of the comparison/validation 1, 0 or -1
3467 function tag_cloud_sort($a, $b) {
3468 debugging('Method tag_cloud_sort() is deprecated, similar method can be found in core_tag_collection::cloud_sort()', DEBUG_DEVELOPER
);
3471 if (empty($CFG->tagsort
)) {
3472 $tagsort = 'name'; // by default, sort by name
3474 $tagsort = $CFG->tagsort
;
3477 if (is_numeric($a->$tagsort)) {
3478 return ($a->$tagsort == $b->$tagsort) ?
0 : ($a->$tagsort > $b->$tagsort) ?
1 : -1;
3479 } elseif (is_string($a->$tagsort)) {
3480 return strcmp($a->$tagsort, $b->$tagsort);
3487 * Loads the events definitions for the component (from file). If no
3488 * events are defined for the component, we simply return an empty array.
3490 * @access protected To be used from eventslib only
3491 * @deprecated since Moodle 3.1
3492 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3493 * @return array Array of capabilities or empty array if not exists
3495 function events_load_def($component) {
3497 if ($component === 'unittest') {
3498 $defpath = $CFG->dirroot
.'/lib/tests/fixtures/events.php';
3500 $defpath = core_component
::get_component_directory($component).'/db/events.php';
3503 $handlers = array();
3505 if (file_exists($defpath)) {
3509 // make sure the definitions are valid and complete; tell devs what is wrong
3510 foreach ($handlers as $eventname => $handler) {
3511 if ($eventname === 'reset') {
3512 debugging("'reset' can not be used as event name.");
3513 unset($handlers['reset']);
3516 if (!is_array($handler)) {
3517 debugging("Handler of '$eventname' must be specified as array'");
3518 unset($handlers[$eventname]);
3521 if (!isset($handler['handlerfile'])) {
3522 debugging("Handler of '$eventname' must include 'handlerfile' key'");
3523 unset($handlers[$eventname]);
3526 if (!isset($handler['handlerfunction'])) {
3527 debugging("Handler of '$eventname' must include 'handlerfunction' key'");
3528 unset($handlers[$eventname]);
3531 if (!isset($handler['schedule'])) {
3532 $handler['schedule'] = 'instant';
3534 if ($handler['schedule'] !== 'instant' and $handler['schedule'] !== 'cron') {
3535 debugging("Handler of '$eventname' must include valid 'schedule' type (instant or cron)'");
3536 unset($handlers[$eventname]);
3539 if (!isset($handler['internal'])) {
3540 $handler['internal'] = 1;
3542 $handlers[$eventname] = $handler;
3549 * Puts a handler on queue
3551 * @access protected To be used from eventslib only
3552 * @deprecated since Moodle 3.1
3553 * @param stdClass $handler event handler object from db
3554 * @param stdClass $event event data object
3555 * @param string $errormessage The error message indicating the problem
3556 * @return int id number of new queue handler
3558 function events_queue_handler($handler, $event, $errormessage) {
3561 if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id
, 'handlerid'=>$handler->id
))) {
3562 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
3563 return $qhandler->id
;
3566 // make a new queue handler
3567 $qhandler = new stdClass();
3568 $qhandler->queuedeventid
= $event->id
;
3569 $qhandler->handlerid
= $handler->id
;
3570 $qhandler->errormessage
= $errormessage;
3571 $qhandler->timemodified
= time();
3572 if ($handler->schedule
=== 'instant' and $handler->status
== 1) {
3573 $qhandler->status
= 1; //already one failed attempt to dispatch this event
3575 $qhandler->status
= 0;
3578 return $DB->insert_record('events_queue_handlers', $qhandler);
3582 * trigger a single event with a specified handler
3584 * @access protected To be used from eventslib only
3585 * @deprecated since Moodle 3.1
3586 * @param stdClass $handler This shoudl be a row from the events_handlers table.
3587 * @param stdClass $eventdata An object containing information about the event
3588 * @param string $errormessage error message indicating problem
3589 * @return bool|null True means event processed, false means retry event later; may throw exception, NULL means internal error
3591 function events_dispatch($handler, $eventdata, &$errormessage) {
3594 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER
);
3596 $function = unserialize($handler->handlerfunction
);
3598 if (is_callable($function)) {
3599 // oki, no need for includes
3601 } else if (file_exists($CFG->dirroot
.$handler->handlerfile
)) {
3602 include_once($CFG->dirroot
.$handler->handlerfile
);
3605 $errormessage = "Handler file of component $handler->component: $handler->handlerfile can not be found!";
3609 // checks for handler validity
3610 if (is_callable($function)) {
3611 $result = call_user_func($function, $eventdata);
3612 if ($result === false) {
3613 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction requested resending of event!";
3619 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction not callable function or class method!";
3625 * given a queued handler, call the respective event handler to process the event
3627 * @access protected To be used from eventslib only
3628 * @deprecated since Moodle 3.1
3629 * @param stdClass $qhandler events_queued_handler row from db
3630 * @return boolean true means event processed, false means retry later, NULL means fatal failure
3632 function events_process_queued_handler($qhandler) {
3636 if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid
))) {
3637 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
3638 //irrecoverable error, remove broken queue handler
3639 events_dequeue($qhandler);
3644 if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid
))) {
3645 // can't proceed with no event object - might happen when two crons running at the same time
3646 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
3647 //irrecoverable error, remove broken queue handler
3648 events_dequeue($qhandler);
3652 // call the function specified by the handler
3654 $errormessage = 'Unknown error';
3655 if (events_dispatch($handler, unserialize(base64_decode($event->eventdata
)), $errormessage)) {
3657 events_dequeue($qhandler);
3660 } catch (Exception
$e) {
3661 // the problem here is that we do not want one broken handler to stop all others,
3662 // cron handlers are very tricky because the needed data might have been deleted before the cron execution
3663 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction threw exception :" .
3664 $e->getMessage() . "\n" . format_backtrace($e->getTrace(), true);
3665 if (!empty($e->debuginfo
)) {
3666 $errormessage .= $e->debuginfo
;
3670 //dispatching failed
3671 $qh = new stdClass();
3672 $qh->id
= $qhandler->id
;
3673 $qh->errormessage
= $errormessage;
3674 $qh->timemodified
= time();
3675 $qh->status
= $qhandler->status +
1;
3676 $DB->update_record('events_queue_handlers', $qh);
3678 debugging($errormessage);
3684 * Updates all of the event definitions within the database.
3686 * Unfortunately this isn't as simple as removing them all and then readding
3687 * the updated event definitions. Chances are queued items are referencing the
3688 * existing definitions.
3690 * Note that the absence of the db/events.php event definition file
3691 * will cause any queued events for the component to be removed from
3695 * @deprecated since Moodle 3.1
3696 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3697 * @return boolean always returns true
3699 function events_update_definition($component='moodle') {
3702 // load event definition from events.php
3703 $filehandlers = events_load_def($component);
3705 if ($filehandlers) {
3706 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER
);
3709 // load event definitions from db tables
3710 // if we detect an event being already stored, we discard from this array later
3711 // the remaining needs to be removed
3712 $cachedhandlers = events_get_cached($component);
3714 foreach ($filehandlers as $eventname => $filehandler) {
3715 if (!empty($cachedhandlers[$eventname])) {
3716 if ($cachedhandlers[$eventname]['handlerfile'] === $filehandler['handlerfile'] &&
3717 $cachedhandlers[$eventname]['handlerfunction'] === serialize($filehandler['handlerfunction']) &&
3718 $cachedhandlers[$eventname]['schedule'] === $filehandler['schedule'] &&
3719 $cachedhandlers[$eventname]['internal'] == $filehandler['internal']) {
3720 // exact same event handler already present in db, ignore this entry
3722 unset($cachedhandlers[$eventname]);
3726 // same event name matches, this event has been updated, update the datebase
3727 $handler = new stdClass();
3728 $handler->id
= $cachedhandlers[$eventname]['id'];
3729 $handler->handlerfile
= $filehandler['handlerfile'];
3730 $handler->handlerfunction
= serialize($filehandler['handlerfunction']); // static class methods stored as array
3731 $handler->schedule
= $filehandler['schedule'];
3732 $handler->internal
= $filehandler['internal'];
3734 $DB->update_record('events_handlers', $handler);
3736 unset($cachedhandlers[$eventname]);
3741 // if we are here, this event handler is not present in db (new)
3743 $handler = new stdClass();
3744 $handler->eventname
= $eventname;
3745 $handler->component
= $component;
3746 $handler->handlerfile
= $filehandler['handlerfile'];
3747 $handler->handlerfunction
= serialize($filehandler['handlerfunction']); // static class methods stored as array
3748 $handler->schedule
= $filehandler['schedule'];
3749 $handler->status
= 0;
3750 $handler->internal
= $filehandler['internal'];
3752 $DB->insert_record('events_handlers', $handler);
3756 // clean up the left overs, the entries in cached events array at this points are deprecated event handlers
3757 // and should be removed, delete from db
3758 events_cleanup($component, $cachedhandlers);
3760 events_get_handlers('reset');
3766 * Events cron will try to empty the events queue by processing all the queued events handlers
3768 * @access public Part of the public API
3769 * @deprecated since Moodle 3.1
3771 * @param string $eventname empty means all
3772 * @return int number of dispatched events
3774 function events_cron($eventname='') {
3782 FROM {events_queue_handlers} qh, {events_handlers} h
3783 WHERE qh.handlerid = h.id AND h.eventname=?
3785 $params = array($eventname);
3788 FROM {events_queue_handlers}
3793 $rs = $DB->get_recordset_sql($sql, $params);
3795 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER
);
3798 foreach ($rs as $qhandler) {
3799 if (isset($failed[$qhandler->handlerid
])) {
3800 // do not try to dispatch any later events when one already asked for retry or ended with exception
3803 $status = events_process_queued_handler($qhandler);
3804 if ($status === false) {
3805 // handler is asking for retry, do not send other events to this handler now
3806 $failed[$qhandler->handlerid
] = $qhandler->handlerid
;
3807 } else if ($status === NULL) {
3808 // means completely broken handler, event data was purged
3809 $failed[$qhandler->handlerid
] = $qhandler->handlerid
;
3816 // remove events that do not have any handlers waiting
3817 $sql = "SELECT eq.id
3818 FROM {events_queue} eq
3819 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
3820 WHERE qh.id IS NULL";
3821 $rs = $DB->get_recordset_sql($sql);
3822 foreach ($rs as $event) {
3823 //debugging('Purging stale event '.$event->id);
3824 $DB->delete_records('events_queue', array('id'=>$event->id
));
3832 * Do not call directly, this is intended to be used from new event base only.
3835 * @deprecated since Moodle 3.1
3836 * @param string $eventname name of the event
3837 * @param mixed $eventdata event data object
3838 * @return int number of failed events
3840 function events_trigger_legacy($eventname, $eventdata) {
3841 global $CFG, $USER, $DB;
3843 $failedcount = 0; // number of failed events.
3845 // pull out all registered event handlers
3846 if ($handlers = events_get_handlers($eventname)) {
3847 foreach ($handlers as $handler) {
3850 if ($handler->schedule
=== 'instant') {
3851 if ($handler->status
) {
3852 //check if previous pending events processed
3853 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id
))) {
3854 // ok, queue is empty, lets reset the status back to 0 == ok
3855 $handler->status
= 0;
3856 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id
));
3857 // reset static handler cache
3858 events_get_handlers('reset');
3862 // dispatch the event only if instant schedule and status ok
3863 if ($handler->status
or (!$handler->internal
and $DB->is_transaction_started())) {
3864 // increment the error status counter
3866 $DB->set_field('events_handlers', 'status', $handler->status
, array('id'=>$handler->id
));
3867 // reset static handler cache
3868 events_get_handlers('reset');
3871 $errormessage = 'Unknown error';
3872 $result = events_dispatch($handler, $eventdata, $errormessage);
3873 if ($result === true) {
3874 // everything is fine - event dispatched
3876 } else if ($result === false) {
3877 // retry later - set error count to 1 == send next instant into cron queue
3878 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id
));
3879 // reset static handler cache
3880 events_get_handlers('reset');
3882 // internal problem - ignore the event completely
3888 // update the failed counter
3891 } else if ($handler->schedule
=== 'cron') {
3892 //ok - use queueing of events only
3895 // unknown schedule - ignore event completely
3896 debugging("Unknown handler schedule type: $handler->schedule");
3901 // if even type is not instant, or dispatch asked for retry, queue it
3902 $event = new stdClass();
3903 $event->userid
= $USER->id
;
3904 $event->eventdata
= base64_encode(serialize($eventdata));
3905 $event->timecreated
= time();
3908 $callers = debug_backtrace();
3909 foreach ($callers as $caller) {
3910 if (!isset($caller['line'])) {
3911 $caller['line'] = '?';
3913 if (!isset($caller['file'])) {
3914 $caller['file'] = '?';
3916 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot
) +
1);
3917 if (isset($caller['function'])) {
3918 $dump .= ': call to ';
3919 if (isset($caller['class'])) {
3920 $dump .= $caller['class'] . $caller['type'];
3922 $dump .= $caller['function'] . '()';
3926 $event->stackdump
= $dump;
3928 $event->stackdump
= '';
3930 $event->id
= $DB->insert_record('events_queue', $event);
3931 events_queue_handler($handler, $event, $errormessage);
3934 // No handler found for this event name - this is ok!
3937 return $failedcount;
3941 * checks if an event is registered for this component
3943 * @access public Part of the public API
3944 * @deprecated since Moodle 3.1
3945 * @param string $eventname name of the event
3946 * @param string $component component name, can be mod/data or moodle
3949 function events_is_registered($eventname, $component) {
3952 debugging('events_is_registered() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3953 ' please use it instead.', DEBUG_DEVELOPER
);
3955 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
3959 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
3961 * @access public Part of the public API
3962 * @deprecated since Moodle 3.1
3963 * @param string $eventname name of the event
3964 * @return int number of queued events
3966 function events_pending_count($eventname) {
3969 debugging('events_pending_count() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3970 ' please use it instead.', DEBUG_DEVELOPER
);
3972 $sql = "SELECT COUNT('x')
3973 FROM {events_queue_handlers} qh
3974 JOIN {events_handlers} h ON h.id = qh.handlerid
3975 WHERE h.eventname = ?";
3977 return $DB->count_records_sql($sql, array($eventname));
3981 * Emails admins about a clam outcome
3983 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3984 * @param string $notice The body of the email to be sent.
3987 function clam_message_admins($notice) {
3988 debugging('clam_message_admins() is deprecated, please use message_admins() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER
);
3990 $antivirus = \core\antivirus\manager
::get_antivirus('clamav');
3991 $antivirus->message_admins($notice);
3995 * Returns the string equivalent of a numeric clam error code
3997 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3998 * @param int $returncode The numeric error code in question.
3999 * @return string The definition of the error code
4001 function get_clam_error_code($returncode) {
4002 debugging('get_clam_error_code() is deprecated, please use get_clam_error_code() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER
);
4004 $antivirus = \core\antivirus\manager
::get_antivirus('clamav');
4005 return $antivirus->get_clam_error_code($returncode);
4009 * Returns the rename action.
4011 * @deprecated since 3.1
4012 * @param cm_info $mod The module to produce editing buttons for
4013 * @param int $sr The section to link back to (used for creating the links)
4014 * @return The markup for the rename action, or an empty string if not available.
4016 function course_get_cm_rename_action(cm_info
$mod, $sr = null) {
4017 global $COURSE, $OUTPUT;
4022 debugging('Function course_get_cm_rename_action() is deprecated. Please use inplace_editable ' .
4023 'https://docs.moodle.org/dev/Inplace_editable', DEBUG_DEVELOPER
);
4025 $modcontext = context_module
::instance($mod->id
);
4026 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
4029 $str = get_strings(array('edittitle'));
4032 if (!isset($baseurl)) {
4033 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
4037 $baseurl->param('sr', $sr);
4041 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
4042 (($mod->course
== $COURSE->id
) ||
($mod->course
== SITEID
))) {
4043 // we will not display link if we are on some other-course page (where we should not see this module anyway)
4044 return html_writer
::span(
4046 new moodle_url($baseurl, array('update' => $mod->id
)),
4047 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
4049 'class' => 'editing_title',
4050 'data-action' => 'edittitle',
4051 'title' => $str->edittitle
,
4060 * This function returns the number of activities using the given scale in the given course.
4062 * @deprecated since Moodle 3.1
4063 * @param int $courseid The course ID to check.
4064 * @param int $scaleid The scale ID to check
4067 function course_scale_used($courseid, $scaleid) {
4070 debugging('course_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4071 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER
);
4075 if (!empty($scaleid)) {
4076 if ($cms = get_course_mods($courseid)) {
4077 foreach ($cms as $cm) {
4078 // Check cm->name/lib.php exists.
4079 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
4080 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
4081 $functionname = $cm->modname
.'_scale_used';
4082 if (function_exists($functionname)) {
4083 if ($functionname($cm->instance
, $scaleid)) {
4091 // Check if any course grade item makes use of the scale.
4092 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
4094 // Check if any outcome in the course makes use of the scale.
4095 $return +
= $DB->count_records_sql("SELECT COUNT('x')
4096 FROM {grade_outcomes_courses} goc,
4098 WHERE go.id = goc.outcomeid
4099 AND go.scaleid = ? AND goc.courseid = ?",
4100 array($scaleid, $courseid));
4106 * This function returns the number of activities using scaleid in the entire site
4108 * @deprecated since Moodle 3.1
4109 * @param int $scaleid
4110 * @param array $courses
4113 function site_scale_used($scaleid, &$courses) {
4116 debugging('site_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4117 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER
);
4119 if (!is_array($courses) ||
count($courses) == 0) {
4120 $courses = get_courses("all", false, "c.id, c.shortname");
4123 if (!empty($scaleid)) {
4124 if (is_array($courses) && count($courses) > 0) {
4125 foreach ($courses as $course) {
4126 $return +
= course_scale_used($course->id
, $scaleid);
4134 * Returns detailed function information
4136 * @deprecated since Moodle 3.1
4137 * @param string|object $function name of external function or record from external_function
4138 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4139 * MUST_EXIST means throw exception if no record or multiple records found
4140 * @return stdClass description or false if not found or exception thrown
4143 function external_function_info($function, $strictness=MUST_EXIST
) {
4144 debugging('external_function_info() is deprecated. Please use external_api::external_function_info() instead.',
4146 return external_api
::external_function_info($function, $strictness);
4150 * Retrieves an array of records from a CSV file and places
4151 * them into a given table structure
4152 * This function is deprecated. Please use csv_import_reader() instead.
4154 * @deprecated since Moodle 3.2 MDL-55126
4155 * @todo MDL-55195 for final deprecation in Moodle 3.6
4156 * @see csv_import_reader::load_csv_content()
4157 * @global stdClass $CFG
4158 * @global moodle_database $DB
4159 * @param string $file The path to a CSV file
4160 * @param string $table The table to retrieve columns from
4161 * @return bool|array Returns an array of CSV records or false
4163 function get_records_csv($file, $table) {
4166 debugging('get_records_csv() is deprecated. Please use lib/csvlib.class.php csv_import_reader() instead.');
4168 if (!$metacolumns = $DB->get_columns($table)) {
4172 if(!($handle = @fopen
($file, 'r'))) {
4173 print_error('get_records_csv failed to open '.$file);
4176 $fieldnames = fgetcsv($handle, 4096);
4177 if(empty($fieldnames)) {
4184 foreach($metacolumns as $metacolumn) {
4185 $ord = array_search($metacolumn->name
, $fieldnames);
4187 $columns[$metacolumn->name
] = $ord;
4193 while (($data = fgetcsv($handle, 4096)) !== false) {
4194 $item = new stdClass
;
4195 foreach($columns as $name => $ord) {
4196 $item->$name = $data[$ord];
4206 * Create a file with CSV contents
4207 * This function is deprecated. Please use download_as_dataformat() instead.
4209 * @deprecated since Moodle 3.2 MDL-55126
4210 * @todo MDL-55195 for final deprecation in Moodle 3.6
4211 * @see download_as_dataformat (lib/dataformatlib.php)
4212 * @global stdClass $CFG
4213 * @global moodle_database $DB
4214 * @param string $file The file to put the CSV content into
4215 * @param array $records An array of records to write to a CSV file
4216 * @param string $table The table to get columns from
4217 * @return bool success
4219 function put_records_csv($file, $records, $table = NULL) {
4222 debugging('put_records_csv() is deprecated. Please use lib/dataformatlib.php download_as_dataformat()');
4224 if (empty($records)) {
4228 $metacolumns = NULL;
4229 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
4235 if(!($fp = @fopen
($CFG->tempdir
.'/'.$file, 'w'))) {
4236 print_error('put_records_csv failed to open '.$file);
4239 $proto = reset($records);
4240 if(is_object($proto)) {
4241 $fields_records = array_keys(get_object_vars($proto));
4243 else if(is_array($proto)) {
4244 $fields_records = array_keys($proto);
4251 if(!empty($metacolumns)) {
4252 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
4253 $fields = array_intersect($fields_records, $fields_table);
4256 $fields = $fields_records;
4259 fwrite($fp, implode(',', $fields));
4260 fwrite($fp, "\r\n");
4262 foreach($records as $record) {
4263 $array = (array)$record;
4265 foreach($fields as $field) {
4266 if(strpos($array[$field], ',')) {
4267 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
4270 $values[] = $array[$field];
4273 fwrite($fp, implode(',', $values)."\r\n");
4277 @chmod
($CFG->tempdir
.'/'.$file, $CFG->filepermissions
);
4282 * Determines if the given value is a valid CSS colour.
4284 * A CSS colour can be one of the following:
4285 * - Hex colour: #AA66BB
4286 * - RGB colour: rgb(0-255, 0-255, 0-255)
4287 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
4288 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
4289 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
4291 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
4293 * @deprecated since Moodle 3.2
4294 * @todo MDL-56173 for final deprecation in Moodle 3.6
4295 * @param string $value The colour value to check
4298 function css_is_colour($value) {
4299 debugging('css_is_colour() is deprecated without a replacement. Please copy the implementation '.
4300 'into your plugin if you need this functionality.', DEBUG_DEVELOPER
);
4302 $value = trim($value);
4304 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
4305 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
4306 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4307 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
4308 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4310 if (in_array(strtolower($value), array('inherit'))) {
4312 } else if (preg_match($hex, $value)) {
4314 } else if (in_array(strtolower($value), array_keys(css_optimiser
::$htmlcolours))) {
4316 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4317 // It is an RGB colour.
4319 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4320 // It is an RGBA colour.
4322 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4323 // It is an HSL colour.
4325 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4326 // It is an HSLA colour.
4329 // Doesn't look like a colour.
4334 * Returns true is the passed value looks like a CSS width.
4335 * In order to pass this test the value must be purely numerical or end with a
4336 * valid CSS unit term.
4338 * @param string|int $value
4340 * @deprecated since Moodle 3.2
4341 * @todo MDL-56173 for final deprecation in Moodle 3.6
4343 function css_is_width($value) {
4344 debugging('css_is_width() is deprecated without a replacement. Please copy the implementation '.
4345 'into your plugin if you need this functionality.', DEBUG_DEVELOPER
);
4347 $value = trim($value);
4348 if (in_array(strtolower($value), array('auto', 'inherit'))) {
4351 if ((string)$value === '0' ||
preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
4358 * A simple sorting function to sort two array values on the number of items they contain
4363 * @deprecated since Moodle 3.2
4364 * @todo MDL-56173 for final deprecation in Moodle 3.6
4366 function css_sort_by_count(array $a, array $b) {
4367 debugging('css_sort_by_count() is deprecated without a replacement. Please copy the implementation '.
4368 'into your plugin if you need this functionality.', DEBUG_DEVELOPER
);
4375 return ($a > $b) ?
-1 : 1;
4379 * A basic CSS optimiser that strips out unwanted things and then processes CSS organising and cleaning styles.
4380 * @deprecated since Moodle 3.2
4381 * @todo MDL-56173 for final deprecation in Moodle 3.6
4383 class css_optimiser
{
4385 * An array of the common HTML colours that are supported by most browsers.
4387 * This reference table is used to allow us to unify colours, and will aid
4388 * us in identifying buggy CSS using unsupported colours.
4391 * @deprecated since Moodle 3.2
4392 * @todo MDL-56173 for final deprecation in Moodle 3.6
4394 public static $htmlcolours = array(
4395 'aliceblue' => '#F0F8FF',
4396 'antiquewhite' => '#FAEBD7',
4397 'aqua' => '#00FFFF',
4398 'aquamarine' => '#7FFFD4',
4399 'azure' => '#F0FFFF',
4400 'beige' => '#F5F5DC',
4401 'bisque' => '#FFE4C4',
4402 'black' => '#000000',
4403 'blanchedalmond' => '#FFEBCD',
4404 'blue' => '#0000FF',
4405 'blueviolet' => '#8A2BE2',
4406 'brown' => '#A52A2A',
4407 'burlywood' => '#DEB887',
4408 'cadetblue' => '#5F9EA0',
4409 'chartreuse' => '#7FFF00',
4410 'chocolate' => '#D2691E',
4411 'coral' => '#FF7F50',
4412 'cornflowerblue' => '#6495ED',
4413 'cornsilk' => '#FFF8DC',
4414 'crimson' => '#DC143C',
4415 'cyan' => '#00FFFF',
4416 'darkblue' => '#00008B',
4417 'darkcyan' => '#008B8B',
4418 'darkgoldenrod' => '#B8860B',
4419 'darkgray' => '#A9A9A9',
4420 'darkgrey' => '#A9A9A9',
4421 'darkgreen' => '#006400',
4422 'darkKhaki' => '#BDB76B',
4423 'darkmagenta' => '#8B008B',
4424 'darkolivegreen' => '#556B2F',
4425 'arkorange' => '#FF8C00',
4426 'darkorchid' => '#9932CC',
4427 'darkred' => '#8B0000',
4428 'darksalmon' => '#E9967A',
4429 'darkseagreen' => '#8FBC8F',
4430 'darkslateblue' => '#483D8B',
4431 'darkslategray' => '#2F4F4F',
4432 'darkslategrey' => '#2F4F4F',
4433 'darkturquoise' => '#00CED1',
4434 'darkviolet' => '#9400D3',
4435 'deeppink' => '#FF1493',
4436 'deepskyblue' => '#00BFFF',
4437 'dimgray' => '#696969',
4438 'dimgrey' => '#696969',
4439 'dodgerblue' => '#1E90FF',
4440 'firebrick' => '#B22222',
4441 'floralwhite' => '#FFFAF0',
4442 'forestgreen' => '#228B22',
4443 'fuchsia' => '#FF00FF',
4444 'gainsboro' => '#DCDCDC',
4445 'ghostwhite' => '#F8F8FF',
4446 'gold' => '#FFD700',
4447 'goldenrod' => '#DAA520',
4448 'gray' => '#808080',
4449 'grey' => '#808080',
4450 'green' => '#008000',
4451 'greenyellow' => '#ADFF2F',
4452 'honeydew' => '#F0FFF0',
4453 'hotpink' => '#FF69B4',
4454 'indianred ' => '#CD5C5C',
4455 'indigo ' => '#4B0082',
4456 'ivory' => '#FFFFF0',
4457 'khaki' => '#F0E68C',
4458 'lavender' => '#E6E6FA',
4459 'lavenderblush' => '#FFF0F5',
4460 'lawngreen' => '#7CFC00',
4461 'lemonchiffon' => '#FFFACD',
4462 'lightblue' => '#ADD8E6',
4463 'lightcoral' => '#F08080',
4464 'lightcyan' => '#E0FFFF',
4465 'lightgoldenrodyellow' => '#FAFAD2',
4466 'lightgray' => '#D3D3D3',
4467 'lightgrey' => '#D3D3D3',
4468 'lightgreen' => '#90EE90',
4469 'lightpink' => '#FFB6C1',
4470 'lightsalmon' => '#FFA07A',
4471 'lightseagreen' => '#20B2AA',
4472 'lightskyblue' => '#87CEFA',
4473 'lightslategray' => '#778899',
4474 'lightslategrey' => '#778899',
4475 'lightsteelblue' => '#B0C4DE',
4476 'lightyellow' => '#FFFFE0',
4477 'lime' => '#00FF00',
4478 'limegreen' => '#32CD32',
4479 'linen' => '#FAF0E6',
4480 'magenta' => '#FF00FF',
4481 'maroon' => '#800000',
4482 'mediumaquamarine' => '#66CDAA',
4483 'mediumblue' => '#0000CD',
4484 'mediumorchid' => '#BA55D3',
4485 'mediumpurple' => '#9370D8',
4486 'mediumseagreen' => '#3CB371',
4487 'mediumslateblue' => '#7B68EE',
4488 'mediumspringgreen' => '#00FA9A',
4489 'mediumturquoise' => '#48D1CC',
4490 'mediumvioletred' => '#C71585',
4491 'midnightblue' => '#191970',
4492 'mintcream' => '#F5FFFA',
4493 'mistyrose' => '#FFE4E1',
4494 'moccasin' => '#FFE4B5',
4495 'navajowhite' => '#FFDEAD',
4496 'navy' => '#000080',
4497 'oldlace' => '#FDF5E6',
4498 'olive' => '#808000',
4499 'olivedrab' => '#6B8E23',
4500 'orange' => '#FFA500',
4501 'orangered' => '#FF4500',
4502 'orchid' => '#DA70D6',
4503 'palegoldenrod' => '#EEE8AA',
4504 'palegreen' => '#98FB98',
4505 'paleturquoise' => '#AFEEEE',
4506 'palevioletred' => '#D87093',
4507 'papayawhip' => '#FFEFD5',
4508 'peachpuff' => '#FFDAB9',
4509 'peru' => '#CD853F',
4510 'pink' => '#FFC0CB',
4511 'plum' => '#DDA0DD',
4512 'powderblue' => '#B0E0E6',
4513 'purple' => '#800080',
4515 'rosybrown' => '#BC8F8F',
4516 'royalblue' => '#4169E1',
4517 'saddlebrown' => '#8B4513',
4518 'salmon' => '#FA8072',
4519 'sandybrown' => '#F4A460',
4520 'seagreen' => '#2E8B57',
4521 'seashell' => '#FFF5EE',
4522 'sienna' => '#A0522D',
4523 'silver' => '#C0C0C0',
4524 'skyblue' => '#87CEEB',
4525 'slateblue' => '#6A5ACD',
4526 'slategray' => '#708090',
4527 'slategrey' => '#708090',
4528 'snow' => '#FFFAFA',
4529 'springgreen' => '#00FF7F',
4530 'steelblue' => '#4682B4',
4532 'teal' => '#008080',
4533 'thistle' => '#D8BFD8',
4534 'tomato' => '#FF6347',
4535 'transparent' => 'transparent',
4536 'turquoise' => '#40E0D0',
4537 'violet' => '#EE82EE',
4538 'wheat' => '#F5DEB3',
4539 'white' => '#FFFFFF',
4540 'whitesmoke' => '#F5F5F5',
4541 'yellow' => '#FFFF00',
4542 'yellowgreen' => '#9ACD32'
4546 * Used to orocesses incoming CSS optimising it and then returning it. Now just returns
4547 * what is sent to it. Do not use.
4549 * @param string $css The raw CSS to optimise
4550 * @return string The optimised CSS
4551 * @deprecated since Moodle 3.2
4552 * @todo MDL-56173 for final deprecation in Moodle 3.6
4554 public function process($css) {
4555 debugging('class css_optimiser is deprecated and no longer does anything, '.
4556 'please consider using stylelint to optimise your css.', DEBUG_DEVELOPER
);
4563 * Load the course contexts for all of the users courses
4565 * @deprecated since Moodle 3.2
4566 * @param array $courses array of course objects. The courses the user is enrolled in.
4567 * @return array of course contexts
4569 function message_get_course_contexts($courses) {
4570 debugging('message_get_course_contexts() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4572 $coursecontexts = array();
4574 foreach($courses as $course) {
4575 $coursecontexts[$course->id
] = context_course
::instance($course->id
);
4578 return $coursecontexts;
4582 * strip off action parameters like 'removecontact'
4584 * @deprecated since Moodle 3.2
4585 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
4586 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
4588 function message_remove_url_params($moodleurl) {
4589 debugging('message_remove_url_params() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4591 $newurl = new moodle_url($moodleurl);
4592 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
4593 return $newurl->out();
4597 * Count the number of messages with a field having a specified value.
4598 * if $field is empty then return count of the whole array
4599 * if $field is non-existent then return 0
4601 * @deprecated since Moodle 3.2
4602 * @param array $messagearray array of message objects
4603 * @param string $field the field to inspect on the message objects
4604 * @param string $value the value to test the field against
4606 function message_count_messages($messagearray, $field='', $value='') {
4607 debugging('message_count_messages() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4609 if (!is_array($messagearray)) return 0;
4610 if ($field == '' or empty($messagearray)) return count($messagearray);
4613 foreach ($messagearray as $message) {
4614 $count +
= ($message->$field == $value) ?
1 : 0;
4620 * Count the number of users blocked by $user1
4622 * @deprecated since Moodle 3.2
4623 * @param object $user1 user object
4624 * @return int the number of blocked users
4626 function message_count_blocked_users($user1=null) {
4627 debugging('message_count_blocked_users() is deprecated, please use \core_message\api::count_blocked_users() instead.',
4630 return \core_message\api
::count_blocked_users($user1);
4634 * Print a message contact link
4636 * @deprecated since Moodle 3.2
4637 * @param int $userid the ID of the user to apply to action to
4638 * @param string $linktype can be add, remove, block or unblock
4639 * @param bool $return if true return the link as a string. If false echo the link.
4640 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4641 * @param bool $text include text next to the icons?
4642 * @param bool $icon include a graphical icon?
4643 * @return string if $return is true otherwise bool
4645 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
4646 debugging('message_contact_link() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4648 global $OUTPUT, $PAGE;
4650 //hold onto the strings as we're probably creating a bunch of links
4653 if (empty($script)) {
4654 //strip off previous action params like 'removecontact'
4655 $script = message_remove_url_params($PAGE->url
);
4658 if (empty($str->blockcontact
)) {
4659 $str = new stdClass();
4660 $str->blockcontact
= get_string('blockcontact', 'message');
4661 $str->unblockcontact
= get_string('unblockcontact', 'message');
4662 $str->removecontact
= get_string('removecontact', 'message');
4663 $str->addcontact
= get_string('addcontact', 'message');
4666 $command = $linktype.'contact';
4667 $string = $str->{$command};
4669 $safealttext = s($string);
4672 if (!empty($text)) {
4673 $safestring = $safealttext;
4679 switch ($linktype) {
4681 $iconpath = 't/block';
4684 $iconpath = 't/unblock';
4687 $iconpath = 't/removecontact';
4691 $iconpath = 't/addcontact';
4694 $img = $OUTPUT->pix_icon($iconpath, $safealttext);
4697 $output = '<span class="'.$linktype.'contact">'.
4698 '<a href="'.$script.'&'.$command.'='.$userid.
4699 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
4701 $safestring.'</a></span>';
4712 * Get the users recent event notifications
4714 * @deprecated since Moodle 3.2
4715 * @param object $user the current user
4716 * @param int $limitfrom can be used for paging
4717 * @param int $limitto can be used for paging
4720 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
4721 debugging('message_get_recent_notifications() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4725 $userfields = user_picture
::fields('u', array('lastaccess'));
4726 $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
4727 FROM {message_read} mr
4728 JOIN {user} u ON u.id=mr.useridfrom
4729 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
4730 ORDER BY mr.timecreated DESC";
4731 $params = array('userid1' => $user->id
, 'notification' => 1);
4733 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
4734 return $notifications;
4738 * echo or return a link to take the user to the full message history between themselves and another user
4740 * @deprecated since Moodle 3.2
4741 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
4742 * @param int $userid2 the ID of the other user
4743 * @param bool $return true to return the link as a string. False to echo the link.
4744 * @param string $keywords any keywords to highlight in the message history
4745 * @param string $position anchor name to jump to within the message history
4746 * @param string $linktext optionally specify the link text
4747 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
4749 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
4750 debugging('message_history_link() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4752 global $OUTPUT, $PAGE;
4753 static $strmessagehistory;
4755 if (empty($strmessagehistory)) {
4756 $strmessagehistory = get_string('messagehistory', 'message');
4760 $position = "#$position";
4763 $keywords = "&search=".urlencode($keywords);
4766 if ($linktext == 'icon') { // Icon only
4767 $fulllink = $OUTPUT->pix_icon('t/messages', $strmessagehistory);
4768 } else if ($linktext == 'both') { // Icon and standard name
4769 $fulllink = $OUTPUT->pix_icon('t/messages', '');
4770 $fulllink .= ' '.$strmessagehistory;
4771 } else if ($linktext) { // Custom name
4772 $fulllink = $linktext;
4773 } else { // Standard name only
4774 $fulllink = $strmessagehistory;
4777 $popupoptions = array(
4781 'location' => false,
4783 'scrollbars' => true,
4784 'resizable' => true);
4786 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL
."&user1=$userid1&user2=$userid2$keywords$position");
4787 if ($PAGE->url
&& $PAGE->url
->get_param('viewing')) {
4788 $link->param('viewing', $PAGE->url
->get_param('viewing'));
4791 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
4793 $str = '<span class="history">'.$str.'</span>';
4804 * Search a user's messages
4806 * Returns a list of posts found using an array of search terms
4807 * eg word +word -word
4809 * @deprecated since Moodle 3.2
4810 * @param array $searchterms an array of search terms (strings)
4811 * @param bool $fromme include messages from the user?
4812 * @param bool $tome include messages to the user?
4813 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
4814 * @param int $userid the user ID of the current user
4815 * @return mixed An array of messages or false if no matching messages were found
4817 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
4818 debugging('message_search() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4820 global $CFG, $USER, $DB;
4822 // If user is searching all messages check they are allowed to before doing anything else.
4823 if ($courseid == SITEID
&& !has_capability('moodle/site:readallmessages', context_system
::instance())) {
4824 print_error('accessdenied','admin');
4827 // If no userid sent then assume current user.
4828 if ($userid == 0) $userid = $USER->id
;
4830 // Some differences in SQL syntax.
4831 if ($DB->sql_regex_supported()) {
4832 $REGEXP = $DB->sql_regex(true);
4833 $NOTREGEXP = $DB->sql_regex(false);
4836 $searchcond = array();
4840 // Preprocess search terms to check whether we have at least 1 eligible search term.
4841 // If we do we can drop words around it like 'a'.
4842 $dropshortwords = false;
4843 foreach ($searchterms as $searchterm) {
4844 if (strlen($searchterm) >= 2) {
4845 $dropshortwords = true;
4849 foreach ($searchterms as $searchterm) {
4852 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
4854 if ($dropshortwords && strlen($searchterm) < 2) {
4857 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
4858 if (!$DB->sql_regex_supported()) {
4859 if (substr($searchterm, 0, 1) == '-') {
4862 $searchterm = trim($searchterm, '+-');
4865 if (substr($searchterm,0,1) == "+") {
4866 $searchterm = substr($searchterm,1);
4867 $searchterm = preg_quote($searchterm, '|');
4868 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
4869 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
4871 } else if (substr($searchterm,0,1) == "-") {
4872 $searchterm = substr($searchterm,1);
4873 $searchterm = preg_quote($searchterm, '|');
4874 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
4875 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
4878 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
4879 $params['ss'.$i] = "%$searchterm%";
4883 if (empty($searchcond)) {
4884 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
4885 $params['ss1'] = "%";
4887 $searchcond = implode(" AND ", $searchcond);
4890 // There are several possibilities
4891 // 1. courseid = SITEID : The admin is searching messages by all users
4892 // 2. courseid = ?? : A teacher is searching messages by users in
4893 // one of their courses - currently disabled
4894 // 3. courseid = none : User is searching their own messages;
4895 // a. Messages from user
4896 // b. Messages to user
4897 // c. Messages to and from user
4899 if ($fromme && $tome) {
4900 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
4901 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
4902 $params['useridto'] = $userid;
4903 $params['useridfrom'] = $userid;
4904 } else if ($fromme) {
4905 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
4906 $params['useridfrom'] = $userid;
4908 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
4909 $params['useridto'] = $userid;
4911 if ($courseid == SITEID
) { // Admin is searching all messages.
4912 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4913 FROM {message_read} m
4914 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
4915 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4917 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
4919 } else if ($courseid !== 'none') {
4920 // This has not been implemented due to security concerns.
4922 $m_unread = array();
4926 if ($fromme and $tome) {
4927 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
4928 $params['userid1'] = $userid;
4929 $params['userid2'] = $userid;
4931 } else if ($fromme) {
4932 $searchcond .= " AND m.useridfrom=:userid";
4933 $params['userid'] = $userid;
4936 $searchcond .= " AND m.useridto=:userid";
4937 $params['userid'] = $userid;
4940 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4941 FROM {message_read} m
4942 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
4943 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
4945 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
4949 /// The keys may be duplicated in $m_read and $m_unread so we can't
4950 /// do a simple concatenation
4951 $messages = array();
4952 foreach ($m_read as $m) {
4955 foreach ($m_unread as $m) {
4959 return (empty($messages)) ?
false : $messages;
4963 * Given a message object that we already know has a long message
4964 * this function truncates the message nicely to the first
4965 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
4967 * @deprecated since Moodle 3.2
4968 * @param string $message the message
4969 * @param int $minlength the minimum length to trim the message to
4970 * @return string the shortened message
4972 function message_shorten_message($message, $minlength = 0) {
4973 debugging('message_shorten_message() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
4977 $length = strlen($message);
4981 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
4984 for ($i=0; $i<$length; $i++
) {
4985 $char = $message[$i];
4997 if ($char == '.' or $char == ' ') {
5007 if ($count > $minlength) {
5017 return substr($message, 0, $truncate);
5021 * Given a string and an array of keywords, this function looks
5022 * for the first keyword in the string, and then chops out a
5023 * small section from the text that shows that word in context.
5025 * @deprecated since Moodle 3.2
5026 * @param string $message the text to search
5027 * @param array $keywords array of keywords to find
5029 function message_get_fragment($message, $keywords) {
5030 debugging('message_get_fragment() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
5033 $halfsize = (int)($fullsize/2);
5035 $message = strip_tags($message);
5037 foreach ($keywords as $keyword) { // Just get the first one
5038 if ($keyword !== '') {
5042 if (empty($keyword)) { // None found, so just return start of message
5043 return message_shorten_message($message, 30);
5046 $leadin = $leadout = '';
5048 /// Find the start of the fragment
5050 $length = strlen($message);
5052 $pos = strpos($message, $keyword);
5053 if ($pos > $halfsize) {
5054 $start = $pos - $halfsize;
5057 /// Find the end of the fragment
5058 $end = $start +
$fullsize;
5059 if ($end > $length) {
5065 /// Pull out the fragment and format it
5067 $fragment = substr($message, $start, $end - $start);
5068 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
5073 * Retrieve the messages between two users
5075 * @deprecated since Moodle 3.2
5076 * @param object $user1 the current user
5077 * @param object $user2 the other user
5078 * @param int $limitnum the maximum number of messages to retrieve
5079 * @param bool $viewingnewmessages are we currently viewing new messages?
5081 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
5082 debugging('message_get_history() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
5086 $messages = array();
5088 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
5089 //desc to get the last $limitnum messages then flip the order in php
5095 $notificationswhere = null;
5096 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
5097 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications
) {
5098 $notificationswhere = 'AND notification=0';
5101 //prevent notifications of your own actions appearing in your own message history
5102 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
5104 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
5105 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
5106 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
5107 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
5108 "timecreated $sort", '*', 0, $limitnum)) {
5109 foreach ($messages_read as $message) {
5110 $messages[] = $message;
5113 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
5114 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
5115 "timecreated $sort", '*', 0, $limitnum)) {
5116 foreach ($messages_new as $message) {
5117 $messages[] = $message;
5121 $result = core_collator
::asort_objects_by_property($messages, 'timecreated', core_collator
::SORT_NUMERIC
);
5123 //if we only want the last $limitnum messages
5124 $messagecount = count($messages);
5125 if ($limitnum > 0 && $messagecount > $limitnum) {
5126 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
5133 * Constructs the add/remove contact link to display next to other users
5135 * @deprecated since Moodle 3.2
5136 * @param bool $incontactlist is the user a contact
5137 * @param bool $isblocked is the user blocked
5138 * @param stdClass $contact contact object
5139 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5140 * @param bool $text include text next to the icons?
5141 * @param bool $icon include a graphical icon?
5144 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5145 debugging('message_get_contact_add_remove_link() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
5150 $strcontact = message_contact_link($contact->id
, 'remove', true, $script, $text, $icon);
5151 } else if ($isblocked) {
5152 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
5154 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
5161 * Constructs the block contact link to display next to other users
5163 * @deprecated since Moodle 3.2
5164 * @param bool $incontactlist is the user a contact?
5165 * @param bool $isblocked is the user blocked?
5166 * @param stdClass $contact contact object
5167 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5168 * @param bool $text include text next to the icons?
5169 * @param bool $icon include a graphical icon?
5172 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5173 debugging('message_get_contact_block_link() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
5177 //commented out to allow the user to block a contact without having to remove them first
5178 /*if ($incontactlist) {
5182 $strblock = message_contact_link($contact->id
, 'unblock', true, $script, $text, $icon);
5184 $strblock = message_contact_link($contact->id
, 'block', true, $script, $text, $icon);
5191 * marks ALL messages being sent from $fromuserid to $touserid as read
5193 * @deprecated since Moodle 3.2
5194 * @param int $touserid the id of the message recipient
5195 * @param int $fromuserid the id of the message sender
5198 function message_mark_messages_read($touserid, $fromuserid) {
5199 debugging('message_mark_messages_read() is deprecated and is no longer used, please use
5200 \core_message\api::mark_all_read_for_user() instead.', DEBUG_DEVELOPER
);
5202 \core_message\api
::mark_all_read_for_user($touserid, $fromuserid);
5206 * Return a list of page types
5208 * @deprecated since Moodle 3.2
5209 * @param string $pagetype current page type
5210 * @param stdClass $parentcontext Block's parent context
5211 * @param stdClass $currentcontext Current context of block
5213 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
5214 debugging('message_page_type_list() is deprecated and is no longer used.', DEBUG_DEVELOPER
);
5216 return array('messages-*'=>get_string('page-message-x', 'message'));
5220 * Determines if a user is permitted to send another user a private message.
5221 * If no sender is provided then it defaults to the logged in user.
5223 * @deprecated since Moodle 3.2
5224 * @param object $recipient User object.
5225 * @param object $sender User object.
5226 * @return bool true if user is permitted, false otherwise.
5228 function message_can_post_message($recipient, $sender = null) {
5229 debugging('message_can_post_message() is deprecated and is no longer used, please use
5230 \core_message\api::can_post_message() instead.', DEBUG_DEVELOPER
);
5232 return \core_message\api
::can_post_message($recipient, $sender);
5236 * Checks if the recipient is allowing messages from users that aren't a
5237 * contact. If not then it checks to make sure the sender is in the
5238 * recipient's contacts.
5240 * @deprecated since Moodle 3.2
5241 * @param object $recipient User object.
5242 * @param object $sender User object.
5243 * @return bool true if $sender is blocked, false otherwise.
5245 function message_is_user_non_contact_blocked($recipient, $sender = null) {
5246 debugging('message_is_user_non_contact_blocked() is deprecated and is no longer used, please use
5247 \core_message\api::is_user_non_contact_blocked() instead.', DEBUG_DEVELOPER
);
5249 return \core_message\api
::is_user_non_contact_blocked($recipient, $sender);
5253 * Checks if the recipient has specifically blocked the sending user.
5255 * Note: This function will always return false if the sender has the
5256 * readallmessages capability at the system context level.
5258 * @deprecated since Moodle 3.2
5259 * @param object $recipient User object.
5260 * @param object $sender User object.
5261 * @return bool true if $sender is blocked, false otherwise.
5263 function message_is_user_blocked($recipient, $sender = null) {
5264 debugging('message_is_user_blocked() is deprecated and is no longer used, please use
5265 \core_message\api::is_user_blocked() instead.', DEBUG_DEVELOPER
);
5268 if ($sender !== null && isset($sender->id
)) {
5269 $senderid = $sender->id
;
5271 return \core_message\api
::is_user_blocked($recipient->id
, $senderid);
5277 * @deprecated since 3.2
5279 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5280 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5281 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5283 global $CFG, $DB, $OUTPUT;
5285 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
5286 $modname, $modid, $modaction, $groupid)) {
5287 echo $OUTPUT->notification("No logs found!");
5288 echo $OUTPUT->footer();
5294 if ($course->id
== SITEID
) {
5296 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5297 foreach ($ccc as $cc) {
5298 $courses[$cc->id
] = $cc->shortname
;
5302 $courses[$course->id
] = $course->shortname
;
5305 $totalcount = $logs['totalcount'];
5308 $strftimedatetime = get_string("strftimedatetime");
5310 echo "<div class=\"info\">\n";
5311 print_string("displayingrecords", "", $totalcount);
5314 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5316 $table = new html_table();
5317 $table->classes
= array('logtable','generaltable');
5318 $table->align
= array('right', 'left', 'left');
5319 $table->head
= array(
5321 get_string('ip_address'),
5322 get_string('fullnameuser'),
5323 get_string('action'),
5326 $table->data
= array();
5328 if ($course->id
== SITEID
) {
5329 array_unshift($table->align
, 'left');
5330 array_unshift($table->head
, get_string('course'));
5333 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
5334 if (empty($logs['logs'])) {
5335 $logs['logs'] = array();
5338 foreach ($logs['logs'] as $log) {
5340 if (isset($ldcache[$log->module
][$log->action
])) {
5341 $ld = $ldcache[$log->module
][$log->action
];
5343 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
5344 $ldcache[$log->module
][$log->action
] = $ld;
5346 if ($ld && is_numeric($log->info
)) {
5347 // ugly hack to make sure fullname is shown correctly
5348 if ($ld->mtable
== 'user' && $ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname')) {
5349 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
5351 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
5356 $log->info
= format_string($log->info
);
5358 // If $log->url has been trimmed short by the db size restriction
5359 // code in add_to_log, keep a note so we don't add a link to a broken url
5360 $brokenurl=(core_text
::strlen($log->url
)==100 && core_text
::substr($log->url
,97)=='...');
5363 if ($course->id
== SITEID
) {
5364 if (empty($log->course
)) {
5365 $row[] = get_string('site');
5367 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>";
5371 $row[] = userdate($log->time
, '%a').' '.userdate($log->time
, $strftimedatetime);
5373 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5374 $row[] = $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
5376 $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
))));
5378 $displayaction="$log->module $log->action";
5380 $row[] = $displayaction;
5382 $link = make_log_url($log->module
,$log->url
);
5383 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
5385 $row[] = $log->info
;
5386 $table->data
[] = $row;
5389 echo html_writer
::table($table);
5390 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5394 * Display MNET logs.
5396 * @deprecated since 3.2
5398 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5399 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5400 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5402 global $CFG, $DB, $OUTPUT;
5404 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
5405 $modname, $modid, $modaction, $groupid)) {
5406 echo $OUTPUT->notification("No logs found!");
5407 echo $OUTPUT->footer();
5411 if ($course->id
== SITEID
) {
5413 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
5414 foreach ($ccc as $cc) {
5415 $courses[$cc->id
] = $cc->shortname
;
5420 $totalcount = $logs['totalcount'];
5423 $strftimedatetime = get_string("strftimedatetime");
5425 echo "<div class=\"info\">\n";
5426 print_string("displayingrecords", "", $totalcount);
5429 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5431 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
5433 if ($course->id
== SITEID
) {
5434 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
5436 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
5437 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
5438 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
5439 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
5440 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
5443 if (empty($logs['logs'])) {
5449 foreach ($logs['logs'] as $log) {
5451 $log->info
= $log->coursename
;
5452 $row = ($row +
1) %
2;
5454 if (isset($ldcache[$log->module
][$log->action
])) {
5455 $ld = $ldcache[$log->module
][$log->action
];
5457 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
5458 $ldcache[$log->module
][$log->action
] = $ld;
5460 if (0 && $ld && !empty($log->info
)) {
5461 // ugly hack to make sure fullname is shown correctly
5462 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5463 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
5465 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
5470 $log->info
= format_string($log->info
);
5472 echo '<tr class="r'.$row.'">';
5473 if ($course->id
== SITEID
) {
5474 $courseshortname = format_string($courses[$log->course
], true, array('context' => context_course
::instance(SITEID
)));
5475 echo "<td class=\"r$row c0\" >\n";
5476 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
5479 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
5480 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
5481 echo "<td class=\"r$row c2\" >\n";
5482 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5483 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
5485 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course
::instance($course->id
)));
5486 echo "<td class=\"r$row c3\" >\n";
5487 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
5489 echo "<td class=\"r$row c4\">\n";
5490 echo $log->action
.': '.$log->module
;
5492 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
5497 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5501 * Display logs in CSV format.
5503 * @deprecated since 3.2
5505 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
5506 $modid, $modaction, $groupid) {
5507 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5511 require_once($CFG->libdir
. '/csvlib.class.php');
5513 $csvexporter = new csv_export_writer('tab');
5516 $header[] = get_string('course');
5517 $header[] = get_string('time');
5518 $header[] = get_string('ip_address');
5519 $header[] = get_string('fullnameuser');
5520 $header[] = get_string('action');
5521 $header[] = get_string('info');
5523 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5524 $modname, $modid, $modaction, $groupid)) {
5530 if ($course->id
== SITEID
) {
5532 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5533 foreach ($ccc as $cc) {
5534 $courses[$cc->id
] = $cc->shortname
;
5538 $courses[$course->id
] = $course->shortname
;
5543 $tt = getdate(time());
5544 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5546 $strftimedatetime = get_string("strftimedatetime");
5548 $csvexporter->set_filename('logs', '.txt');
5549 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
5550 $csvexporter->add_data($title);
5551 $csvexporter->add_data($header);
5553 if (empty($logs['logs'])) {
5557 foreach ($logs['logs'] as $log) {
5558 if (isset($ldcache[$log->module
][$log->action
])) {
5559 $ld = $ldcache[$log->module
][$log->action
];
5561 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
5562 $ldcache[$log->module
][$log->action
] = $ld;
5564 if ($ld && is_numeric($log->info
)) {
5565 // ugly hack to make sure fullname is shown correctly
5566 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5567 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
5569 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
5574 $log->info
= format_string($log->info
);
5575 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
5577 $coursecontext = context_course
::instance($course->id
);
5578 $firstField = format_string($courses[$log->course
], true, array('context' => $coursecontext));
5579 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5580 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
5581 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
.' ('.$actionurl.')', $log->info
);
5582 $csvexporter->add_data($row);
5584 $csvexporter->download_file();
5589 * Display logs in XLS format.
5591 * @deprecated since 3.2
5593 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
5594 $modid, $modaction, $groupid) {
5595 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5599 require_once("$CFG->libdir/excellib.class.php");
5601 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5602 $modname, $modid, $modaction, $groupid)) {
5608 if ($course->id
== SITEID
) {
5610 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5611 foreach ($ccc as $cc) {
5612 $courses[$cc->id
] = $cc->shortname
;
5616 $courses[$course->id
] = $course->shortname
;
5621 $tt = getdate(time());
5622 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5624 $strftimedatetime = get_string("strftimedatetime");
5626 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
5627 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5628 $filename .= '.xls';
5630 $workbook = new MoodleExcelWorkbook('-');
5631 $workbook->send($filename);
5633 $worksheet = array();
5634 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5635 get_string('fullnameuser'), get_string('action'), get_string('info'));
5637 // Creating worksheets
5638 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
5639 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5640 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5641 $worksheet[$wsnumber]->set_column(1, 1, 30);
5642 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5643 userdate(time(), $strftimedatetime));
5645 foreach ($headers as $item) {
5646 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
5651 if (empty($logs['logs'])) {
5656 $formatDate =& $workbook->add_format();
5657 $formatDate->set_num_format(get_string('log_excel_date_format'));
5659 $row = FIRSTUSEDEXCELROW
;
5661 $myxls =& $worksheet[$wsnumber];
5662 foreach ($logs['logs'] as $log) {
5663 if (isset($ldcache[$log->module
][$log->action
])) {
5664 $ld = $ldcache[$log->module
][$log->action
];
5666 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
5667 $ldcache[$log->module
][$log->action
] = $ld;
5669 if ($ld && is_numeric($log->info
)) {
5670 // ugly hack to make sure fullname is shown correctly
5671 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5672 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
5674 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
5679 $log->info
= format_string($log->info
);
5680 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
5683 if ($row > EXCELROWS
) {
5685 $myxls =& $worksheet[$wsnumber];
5686 $row = FIRSTUSEDEXCELROW
;
5690 $coursecontext = context_course
::instance($course->id
);
5692 $myxls->write($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)), '');
5693 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
5694 $myxls->write($row, 2, $log->ip
, '');
5695 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5696 $myxls->write($row, 3, $fullname, '');
5697 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
5698 $myxls->write($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')', '');
5699 $myxls->write($row, 5, $log->info
, '');
5709 * Display logs in ODS format.
5711 * @deprecated since 3.2
5713 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
5714 $modid, $modaction, $groupid) {
5715 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5719 require_once("$CFG->libdir/odslib.class.php");
5721 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5722 $modname, $modid, $modaction, $groupid)) {
5728 if ($course->id
== SITEID
) {
5730 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5731 foreach ($ccc as $cc) {
5732 $courses[$cc->id
] = $cc->shortname
;
5736 $courses[$course->id
] = $course->shortname
;
5741 $strftimedatetime = get_string("strftimedatetime");
5743 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
5744 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5745 $filename .= '.ods';
5747 $workbook = new MoodleODSWorkbook('-');
5748 $workbook->send($filename);
5750 $worksheet = array();
5751 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5752 get_string('fullnameuser'), get_string('action'), get_string('info'));
5754 // Creating worksheets
5755 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
5756 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5757 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5758 $worksheet[$wsnumber]->set_column(1, 1, 30);
5759 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5760 userdate(time(), $strftimedatetime));
5762 foreach ($headers as $item) {
5763 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
5768 if (empty($logs['logs'])) {
5773 $formatDate =& $workbook->add_format();
5774 $formatDate->set_num_format(get_string('log_excel_date_format'));
5776 $row = FIRSTUSEDEXCELROW
;
5778 $myxls =& $worksheet[$wsnumber];
5779 foreach ($logs['logs'] as $log) {
5780 if (isset($ldcache[$log->module
][$log->action
])) {
5781 $ld = $ldcache[$log->module
][$log->action
];
5783 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
5784 $ldcache[$log->module
][$log->action
] = $ld;
5786 if ($ld && is_numeric($log->info
)) {
5787 // ugly hack to make sure fullname is shown correctly
5788 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5789 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
5791 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
5796 $log->info
= format_string($log->info
);
5797 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
5800 if ($row > EXCELROWS
) {
5802 $myxls =& $worksheet[$wsnumber];
5803 $row = FIRSTUSEDEXCELROW
;
5807 $coursecontext = context_course
::instance($course->id
);
5809 $myxls->write_string($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)));
5810 $myxls->write_date($row, 1, $log->time
);
5811 $myxls->write_string($row, 2, $log->ip
);
5812 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5813 $myxls->write_string($row, 3, $fullname);
5814 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
5815 $myxls->write_string($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')');
5816 $myxls->write_string($row, 5, $log->info
);
5826 * Build an array of logs.
5828 * @deprecated since 3.2
5830 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
5831 $modname="", $modid=0, $modaction="", $groupid=0) {
5832 global $DB, $SESSION, $USER;
5834 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5835 // It is assumed that $date is the GMT time of midnight for that day,
5836 // and so the next 86400 seconds worth of logs are printed.
5838 // Setup for group handling.
5840 // If the group mode is separate, and this user does not have editing privileges,
5841 // then only the user's group can be viewed.
5842 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', context_course
::instance($course->id
))) {
5843 if (isset($SESSION->currentgroup
[$course->id
])) {
5844 $groupid = $SESSION->currentgroup
[$course->id
];
5846 $groupid = groups_get_all_groups($course->id
, $USER->id
);
5847 if (is_array($groupid)) {
5848 $groupid = array_shift(array_keys($groupid));
5849 $SESSION->currentgroup
[$course->id
] = $groupid;
5855 // If this course doesn't have groups, no groupid can be specified.
5856 else if (!$course->groupmode
) {
5863 if ($course->id
!= SITEID ||
$modid != 0) {
5864 $joins[] = "l.course = :courseid";
5865 $params['courseid'] = $course->id
;
5869 $joins[] = "l.module = :modname";
5870 $params['modname'] = $modname;
5873 if ('site_errors' === $modid) {
5874 $joins[] = "( l.action='error' OR l.action='infected' )";
5875 } else if ($modid) {
5876 $joins[] = "l.cmid = :modid";
5877 $params['modid'] = $modid;
5881 $firstletter = substr($modaction, 0, 1);
5882 if ($firstletter == '-') {
5883 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
5884 $params['modaction'] = '%'.substr($modaction, 1).'%';
5886 $joins[] = $DB->sql_like('l.action', ':modaction', false);
5887 $params['modaction'] = '%'.$modaction.'%';
5892 /// Getting all members of a group.
5893 if ($groupid and !$user) {
5894 if ($gusers = groups_get_members($groupid)) {
5895 $gusers = array_keys($gusers);
5896 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
5898 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
5902 $joins[] = "l.userid = :userid";
5903 $params['userid'] = $user;
5907 $enddate = $date +
86400;
5908 $joins[] = "l.time > :date AND l.time < :enddate";
5909 $params['date'] = $date;
5910 $params['enddate'] = $enddate;
5913 $selector = implode(' AND ', $joins);
5915 $totalcount = 0; // Initialise
5917 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
5918 $result['totalcount'] = $totalcount;
5923 * Select all log records for a given course and user.
5925 * @deprecated since 3.2
5926 * @param int $userid The id of the user as found in the 'user' table.
5927 * @param int $courseid The id of the course as found in the 'course' table.
5928 * @param string $coursestart unix timestamp representing course start date and time.
5931 function get_logs_usercourse($userid, $courseid, $coursestart) {
5934 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5940 $courseselect = "AND course = :courseid";
5941 $params['courseid'] = $courseid;
5943 $params['userid'] = $userid;
5944 // We have to sanitize this param ourselves here instead of relying on DB.
5945 // Postgres complains if you use name parameter or column alias in GROUP BY.
5946 // See MDL-27696 and 51c3e85 for details.
5947 $coursestart = (int)$coursestart;
5949 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS
.") AS day, COUNT(*) AS num
5951 WHERE userid = :userid
5952 AND time > $coursestart $courseselect
5953 GROUP BY FLOOR((time - $coursestart)/". DAYSECS
.")", $params);
5957 * Select all log records for a given course, user, and day.
5959 * @deprecated since 3.2
5960 * @param int $userid The id of the user as found in the 'user' table.
5961 * @param int $courseid The id of the course as found in the 'course' table.
5962 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
5965 function get_logs_userday($userid, $courseid, $daystart) {
5968 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
5970 $params = array('userid'=>$userid);
5974 $courseselect = "AND course = :courseid";
5975 $params['courseid'] = $courseid;
5977 // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
5978 $daystart = (int) $daystart;
5980 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS
.") AS hour, COUNT(*) AS num
5982 WHERE userid = :userid
5983 AND time > $daystart $courseselect
5984 GROUP BY FLOOR((time - $daystart)/". HOURSECS
.") ", $params);
5988 * Select all log records based on SQL criteria.
5990 * @deprecated since 3.2
5991 * @param string $select SQL select criteria
5992 * @param array $params named sql type params
5993 * @param string $order SQL order by clause to sort the records returned
5994 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
5995 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
5996 * @param int $totalcount Passed in by reference.
5999 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
6002 debugging(__FUNCTION__
. '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER
);
6005 $order = "ORDER BY $order";
6009 $select = "WHERE $select";
6012 $sql = "SELECT COUNT(*)
6016 $totalcount = $DB->count_records_sql($sql, $params);
6017 $allnames = get_all_user_name_fields(true, 'u');
6018 $sql = "SELECT l.*, $allnames, u.picture
6020 LEFT JOIN {user} u ON l.userid = u.id
6024 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
6028 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
6030 * @deprecated since Moodle 3.2 MDL-53048
6032 function prevent_form_autofill_password() {
6033 debugging('prevent_form_autofill_password has been deprecated and is no longer in use.', DEBUG_DEVELOPER
);
6038 * Get the users recent conversations meaning all the people they've recently
6039 * sent or received a message from plus the most recent message sent to or received from each other user
6041 * @deprecated since Moodle 3.3 MDL-57370
6042 * @param object|int $userorid the current user or user id
6043 * @param int $limitfrom can be used for paging
6044 * @param int $limitto can be used for paging
6047 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
6050 debugging('message_get_recent_conversations() is deprecated. Please use \core_message\api::get_conversations() instead.', DEBUG_DEVELOPER
);
6052 if (is_object($userorid)) {
6055 $userid = $userorid;
6056 $user = new stdClass();
6057 $user->id
= $userid;
6060 $userfields = user_picture
::fields('otheruser', array('lastaccess'));
6062 // This query retrieves the most recent message received from or sent to
6063 // seach other user.
6065 // If two messages have the same timecreated, we take the one with the
6068 // There is a separate query for read and unread messages as they are stored
6069 // in different tables. They were originally retrieved in one query but it
6070 // was so large that it was difficult to be confident in its correctness.
6071 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
6072 $sql = "SELECT $uniquefield, $userfields,
6073 message.id as mid, message.notification, message.useridfrom, message.useridto,
6074 message.smallmessage, message.fullmessage, message.fullmessagehtml,
6075 message.fullmessageformat, message.timecreated,
6076 contact.id as contactlistid, contact.blocked
6077 FROM {message_read} message
6079 SELECT MAX(id) AS messageid,
6080 matchedmessage.useridto,
6081 matchedmessage.useridfrom
6082 FROM {message_read} matchedmessage
6084 SELECT MAX(recentmessages.timecreated) timecreated,
6085 recentmessages.useridfrom,
6086 recentmessages.useridto
6087 FROM {message_read} recentmessages
6089 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
6090 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
6092 GROUP BY recentmessages.useridfrom, recentmessages.useridto
6093 ) recent ON matchedmessage.useridto = recent.useridto
6094 AND matchedmessage.useridfrom = recent.useridfrom
6095 AND matchedmessage.timecreated = recent.timecreated
6097 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
6098 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
6100 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
6101 ) messagesubset ON messagesubset.messageid = message.id
6102 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
6103 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
6104 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.contactid = otheruser.id
6105 WHERE otheruser.deleted = 0 AND message.notification = 0
6106 ORDER BY message.timecreated DESC";
6108 'userid1' => $user->id
,
6109 'userid2' => $user->id
,
6110 'userid3' => $user->id
,
6111 'userid4' => $user->id
,
6112 'userid5' => $user->id
,
6113 'userid6' => $user->id
,
6114 'userid7' => $user->id
6116 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
6118 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
6119 // exact same query as the one above, except for the table we are querying. So, simply replace references to
6120 // the 'message_read' table with the 'message' table.
6121 $sql = str_replace('{message_read}', '{message}', $sql);
6122 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
6124 $unreadcountssql = 'SELECT useridfrom, count(*) as count
6126 WHERE useridto = :userid
6127 AND timeusertodeleted = 0
6128 AND notification = 0
6129 GROUP BY useridfrom';
6130 $unreadcounts = $DB->get_records_sql($unreadcountssql, array('userid' => $user->id
));
6132 // Union the 2 result sets together looking for the message with the most
6133 // recent timecreated for each other user.
6134 // $conversation->id (the array key) is the other user's ID.
6135 $conversations = array();
6136 $conversation_arrays = array($unread, $read);
6137 foreach ($conversation_arrays as $conversation_array) {
6138 foreach ($conversation_array as $conversation) {
6139 // Only consider it unread if $user has unread messages.
6140 if (isset($unreadcounts[$conversation->useridfrom
])) {
6141 $conversation->isread
= 0;
6142 $conversation->unreadcount
= $unreadcounts[$conversation->useridfrom
]->count
;
6144 $conversation->isread
= 1;
6147 if (!isset($conversations[$conversation->id
])) {
6148 $conversations[$conversation->id
] = $conversation;
6150 $current = $conversations[$conversation->id
];
6151 // We need to maintain the isread and unreadcount values from existing
6152 // parts of the conversation if we're replacing it.
6153 $conversation->isread
= ($conversation->isread
&& $current->isread
);
6154 if (isset($current->unreadcount
) && !isset($conversation->unreadcount
)) {
6155 $conversation->unreadcount
= $current->unreadcount
;
6158 if ($current->timecreated
< $conversation->timecreated
) {
6159 $conversations[$conversation->id
] = $conversation;
6160 } else if ($current->timecreated
== $conversation->timecreated
) {
6161 if ($current->mid
< $conversation->mid
) {
6162 $conversations[$conversation->id
] = $conversation;
6169 // Sort the conversations by $conversation->timecreated, newest to oldest
6170 // There may be multiple conversations with the same timecreated
6171 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
6172 $result = core_collator
::asort_objects_by_property($conversations, 'timecreated', core_collator
::SORT_NUMERIC
);
6173 $conversations = array_reverse($conversations);
6175 return $conversations;
6179 * Display calendar preference button.
6181 * @param stdClass $course course object
6182 * @deprecated since Moodle 3.2
6183 * @return string return preference button in html
6185 function calendar_preferences_button(stdClass
$course) {
6186 debugging('This should no longer be used, the calendar preferences are now linked to the user preferences page.');
6190 // Guests have no preferences.
6191 if (!isloggedin() ||
isguestuser()) {
6195 return $OUTPUT->single_button(new moodle_url('/user/calendar.php'), get_string("preferences", "calendar"));
6199 * Return the name of the weekday
6201 * @deprecated since 3.3
6202 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6203 * @param string $englishname
6204 * @return string of the weekeday
6206 function calendar_wday_name($englishname) {
6207 debugging(__FUNCTION__
. '() is deprecated and no longer used in core.', DEBUG_DEVELOPER
);
6208 return get_string(strtolower($englishname), 'calendar');
6212 * Get the upcoming event block.
6214 * @deprecated since 3.3
6215 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6216 * @param array $events list of events
6217 * @param moodle_url|string $linkhref link to event referer
6218 * @param boolean $showcourselink whether links to courses should be shown
6219 * @return string|null $content html block content
6221 function calendar_get_block_upcoming($events, $linkhref = null, $showcourselink = false) {
6225 __FUNCTION__
. '() has been deprecated. ' .
6226 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
6230 require_once($CFG->dirroot
. '/blocks/moodleblock.class.php');
6231 require_once($CFG->dirroot
. '/blocks/calendar_upcoming/block_calendar_upcoming.php');
6232 return block_calendar_upcoming
::get_upcoming_content($events, $linkhref, $showcourselink);
6236 * Display month selector options.
6238 * @deprecated since 3.3
6239 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6240 * @param string $name for the select element
6241 * @param string|array $selected options for select elements
6243 function calendar_print_month_selector($name, $selected) {
6244 debugging(__FUNCTION__
. '() is deprecated and no longer used in core.', DEBUG_DEVELOPER
);
6246 for ($i = 1; $i <= 12; $i++
) {
6247 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
6249 echo html_writer
::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
6250 echo html_writer
::select($months, $name, $selected, false);
6254 * Update calendar subscriptions.
6256 * @deprecated since 3.3
6257 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
6260 function calendar_cron() {
6261 debugging(__FUNCTION__
. '() is deprecated and should not be used. Please use the core\task\calendar_cron_task instead.',
6266 require_once($CFG->dirroot
. '/calendar/lib.php');
6267 // In order to execute this we need bennu.
6268 require_once($CFG->libdir
.'/bennu/bennu.inc.php');
6270 mtrace('Updating calendar subscriptions:');
6271 cron_trace_time_and_memory();
6274 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0
6275 AND lastupdated + pollinterval < ?', array($time));
6276 foreach ($subscriptions as $sub) {
6277 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
6279 $log = calendar_update_subscription_events($sub->id
);
6280 mtrace(trim(strip_tags($log)));
6281 } catch (moodle_exception
$ex) {
6282 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
6286 mtrace('Finished updating calendar subscriptions.');
6292 * Previous internal API, it was not supposed to be used anywhere.
6295 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6296 * @param int $userid the id of the user
6297 * @param context_course $coursecontext course context
6298 * @param array $accessdata accessdata array (modified)
6299 * @return void modifies $accessdata parameter
6301 function load_course_context($userid, context_course
$coursecontext, &$accessdata) {
6302 throw new coding_exception('load_course_context() is removed. Do not use private functions or data structures.');
6306 * Previous internal API, it was not supposed to be used anywhere.
6309 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6310 * @param int $roleid the id of the user
6311 * @param context $context needs path!
6312 * @param array $accessdata accessdata array (is modified)
6315 function load_role_access_by_context($roleid, context
$context, &$accessdata) {
6316 throw new coding_exception('load_role_access_by_context() is removed. Do not use private functions or data structures.');
6320 * Previous internal API, it was not supposed to be used anywhere.
6323 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
6326 function dedupe_user_access() {
6327 throw new coding_exception('dedupe_user_access() is removed. Do not use private functions or data structures.');
6331 * Previous internal API, it was not supposed to be used anywhere.
6332 * Return a nested array showing role assignments
6333 * and all relevant role capabilities for the user.
6335 * [ra] => [/path][roleid]=roleid
6336 * [rdef] => ["$contextpath:$roleid"][capability]=permission
6339 * @deprecated since Moodle 3.4. MDL-49398.
6340 * @param int $userid - the id of the user
6341 * @return array access info array
6343 function get_user_access_sitewide($userid) {
6344 debugging('get_user_access_sitewide() is deprecated. Do not use private functions or data structures.', DEBUG_DEVELOPER
);
6346 $accessdata = get_user_accessdata($userid);
6347 $accessdata['rdef'] = array();
6350 foreach ($accessdata['ra'] as $path => $pathroles) {
6351 $roles = array_merge($pathroles, $roles);
6354 $rdefs = get_role_definitions($roles);
6356 foreach ($rdefs as $roleid => $rdef) {
6357 foreach ($rdef as $path => $caps) {
6358 $accessdata['rdef']["$path:$roleid"] = $caps;
6366 * Generates the HTML for a miniature calendar.
6368 * @param array $courses list of course to list events from
6369 * @param array $groups list of group
6370 * @param array $users user's info
6371 * @param int|bool $calmonth calendar month in numeric, default is set to false
6372 * @param int|bool $calyear calendar month in numeric, default is set to false
6373 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
6374 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
6375 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
6376 * and $calyear to support multiple calendars
6377 * @return string $content return html table for mini calendar
6378 * @deprecated since Moodle 3.4. MDL-59333
6380 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
6381 $courseid = false, $time = 0) {
6384 debugging('calendar_get_mini() has been deprecated. Please update your code to use calendar_get_view.',
6387 if (!empty($calmonth) && !empty($calyear)) {
6388 // Do this check for backwards compatibility.
6389 // The core should be passing a timestamp rather than month and year.
6390 // If a month and year are passed they will be in Gregorian.
6391 // Ensure it is a valid date, else we will just set it to the current timestamp.
6392 if (checkdate($calmonth, 1, $calyear)) {
6393 $time = make_timestamp($calyear, $calmonth, 1);
6397 } else if (empty($time)) {
6398 // Get the current date in the calendar type being used.
6402 if ($courseid == SITEID
) {
6403 $course = get_site();
6405 $course = get_course($courseid);
6407 $calendar = new calendar_information(0, 0, 0, $time);
6408 $calendar->prepare_for_view($course, $courses);
6410 $renderer = $PAGE->get_renderer('core_calendar');
6411 list($data, $template) = calendar_get_view($calendar, 'mini');
6412 return $renderer->render_from_template($template, $data);
6416 * Gets the calendar upcoming event.
6418 * @param array $courses array of courses
6419 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
6420 * @param array|int|bool $users array of users, user id or boolean for all/no user events
6421 * @param int $daysinfuture number of days in the future we 'll look
6422 * @param int $maxevents maximum number of events
6423 * @param int $fromtime start time
6424 * @return array $output array of upcoming events
6425 * @deprecated since Moodle 3.4. MDL-59333
6427 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
6429 'calendar_get_upcoming() has been deprecated. ' .
6430 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
6436 $display = new \stdClass
;
6437 $display->range
= $daysinfuture; // How many days in the future we 'll look.
6438 $display->maxevents
= $maxevents;
6443 $now = time(); // We 'll need this later.
6444 $usermidnighttoday = usergetmidnight($now);
6447 $display->tstart
= $fromtime;
6449 $display->tstart
= $usermidnighttoday;
6452 // This works correctly with respect to the user's DST, but it is accurate
6453 // only because $fromtime is always the exact midnight of some day!
6454 $display->tend
= usergetmidnight($display->tstart + DAYSECS
* $display->range +
3 * HOURSECS
) - 1;
6456 // Get the events matching our criteria.
6457 $events = calendar_get_legacy_events($display->tstart
, $display->tend
, $users, $groups, $courses);
6459 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
6460 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
6461 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
6462 // arguments to this function.
6463 $hrefparams = array();
6464 if (!empty($courses)) {
6465 $courses = array_diff($courses, array(SITEID
));
6466 if (count($courses) == 1) {
6467 $hrefparams['course'] = reset($courses);
6471 if ($events !== false) {
6472 foreach ($events as $event) {
6473 if (!empty($event->modulename
)) {
6474 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
6475 if (empty($instances[$event->instance
]->uservisible
)) {
6480 if ($processed >= $display->maxevents
) {
6484 $event->time
= calendar_format_event_time($event, $now, $hrefparams);
6494 * Creates a record in the role_allow_override table
6496 * @param int $sroleid source roleid
6497 * @param int $troleid target roleid
6499 * @deprecated since Moodle 3.4. MDL-50666
6501 function allow_override($sroleid, $troleid) {
6502 debugging('allow_override() has been deprecated. Please update your code to use core_role_set_override_allowed.',
6505 core_role_set_override_allowed($sroleid, $troleid);
6509 * Creates a record in the role_allow_assign table
6511 * @param int $fromroleid source roleid
6512 * @param int $targetroleid target roleid
6514 * @deprecated since Moodle 3.4. MDL-50666
6516 function allow_assign($fromroleid, $targetroleid) {
6517 debugging('allow_assign() has been deprecated. Please update your code to use core_role_set_assign_allowed.',
6520 core_role_set_assign_allowed($fromroleid, $targetroleid);
6524 * Creates a record in the role_allow_switch table
6526 * @param int $fromroleid source roleid
6527 * @param int $targetroleid target roleid
6529 * @deprecated since Moodle 3.4. MDL-50666
6531 function allow_switch($fromroleid, $targetroleid) {
6532 debugging('allow_switch() has been deprecated. Please update your code to use core_role_set_switch_allowed.',
6535 core_role_set_switch_allowed($fromroleid, $targetroleid);
6539 * Organise categories into a single parent category (called the 'Top' category) per context.
6541 * @param array $categories List of question categories in the format of ["$categoryid,$contextid" => $category].
6542 * @param array $pcontexts List of context ids.
6544 * @deprecated since Moodle 3.5. MDL-61132
6546 function question_add_tops($categories, $pcontexts) {
6547 debugging('question_add_tops() has been deprecated. You may want to pass $top = true to get_categories_for_contexts().',
6551 foreach ($pcontexts as $context) {
6552 $topcat = question_get_top_category($context, true);
6554 $newcat = new stdClass();
6555 $newcat->id
= "{$topcat->id},$context";
6556 $newcat->name
= get_string('top');
6557 $newcat->parent
= 0;
6558 $newcat->contextid
= $context;
6559 $topcats["{$topcat->id},$context"] = $newcat;
6561 // Put topcats in at beginning of array - they'll be sorted into different contexts later.
6562 return array_merge($topcats, $categories);
6566 * Checks if the question category is the highest-level category in the context that can be edited, and has no siblings.
6568 * @param int $categoryid a category id.
6570 * @deprecated since Moodle 3.5. MDL-61132
6572 function question_is_only_toplevel_category_in_context($categoryid) {
6573 debugging('question_is_only_toplevel_category_in_context() has been deprecated. '
6574 . 'Please update your code to use question_is_only_child_of_top_category_in_context() instead.',
6577 return question_is_only_child_of_top_category_in_context($categoryid);