Merge branch 'MDL-43230-master' of git://github.com/ryanwyllie/moodle
[moodle.git] / lib / deprecatedlib.php
blob01bd4caf5adbbaa6abdda8d91b6d6b2c9b34d24d
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * deprecatedlib.php - Old functions retained only for backward compatibility
21 * Old functions retained only for backward compatibility. New code should not
22 * use any of these functions.
24 * @package core
25 * @subpackage deprecated
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 * @deprecated
31 defined('MOODLE_INTERNAL') || die();
33 /* === Functions that needs to be kept longer in deprecated lib than normal time period === */
35 /**
36 * Add an entry to the legacy log table.
38 * @deprecated since 2.7 use new events instead
40 * @param int $courseid The course id
41 * @param string $module The module name e.g. forum, journal, resource, course, user etc
42 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
43 * @param string $url The file and parameters used to see the results of the action
44 * @param string $info Additional description information
45 * @param int $cm The course_module->id if there is one
46 * @param int|stdClass $user If log regards $user other than $USER
47 * @return void
49 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
50 debugging('add_to_log() has been deprecated, please rewrite your code to the new events API', DEBUG_DEVELOPER);
52 // This is a nasty hack that allows us to put all the legacy stuff into legacy storage,
53 // this way we may move all the legacy settings there too.
54 $manager = get_log_manager();
55 if (method_exists($manager, 'legacy_add_to_log')) {
56 $manager->legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
60 /**
61 * Function to call all event handlers when triggering an event
63 * @deprecated since 2.6
65 * @param string $eventname name of the event
66 * @param mixed $eventdata event data object
67 * @return int number of failed events
69 function events_trigger($eventname, $eventdata) {
70 debugging('events_trigger() is deprecated, please use new events instead', DEBUG_DEVELOPER);
71 return events_trigger_legacy($eventname, $eventdata);
74 /**
75 * List all core subsystems and their location
77 * This is a whitelist of components that are part of the core and their
78 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
79 * plugin is not listed here and it does not have proper plugintype prefix,
80 * then it is considered as course activity module.
82 * The location is optionally dirroot relative path. NULL means there is no special
83 * directory for this subsystem. If the location is set, the subsystem's
84 * renderer.php is expected to be there.
86 * @deprecated since 2.6, use core_component::get_core_subsystems()
88 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
89 * @return array of (string)name => (string|null)location
91 function get_core_subsystems($fullpaths = false) {
92 global $CFG;
94 // NOTE: do not add any other debugging here, keep forever.
96 $subsystems = core_component::get_core_subsystems();
98 if ($fullpaths) {
99 return $subsystems;
102 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
104 $dlength = strlen($CFG->dirroot);
106 foreach ($subsystems as $k => $v) {
107 if ($v === null) {
108 continue;
110 $subsystems[$k] = substr($v, $dlength+1);
113 return $subsystems;
117 * Lists all plugin types.
119 * @deprecated since 2.6, use core_component::get_plugin_types()
121 * @param bool $fullpaths false means relative paths from dirroot
122 * @return array Array of strings - name=>location
124 function get_plugin_types($fullpaths = true) {
125 global $CFG;
127 // NOTE: do not add any other debugging here, keep forever.
129 $types = core_component::get_plugin_types();
131 if ($fullpaths) {
132 return $types;
135 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
137 $dlength = strlen($CFG->dirroot);
139 foreach ($types as $k => $v) {
140 if ($k === 'theme') {
141 $types[$k] = 'theme';
142 continue;
144 $types[$k] = substr($v, $dlength+1);
147 return $types;
151 * Use when listing real plugins of one type.
153 * @deprecated since 2.6, use core_component::get_plugin_list()
155 * @param string $plugintype type of plugin
156 * @return array name=>fulllocation pairs of plugins of given type
158 function get_plugin_list($plugintype) {
160 // NOTE: do not add any other debugging here, keep forever.
162 if ($plugintype === '') {
163 $plugintype = 'mod';
166 return core_component::get_plugin_list($plugintype);
170 * Get a list of all the plugins of a given type that define a certain class
171 * in a certain file. The plugin component names and class names are returned.
173 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
175 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
176 * @param string $class the part of the name of the class after the
177 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
178 * names like report_courselist_thing. If you are looking for classes with
179 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
180 * @param string $file the name of file within the plugin that defines the class.
181 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
182 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
184 function get_plugin_list_with_class($plugintype, $class, $file) {
186 // NOTE: do not add any other debugging here, keep forever.
188 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
192 * Returns the exact absolute path to plugin directory.
194 * @deprecated since 2.6, use core_component::get_plugin_directory()
196 * @param string $plugintype type of plugin
197 * @param string $name name of the plugin
198 * @return string full path to plugin directory; NULL if not found
200 function get_plugin_directory($plugintype, $name) {
202 // NOTE: do not add any other debugging here, keep forever.
204 if ($plugintype === '') {
205 $plugintype = 'mod';
208 return core_component::get_plugin_directory($plugintype, $name);
212 * Normalize the component name using the "frankenstyle" names.
214 * @deprecated since 2.6, use core_component::normalize_component()
216 * @param string $component
217 * @return array as (string)$type => (string)$plugin
219 function normalize_component($component) {
221 // NOTE: do not add any other debugging here, keep forever.
223 return core_component::normalize_component($component);
227 * Return exact absolute path to a plugin directory.
229 * @deprecated since 2.6, use core_component::normalize_component()
231 * @param string $component name such as 'moodle', 'mod_forum'
232 * @return string full path to component directory; NULL if not found
234 function get_component_directory($component) {
236 // NOTE: do not add any other debugging here, keep forever.
238 return core_component::get_component_directory($component);
242 * Get the context instance as an object. This function will create the
243 * context instance if it does not exist yet.
245 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
246 * @todo This will be deleted in Moodle 2.8, refer MDL-34472
247 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
248 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
249 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
250 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
251 * MUST_EXIST means throw exception if no record or multiple records found
252 * @return context The context object.
254 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
256 debugging('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
258 $instances = (array)$instance;
259 $contexts = array();
261 $classname = context_helper::get_class_for_level($contextlevel);
263 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
264 foreach ($instances as $inst) {
265 $contexts[$inst] = $classname::instance($inst, $strictness);
268 if (is_array($instance)) {
269 return $contexts;
270 } else {
271 return $contexts[$instance];
274 /* === End of long term deprecated api list === */
277 * Adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
279 * @deprecated since 2.7 - use new file picker instead
282 function clam_log_upload($newfilepath, $course=null, $nourl=false) {
283 throw new coding_exception('clam_log_upload() can not be used any more, please use file picker instead');
287 * This function logs to error_log and to the log table that an infected file has been found and what's happened to it.
289 * @deprecated since 2.7 - use new file picker instead
292 function clam_log_infected($oldfilepath='', $newfilepath='', $userid=0) {
293 throw new coding_exception('clam_log_infected() can not be used any more, please use file picker instead');
297 * Some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
299 * @deprecated since 2.7 - use new file picker instead
302 function clam_change_log($oldpath, $newpath, $update=true) {
303 throw new coding_exception('clam_change_log() can not be used any more, please use file picker instead');
307 * Replaces the given file with a string.
309 * @deprecated since 2.7 - infected files are now deleted in file picker
312 function clam_replace_infected_file($file) {
313 throw new coding_exception('clam_replace_infected_file() can not be used any more, please use file picker instead');
317 * Deals with an infected file - either moves it to a quarantinedir
318 * (specified in CFG->quarantinedir) or deletes it.
320 * If moving it fails, it deletes it.
322 * @deprecated since 2.7
324 function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
325 throw new coding_exception('clam_handle_infected_file() can not be used any more, please use file picker instead');
329 * If $CFG->runclamonupload is set, we scan a given file. (called from {@link preprocess_files()})
331 * @deprecated since 2.7
333 function clam_scan_moodle_file(&$file, $course) {
334 throw new coding_exception('clam_scan_moodle_file() can not be used any more, please use file picker instead');
339 * Checks whether the password compatibility library will work with the current
340 * version of PHP. This cannot be done using PHP version numbers since the fix
341 * has been backported to earlier versions in some distributions.
343 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
345 * @deprecated since 2.7 PHP 5.4.x should be always compatible.
348 function password_compat_not_supported() {
349 throw new coding_exception('Do not use password_compat_not_supported() - bcrypt is now always available');
353 * Factory method that was returning moodle_session object.
355 * @deprecated since 2.6
357 function session_get_instance() {
358 throw new coding_exception('session_get_instance() is removed, use \core\session\manager instead');
362 * Returns true if legacy session used.
364 * @deprecated since 2.6
366 function session_is_legacy() {
367 throw new coding_exception('session_is_legacy() is removed, do not use any more');
371 * Terminates all sessions, auth hooks are not executed.
373 * @deprecated since 2.6
375 function session_kill_all() {
376 throw new coding_exception('session_kill_all() is removed, use \core\session\manager::kill_all_sessions() instead');
380 * Mark session as accessed, prevents timeouts.
382 * @deprecated since 2.6
384 function session_touch($sid) {
385 throw new coding_exception('session_touch() is removed, use \core\session\manager::touch_session() instead');
389 * Terminates one sessions, auth hooks are not executed.
391 * @deprecated since 2.6
393 function session_kill($sid) {
394 throw new coding_exception('session_kill() is removed, use \core\session\manager::kill_session() instead');
398 * Terminates all sessions of one user, auth hooks are not executed.
400 * @deprecated since 2.6
402 function session_kill_user($userid) {
403 throw new coding_exception('session_kill_user() is removed, use \core\session\manager::kill_user_sessions() instead');
407 * Setup $USER object - called during login, loginas, etc.
409 * Call sync_user_enrolments() manually after log-in, or log-in-as.
411 * @deprecated since 2.6
413 function session_set_user($user) {
414 throw new coding_exception('session_set_user() is removed, use \core\session\manager::set_user() instead');
418 * Is current $USER logged-in-as somebody else?
419 * @deprecated since 2.6
421 function session_is_loggedinas() {
422 throw new coding_exception('session_is_loggedinas() is removed, use \core\session\manager::is_loggedinas() instead');
426 * Returns the $USER object ignoring current login-as session
427 * @deprecated since 2.6
429 function session_get_realuser() {
430 throw new coding_exception('session_get_realuser() is removed, use \core\session\manager::get_realuser() instead');
434 * Login as another user - no security checks here.
435 * @deprecated since 2.6
437 function session_loginas($userid, $context) {
438 throw new coding_exception('session_loginas() is removed, use \core\session\manager::loginas() instead');
442 * Minify JavaScript files.
444 * @deprecated since 2.6
446 function js_minify($files) {
447 throw new coding_exception('js_minify() is removed, use core_minify::js_files() or core_minify::js() instead.');
451 * Minify CSS files.
453 * @deprecated since 2.6
455 function css_minify_css($files) {
456 throw new coding_exception('css_minify_css() is removed, use core_minify::css_files() or core_minify::css() instead.');
459 // === Deprecated before 2.6.0 ===
462 * Hack to find out the GD version by parsing phpinfo output
464 * @deprecated
466 function check_gd_version() {
467 throw new coding_exception('check_gd_version() is removed, GD extension is always available now');
471 * Not used any more, the account lockout handling is now
472 * part of authenticate_user_login().
473 * @deprecated
475 function update_login_count() {
476 throw new coding_exception('update_login_count() is removed, all calls need to be removed');
480 * Not used any more, replaced by proper account lockout.
481 * @deprecated
483 function reset_login_count() {
484 throw new coding_exception('reset_login_count() is removed, all calls need to be removed');
488 * @deprecated
490 function update_log_display_entry($module, $action, $mtable, $field) {
492 throw new coding_exception('The update_log_display_entry() is removed, please use db/log.php description file instead.');
496 * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions)
497 * this was abused mostly for embedding of attachments
499 function filter_text($text, $courseid = NULL) {
500 throw new coding_exception('filter_text() can not be used anymore, use format_text(), format_string() etc instead.');
504 * @deprecated use $PAGE->https_required() instead
506 function httpsrequired() {
507 throw new coding_exception('httpsrequired() can not be used any more use $PAGE->https_required() instead.');
511 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
513 * @deprecated since 3.1 - replacement legacy file API methods can be found on the moodle_url class, for example:
514 * The moodle_url::make_legacyfile_url() method can be used to generate a legacy course file url. To generate
515 * course module file.php url the moodle_url::make_file_url() should be used.
517 * @param string $path Physical path to a file
518 * @param array $options associative array of GET variables to append to the URL
519 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
520 * @return string URL to file
522 function get_file_url($path, $options=null, $type='coursefile') {
523 debugging('Function get_file_url() is deprecated, please use moodle_url factory methods instead.', DEBUG_DEVELOPER);
524 global $CFG;
526 $path = str_replace('//', '/', $path);
527 $path = trim($path, '/'); // no leading and trailing slashes
529 // type of file
530 switch ($type) {
531 case 'questionfile':
532 $url = $CFG->wwwroot."/question/exportfile.php";
533 break;
534 case 'rssfile':
535 $url = $CFG->wwwroot."/rss/file.php";
536 break;
537 case 'httpscoursefile':
538 $url = $CFG->httpswwwroot."/file.php";
539 break;
540 case 'coursefile':
541 default:
542 $url = $CFG->wwwroot."/file.php";
545 if ($CFG->slasharguments) {
546 $parts = explode('/', $path);
547 foreach ($parts as $key => $part) {
548 /// anchor dash character should not be encoded
549 $subparts = explode('#', $part);
550 $subparts = array_map('rawurlencode', $subparts);
551 $parts[$key] = implode('#', $subparts);
553 $path = implode('/', $parts);
554 $ffurl = $url.'/'.$path;
555 $separator = '?';
556 } else {
557 $path = rawurlencode('/'.$path);
558 $ffurl = $url.'?file='.$path;
559 $separator = '&amp;';
562 if ($options) {
563 foreach ($options as $name=>$value) {
564 $ffurl = $ffurl.$separator.$name.'='.$value;
565 $separator = '&amp;';
569 return $ffurl;
573 * @deprecated use get_enrolled_users($context) instead.
575 function get_course_participants($courseid) {
576 throw new coding_exception('get_course_participants() can not be used any more, use get_enrolled_users() instead.');
580 * @deprecated use is_enrolled($context, $userid) instead.
582 function is_course_participant($userid, $courseid) {
583 throw new coding_exception('is_course_participant() can not be used any more, use is_enrolled() instead.');
587 * @deprecated
589 function get_recent_enrolments($courseid, $timestart) {
590 throw new coding_exception('get_recent_enrolments() is removed as it returned inaccurate results.');
594 * @deprecated use clean_param($string, PARAM_FILE) instead.
596 function detect_munged_arguments($string, $allowdots=1) {
597 throw new coding_exception('detect_munged_arguments() can not be used any more, please use clean_param(,PARAM_FILE) instead.');
602 * Unzip one zip file to a destination dir
603 * Both parameters must be FULL paths
604 * If destination isn't specified, it will be the
605 * SAME directory where the zip file resides.
607 * @global object
608 * @param string $zipfile The zip file to unzip
609 * @param string $destination The location to unzip to
610 * @param bool $showstatus_ignored Unused
611 * @deprecated since 2.0 MDL-15919
613 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
614 debugging(__FUNCTION__ . '() is deprecated. '
615 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
617 // Extract everything from zipfile.
618 $path_parts = pathinfo(cleardoubleslashes($zipfile));
619 $zippath = $path_parts["dirname"]; //The path of the zip file
620 $zipfilename = $path_parts["basename"]; //The name of the zip file
621 $extension = $path_parts["extension"]; //The extension of the file
623 //If no file, error
624 if (empty($zipfilename)) {
625 return false;
628 //If no extension, error
629 if (empty($extension)) {
630 return false;
633 //Clear $zipfile
634 $zipfile = cleardoubleslashes($zipfile);
636 //Check zipfile exists
637 if (!file_exists($zipfile)) {
638 return false;
641 //If no destination, passed let's go with the same directory
642 if (empty($destination)) {
643 $destination = $zippath;
646 //Clear $destination
647 $destpath = rtrim(cleardoubleslashes($destination), "/");
649 //Check destination path exists
650 if (!is_dir($destpath)) {
651 return false;
654 $packer = get_file_packer('application/zip');
656 $result = $packer->extract_to_pathname($zipfile, $destpath);
658 if ($result === false) {
659 return false;
662 foreach ($result as $status) {
663 if ($status !== true) {
664 return false;
668 return true;
672 * Zip an array of files/dirs to a destination zip file
673 * Both parameters must be FULL paths to the files/dirs
675 * @global object
676 * @param array $originalfiles Files to zip
677 * @param string $destination The destination path
678 * @return bool Outcome
680 * @deprecated since 2.0 MDL-15919
682 function zip_files($originalfiles, $destination) {
683 debugging(__FUNCTION__ . '() is deprecated. '
684 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
686 // Extract everything from destination.
687 $path_parts = pathinfo(cleardoubleslashes($destination));
688 $destpath = $path_parts["dirname"]; //The path of the zip file
689 $destfilename = $path_parts["basename"]; //The name of the zip file
690 $extension = $path_parts["extension"]; //The extension of the file
692 //If no file, error
693 if (empty($destfilename)) {
694 return false;
697 //If no extension, add it
698 if (empty($extension)) {
699 $extension = 'zip';
700 $destfilename = $destfilename.'.'.$extension;
703 //Check destination path exists
704 if (!is_dir($destpath)) {
705 return false;
708 //Check destination path is writable. TODO!!
710 //Clean destination filename
711 $destfilename = clean_filename($destfilename);
713 //Now check and prepare every file
714 $files = array();
715 $origpath = NULL;
717 foreach ($originalfiles as $file) { //Iterate over each file
718 //Check for every file
719 $tempfile = cleardoubleslashes($file); // no doubleslashes!
720 //Calculate the base path for all files if it isn't set
721 if ($origpath === NULL) {
722 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
724 //See if the file is readable
725 if (!is_readable($tempfile)) { //Is readable
726 continue;
728 //See if the file/dir is in the same directory than the rest
729 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
730 continue;
732 //Add the file to the array
733 $files[] = $tempfile;
736 $zipfiles = array();
737 $start = strlen($origpath)+1;
738 foreach($files as $file) {
739 $zipfiles[substr($file, $start)] = $file;
742 $packer = get_file_packer('application/zip');
744 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
748 * @deprecated use groups_get_all_groups() instead.
750 function mygroupid($courseid) {
751 throw new coding_exception('mygroupid() can not be used any more, please use groups_get_all_groups() instead.');
756 * Returns the current group mode for a given course or activity module
758 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
760 * @deprecated since Moodle 2.0 MDL-14617 - please do not use this function any more.
761 * @todo MDL-50273 This will be deleted in Moodle 3.2.
763 * @param object $course Course Object
764 * @param object $cm Course Manager Object
765 * @return mixed $course->groupmode
767 function groupmode($course, $cm=null) {
769 debugging('groupmode() is deprecated, please use groups_get_* instead', DEBUG_DEVELOPER);
770 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
771 return $cm->groupmode;
773 return $course->groupmode;
777 * Sets the current group in the session variable
778 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
779 * Sets currentgroup[$courseid] in the session variable appropriately.
780 * Does not do any permission checking.
782 * @deprecated Since year 2006 - please do not use this function any more.
783 * @todo MDL-50273 This will be deleted in Moodle 3.2.
785 * @global object
786 * @global object
787 * @param int $courseid The course being examined - relates to id field in
788 * 'course' table.
789 * @param int $groupid The group being examined.
790 * @return int Current group id which was set by this function
792 function set_current_group($courseid, $groupid) {
793 global $SESSION;
795 debugging('set_current_group() is deprecated, please use $SESSION->currentgroup[$courseid] instead', DEBUG_DEVELOPER);
796 return $SESSION->currentgroup[$courseid] = $groupid;
800 * Gets the current group - either from the session variable or from the database.
802 * @deprecated Since year 2006 - please do not use this function any more.
803 * @todo MDL-50273 This will be deleted in Moodle 3.2.
805 * @global object
806 * @param int $courseid The course being examined - relates to id field in
807 * 'course' table.
808 * @param bool $full If true, the return value is a full record object.
809 * If false, just the id of the record.
810 * @return int|bool
812 function get_current_group($courseid, $full = false) {
813 global $SESSION;
815 debugging('get_current_group() is deprecated, please use groups_get_* instead', DEBUG_DEVELOPER);
816 if (isset($SESSION->currentgroup[$courseid])) {
817 if ($full) {
818 return groups_get_group($SESSION->currentgroup[$courseid]);
819 } else {
820 return $SESSION->currentgroup[$courseid];
824 $mygroupid = mygroupid($courseid);
825 if (is_array($mygroupid)) {
826 $mygroupid = array_shift($mygroupid);
827 set_current_group($courseid, $mygroupid);
828 if ($full) {
829 return groups_get_group($mygroupid);
830 } else {
831 return $mygroupid;
835 if ($full) {
836 return false;
837 } else {
838 return 0;
843 * @deprecated Since Moodle 2.8
845 function groups_filter_users_by_course_module_visible($cm, $users) {
846 throw new coding_exception('groups_filter_users_by_course_module_visible() is removed. ' .
847 'Replace with a call to \core_availability\info_module::filter_user_list(), ' .
848 'which does basically the same thing but includes other restrictions such ' .
849 'as profile restrictions.');
853 * @deprecated Since Moodle 2.8
855 function groups_course_module_visible($cm, $userid=null) {
856 throw new coding_exception('groups_course_module_visible() is removed, use $cm->uservisible to decide whether the current
857 user can ' . 'access an activity.', DEBUG_DEVELOPER);
861 * @deprecated since 2.0
863 function error($message, $link='') {
864 throw new coding_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a removed, please call
865 print_error() instead of error()');
870 * @deprecated use $PAGE->theme->name instead.
872 function current_theme() {
873 throw new coding_exception('current_theme() can not be used any more, please use $PAGE->theme->name instead');
877 * @deprecated
879 function formerr($error) {
880 throw new coding_exception('formerr() is removed. Please change your code to use $OUTPUT->error_text($string).');
884 * @deprecated use $OUTPUT->skip_link_target() in instead.
886 function skip_main_destination() {
887 throw new coding_exception('skip_main_destination() can not be used any more, please use $OUTPUT->skip_link_target() instead.');
891 * @deprecated use $OUTPUT->container() instead.
893 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
894 throw new coding_exception('print_container() can not be used any more. Please use $OUTPUT->container() instead.');
898 * @deprecated use $OUTPUT->container_start() instead.
900 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
901 throw new coding_exception('print_container_start() can not be used any more. Please use $OUTPUT->container_start() instead.');
905 * @deprecated use $OUTPUT->container_end() instead.
907 function print_container_end($return=false) {
908 throw new coding_exception('print_container_end() can not be used any more. Please use $OUTPUT->container_end() instead.');
912 * Print a bold message in an optional color.
914 * @deprecated since Moodle 2.0 MDL-19077 - use $OUTPUT->notification instead.
915 * @todo MDL-50469 This will be deleted in Moodle 3.3.
916 * @param string $message The message to print out
917 * @param string $classes Optional style to display message text in
918 * @param string $align Alignment option
919 * @param bool $return whether to return an output string or echo now
920 * @return string|bool Depending on $result
922 function notify($message, $classes = 'error', $align = 'center', $return = false) {
923 global $OUTPUT;
925 debugging('notify() is deprecated, please use $OUTPUT->notification() instead', DEBUG_DEVELOPER);
927 if ($classes == 'green') {
928 debugging('Use of deprecated class name "green" in notify. Please change to "success".', DEBUG_DEVELOPER);
929 $classes = 'success'; // Backward compatible with old color system.
932 $output = $OUTPUT->notification($message, $classes);
933 if ($return) {
934 return $output;
935 } else {
936 echo $output;
941 * @deprecated use $OUTPUT->continue_button() instead.
943 function print_continue($link, $return = false) {
944 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
948 * @deprecated use $PAGE methods instead.
950 function print_header($title='', $heading='', $navigation='', $focus='',
951 $meta='', $cache=true, $button='&nbsp;', $menu=null,
952 $usexml=false, $bodytags='', $return=false) {
954 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
958 * @deprecated use $PAGE methods instead.
960 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
961 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
963 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
967 * @deprecated use $OUTPUT->block() instead.
969 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
970 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
974 * Prints a basic textarea field.
976 * @deprecated since Moodle 2.0
978 * When using this function, you should
980 * @global object
981 * @param bool $unused No longer used.
982 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
983 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
984 * @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.
985 * @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.
986 * @param string $name Name to use for the textarea element.
987 * @param string $value Initial content to display in the textarea.
988 * @param int $obsolete deprecated
989 * @param bool $return If false, will output string. If true, will return string value.
990 * @param string $id CSS ID to add to the textarea element.
991 * @return string|void depending on the value of $return
993 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
994 /// $width and height are legacy fields and no longer used as pixels like they used to be.
995 /// However, you can set them to zero to override the mincols and minrows values below.
997 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
998 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
1000 global $CFG;
1002 $mincols = 65;
1003 $minrows = 10;
1004 $str = '';
1006 if ($id === '') {
1007 $id = 'edit-'.$name;
1010 if ($height && ($rows < $minrows)) {
1011 $rows = $minrows;
1013 if ($width && ($cols < $mincols)) {
1014 $cols = $mincols;
1017 editors_head_setup();
1018 $editor = editors_get_preferred_editor(FORMAT_HTML);
1019 $editor->set_text($value);
1020 $editor->use_editor($id, array('legacy'=>true));
1022 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
1023 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
1024 $str .= '</textarea>'."\n";
1026 if ($return) {
1027 return $str;
1029 echo $str;
1033 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
1034 * provide this function with the language strings for sortasc and sortdesc.
1036 * @deprecated use $OUTPUT->arrow() instead.
1037 * @todo final deprecation of this function once MDL-45448 is resolved
1039 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
1041 * @global object
1042 * @param string $direction 'up' or 'down'
1043 * @param string $strsort The language string used for the alt attribute of this image
1044 * @param bool $return Whether to print directly or return the html string
1045 * @return string|void depending on $return
1048 function print_arrow($direction='up', $strsort=null, $return=false) {
1049 global $OUTPUT;
1051 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
1053 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
1054 return null;
1057 $return = null;
1059 switch ($direction) {
1060 case 'up':
1061 $sortdir = 'asc';
1062 break;
1063 case 'down':
1064 $sortdir = 'desc';
1065 break;
1066 case 'move':
1067 $sortdir = 'asc';
1068 break;
1069 default:
1070 $sortdir = null;
1071 break;
1074 // Prepare language string
1075 $strsort = '';
1076 if (empty($strsort) && !empty($sortdir)) {
1077 $strsort = get_string('sort' . $sortdir, 'grades');
1080 $return = ' <img src="'.$OUTPUT->pix_url('t/' . $direction) . '" alt="'.$strsort.'" /> ';
1082 if ($return) {
1083 return $return;
1084 } else {
1085 echo $return;
1090 * @deprecated since Moodle 2.0
1092 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1093 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1094 $id='', $listbox=false, $multiple=false, $class='') {
1095 throw new coding_exception('choose_from_menu() is removed. Please change your code to use html_writer::select().');
1100 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1102 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1103 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1104 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1108 * @deprecated use html_writer::checkbox() instead.
1110 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1111 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1115 * Prints the 'update this xxx' button that appears on module pages.
1117 * @deprecated since Moodle 3.2
1119 * @param string $cmid the course_module id.
1120 * @param string $ignored not used any more. (Used to be courseid.)
1121 * @param string $string the module name - get_string('modulename', 'xxx')
1122 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1124 function update_module_button($cmid, $ignored, $string) {
1125 global $CFG, $OUTPUT;
1127 debugging('update_module_button() has been deprecated and should not be used anymore. Activity modules should not add the ' .
1128 'edit module button, the link is already available in the Administration block. Themes can choose to display the link ' .
1129 'in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
1131 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1132 $string = get_string('updatethis', '', $string);
1134 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1135 return $OUTPUT->single_button($url, $string);
1136 } else {
1137 return '';
1142 * @deprecated use $OUTPUT->navbar() instead
1144 function print_navigation ($navigation, $separator=0, $return=false) {
1145 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1149 * @deprecated Please use $PAGE->navabar methods instead.
1151 function build_navigation($extranavlinks, $cm = null) {
1152 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1156 * @deprecated not relevant with global navigation in Moodle 2.x+
1158 function navmenu($course, $cm=NULL, $targetwindow='self') {
1159 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1162 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1166 * @deprecated please use calendar_event::create() instead.
1168 function add_event($event) {
1169 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1173 * @deprecated please calendar_event->update() instead.
1175 function update_event($event) {
1176 throw new coding_exception('update_event() is removed, please use calendar_event->update() instead.');
1180 * @deprecated please use calendar_event->delete() instead.
1182 function delete_event($id) {
1183 throw new coding_exception('delete_event() can not be used any more, please use '.
1184 'calendar_event->delete() instead.');
1188 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1190 function hide_event($event) {
1191 throw new coding_exception('hide_event() can not be used any more, please use '.
1192 'calendar_event->toggle_visibility(false) instead.');
1196 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1198 function show_event($event) {
1199 throw new coding_exception('show_event() can not be used any more, please use '.
1200 'calendar_event->toggle_visibility(true) instead.');
1204 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1205 * @see core_text
1207 function textlib_get_instance() {
1208 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1209 'core_text::functioname() instead.');
1213 * @deprecated since 2.4
1214 * @see get_section_name()
1215 * @see format_base::get_section_name()
1218 function get_generic_section_name($format, stdClass $section) {
1219 throw new coding_exception('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base');
1223 * Returns an array of sections for the requested course id
1225 * It is usually not recommended to display the list of sections used
1226 * in course because the course format may have it's own way to do it.
1228 * If you need to just display the name of the section please call:
1229 * get_section_name($course, $section)
1230 * {@link get_section_name()}
1231 * from 2.4 $section may also be just the field course_sections.section
1233 * If you need the list of all sections it is more efficient to get this data by calling
1234 * $modinfo = get_fast_modinfo($courseorid);
1235 * $sections = $modinfo->get_section_info_all()
1236 * {@link get_fast_modinfo()}
1237 * {@link course_modinfo::get_section_info_all()}
1239 * Information about one section (instance of section_info):
1240 * get_fast_modinfo($courseorid)->get_sections_info($section)
1241 * {@link course_modinfo::get_section_info()}
1243 * @deprecated since 2.4
1245 function get_all_sections($courseid) {
1247 throw new coding_exception('get_all_sections() is removed. See phpdocs for this function');
1251 * This function is deprecated, please use {@link course_add_cm_to_section()}
1252 * Note that course_add_cm_to_section() also updates field course_modules.section and
1253 * calls rebuild_course_cache()
1255 * @deprecated since 2.4
1257 function add_mod_to_section($mod, $beforemod = null) {
1258 throw new coding_exception('Function add_mod_to_section() is removed, please use course_add_cm_to_section()');
1262 * Returns a number of useful structures for course displays
1264 * Function get_all_mods() is deprecated in 2.4
1265 * Instead of:
1266 * <code>
1267 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1268 * </code>
1269 * please use:
1270 * <code>
1271 * $mods = get_fast_modinfo($courseorid)->get_cms();
1272 * $modnames = get_module_types_names();
1273 * $modnamesplural = get_module_types_names(true);
1274 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1275 * </code>
1277 * @deprecated since 2.4
1279 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1280 throw new coding_exception('Function get_all_mods() is removed. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details');
1284 * Returns course section - creates new if does not exist yet
1286 * This function is deprecated. To create a course section call:
1287 * course_create_sections_if_missing($courseorid, $sections);
1288 * to get the section call:
1289 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1291 * @see course_create_sections_if_missing()
1292 * @see get_fast_modinfo()
1293 * @deprecated since 2.4
1295 function get_course_section($section, $courseid) {
1296 throw new coding_exception('Function get_course_section() is removed. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.');
1300 * @deprecated since 2.4
1301 * @see format_weeks::get_section_dates()
1303 function format_weeks_get_section_dates($section, $course) {
1304 throw new coding_exception('Function format_weeks_get_section_dates() is removed. It is not recommended to'.
1305 ' use it outside of format_weeks plugin');
1309 * Deprecated. Instead of:
1310 * list($content, $name) = get_print_section_cm_text($cm, $course);
1311 * use:
1312 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1313 * $name = $cm->get_formatted_name();
1315 * @deprecated since 2.5
1316 * @see cm_info::get_formatted_content()
1317 * @see cm_info::get_formatted_name()
1319 function get_print_section_cm_text(cm_info $cm, $course) {
1320 throw new coding_exception('Function get_print_section_cm_text() is removed. Please use '.
1321 'cm_info::get_formatted_content() and cm_info::get_formatted_name()');
1325 * Deprecated. Please use:
1326 * $courserenderer = $PAGE->get_renderer('core', 'course');
1327 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1328 * array('inblock' => $vertical));
1329 * echo $output;
1331 * @deprecated since 2.5
1332 * @see core_course_renderer::course_section_add_cm_control()
1334 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1335 throw new coding_exception('Function print_section_add_menus() is removed. Please use course renderer '.
1336 'function course_section_add_cm_control()');
1340 * Deprecated. Please use:
1341 * $courserenderer = $PAGE->get_renderer('core', 'course');
1342 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1343 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1345 * @deprecated since 2.5
1346 * @see course_get_cm_edit_actions()
1347 * @see core_course_renderer->course_section_cm_edit_actions()
1349 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1350 throw new coding_exception('Function make_editing_buttons() is removed, please see PHPdocs in '.
1351 'lib/deprecatedlib.php on how to replace it');
1355 * Deprecated. Please use:
1356 * $courserenderer = $PAGE->get_renderer('core', 'course');
1357 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1358 * array('hidecompletion' => $hidecompletion));
1360 * @deprecated since 2.5
1361 * @see core_course_renderer::course_section_cm_list()
1363 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1364 throw new coding_exception('Function print_section() is removed. Please use course renderer function '.
1365 'course_section_cm_list() instead.');
1369 * @deprecated since 2.5
1371 function print_overview($courses, array $remote_courses=array()) {
1372 throw new coding_exception('Function print_overview() is removed. Use block course_overview to display this information');
1376 * @deprecated since 2.5
1378 function print_recent_activity($course) {
1379 throw new coding_exception('Function print_recent_activity() is removed. It is not recommended to'.
1380 ' use it outside of block_recent_activity');
1384 * @deprecated since 2.5
1386 function delete_course_module($id) {
1387 throw new coding_exception('Function delete_course_module() is removed. Please use course_delete_module() instead.');
1391 * @deprecated since 2.5
1393 function update_category_button($categoryid = 0) {
1394 throw new coding_exception('Function update_category_button() is removed. Pages to view '.
1395 'and edit courses are now separate and no longer depend on editing mode.');
1399 * This function is deprecated! For list of categories use
1400 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
1401 * For parents of one particular category use
1402 * coursecat::get($id)->get_parents()
1404 * @deprecated since 2.5
1406 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1407 $excludeid = 0, $category = NULL, $path = "") {
1408 throw new coding_exception('Global function make_categories_list() is removed. Please use '.
1409 'coursecat::make_categories_list() and coursecat::get_parents()');
1413 * @deprecated since 2.5
1415 function category_delete_move($category, $newparentid, $showfeedback=true) {
1416 throw new coding_exception('Function category_delete_move() is removed. Please use coursecat::delete_move() instead.');
1420 * @deprecated since 2.5
1422 function category_delete_full($category, $showfeedback=true) {
1423 throw new coding_exception('Function category_delete_full() is removed. Please use coursecat::delete_full() instead.');
1427 * This function is deprecated. Please use
1428 * $coursecat = coursecat::get($category->id);
1429 * if ($coursecat->can_change_parent($newparentcat->id)) {
1430 * $coursecat->change_parent($newparentcat->id);
1433 * Alternatively you can use
1434 * $coursecat->update(array('parent' => $newparentcat->id));
1436 * @see coursecat::change_parent()
1437 * @see coursecat::update()
1438 * @deprecated since 2.5
1440 function move_category($category, $newparentcat) {
1441 throw new coding_exception('Function move_category() is removed. Please use coursecat::change_parent() instead.');
1445 * This function is deprecated. Please use
1446 * coursecat::get($category->id)->hide();
1448 * @see coursecat::hide()
1449 * @deprecated since 2.5
1451 function course_category_hide($category) {
1452 throw new coding_exception('Function course_category_hide() is removed. Please use coursecat::hide() instead.');
1456 * This function is deprecated. Please use
1457 * coursecat::get($category->id)->show();
1459 * @see coursecat::show()
1460 * @deprecated since 2.5
1462 function course_category_show($category) {
1463 throw new coding_exception('Function course_category_show() is removed. Please use coursecat::show() instead.');
1467 * This function is deprecated.
1468 * To get the category with the specified it please use:
1469 * coursecat::get($catid, IGNORE_MISSING);
1470 * or
1471 * coursecat::get($catid, MUST_EXIST);
1473 * To get the first available category please use
1474 * coursecat::get_default();
1476 * @deprecated since 2.5
1478 function get_course_category($catid=0) {
1479 throw new coding_exception('Function get_course_category() is removed. Please use coursecat::get(), see phpdocs for more details');
1483 * This function is deprecated. It is replaced with the method create() in class coursecat.
1484 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
1486 * @deprecated since 2.5
1488 function create_course_category($category) {
1489 throw new coding_exception('Function create_course_category() is removed. Please use coursecat::create(), see phpdocs for more details');
1493 * This function is deprecated.
1495 * To get visible children categories of the given category use:
1496 * coursecat::get($categoryid)->get_children();
1497 * This function will return the array or coursecat objects, on each of them
1498 * you can call get_children() again
1500 * @see coursecat::get()
1501 * @see coursecat::get_children()
1503 * @deprecated since 2.5
1505 function get_all_subcategories($catid) {
1506 throw new coding_exception('Function get_all_subcategories() is removed. Please use appropriate methods() of coursecat
1507 class. See phpdocs for more details');
1511 * This function is deprecated. Please use functions in class coursecat:
1512 * - coursecat::get($parentid)->has_children()
1513 * tells if the category has children (visible or not to the current user)
1515 * - coursecat::get($parentid)->get_children()
1516 * returns an array of coursecat objects, each of them represents a children category visible
1517 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
1519 * - coursecat::get($parentid)->get_children_count()
1520 * returns number of children categories visible to the current user
1522 * - coursecat::count_all()
1523 * returns total count of all categories in the system (both visible and not)
1525 * - coursecat::get_default()
1526 * returns the first category (usually to be used if count_all() == 1)
1528 * @deprecated since 2.5
1530 function get_child_categories($parentid) {
1531 throw new coding_exception('Function get_child_categories() is removed. Use coursecat::get_children() or see phpdocs for
1532 more details.');
1537 * @deprecated since 2.5
1539 * This function is deprecated. Use appropriate functions from class coursecat.
1540 * Examples:
1542 * coursecat::get($categoryid)->get_children()
1543 * - returns all children of the specified category as instances of class
1544 * coursecat, which means on each of them method get_children() can be called again.
1545 * Only categories visible to the current user are returned.
1547 * coursecat::get(0)->get_children()
1548 * - returns all top-level categories visible to the current user.
1550 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
1552 * coursecat::make_categories_list()
1553 * - returns an array of all categories id/names in the system.
1554 * Also only returns categories visible to current user and can additionally be
1555 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
1557 * make_categories_options()
1558 * - Returns full course categories tree to be used in html_writer::select()
1560 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
1561 * {@link coursecat::get_default()}
1563 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1564 throw new coding_exception('Function get_categories() is removed. Please use coursecat::get_children() or see phpdocs for other alternatives');
1568 * This function is deprecated, please use course renderer:
1569 * $renderer = $PAGE->get_renderer('core', 'course');
1570 * echo $renderer->course_search_form($value, $format);
1572 * @deprecated since 2.5
1574 function print_course_search($value="", $return=false, $format="plain") {
1575 throw new coding_exception('Function print_course_search() is removed, please use course renderer');
1579 * This function is deprecated, please use:
1580 * $renderer = $PAGE->get_renderer('core', 'course');
1581 * echo $renderer->frontpage_my_courses()
1583 * @deprecated since 2.5
1585 function print_my_moodle() {
1586 throw new coding_exception('Function print_my_moodle() is removed, please use course renderer function frontpage_my_courses()');
1590 * This function is deprecated, it is replaced with protected function
1591 * {@link core_course_renderer::frontpage_remote_course()}
1592 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1594 * @deprecated since 2.5
1596 function print_remote_course($course, $width="100%") {
1597 throw new coding_exception('Function print_remote_course() is removed, please use course renderer');
1601 * This function is deprecated, it is replaced with protected function
1602 * {@link core_course_renderer::frontpage_remote_host()}
1603 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1605 * @deprecated since 2.5
1607 function print_remote_host($host, $width="100%") {
1608 throw new coding_exception('Function print_remote_host() is removed, please use course renderer');
1612 * @deprecated since 2.5
1614 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1616 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1617 throw new coding_exception('Function print_whole_category_list() is removed, please use course renderer');
1621 * @deprecated since 2.5
1623 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1624 throw new coding_exception('Function print_category_info() is removed, please use course renderer');
1628 * @deprecated since 2.5
1630 * This function is not used any more in moodle core and course renderer does not have render function for it.
1631 * Combo list on the front page is displayed as:
1632 * $renderer = $PAGE->get_renderer('core', 'course');
1633 * echo $renderer->frontpage_combo_list()
1635 * The new class {@link coursecat} stores the information about course category tree
1636 * To get children categories use:
1637 * coursecat::get($id)->get_children()
1638 * To get list of courses use:
1639 * coursecat::get($id)->get_courses()
1641 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1643 function get_course_category_tree($id = 0, $depth = 0) {
1644 throw new coding_exception('Function get_course_category_tree() is removed, please use course renderer or coursecat class,
1645 see function phpdocs for more info');
1649 * @deprecated since 2.5
1651 * To print a generic list of courses use:
1652 * $renderer = $PAGE->get_renderer('core', 'course');
1653 * echo $renderer->courses_list($courses);
1655 * To print list of all courses:
1656 * $renderer = $PAGE->get_renderer('core', 'course');
1657 * echo $renderer->frontpage_available_courses();
1659 * To print list of courses inside category:
1660 * $renderer = $PAGE->get_renderer('core', 'course');
1661 * echo $renderer->course_category($category); // this will also print subcategories
1663 function print_courses($category) {
1664 throw new coding_exception('Function print_courses() is removed, please use course renderer');
1668 * @deprecated since 2.5
1670 * Please use course renderer to display a course information box.
1671 * $renderer = $PAGE->get_renderer('core', 'course');
1672 * echo $renderer->courses_list($courses); // will print list of courses
1673 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
1675 function print_course($course, $highlightterms = '') {
1676 throw new coding_exception('Function print_course() is removed, please use course renderer');
1680 * @deprecated since 2.5
1682 * This function is not used any more in moodle core and course renderer does not have render function for it.
1683 * Combo list on the front page is displayed as:
1684 * $renderer = $PAGE->get_renderer('core', 'course');
1685 * echo $renderer->frontpage_combo_list()
1687 * The new class {@link coursecat} stores the information about course category tree
1688 * To get children categories use:
1689 * coursecat::get($id)->get_children()
1690 * To get list of courses use:
1691 * coursecat::get($id)->get_courses()
1693 function get_category_courses_array($categoryid = 0) {
1694 throw new coding_exception('Function get_category_courses_array() is removed, please use methods of coursecat class');
1698 * @deprecated since 2.5
1700 function get_category_courses_array_recursively(array &$flattened, $category) {
1701 throw new coding_exception('Function get_category_courses_array_recursively() is removed, please use methods of coursecat class', DEBUG_DEVELOPER);
1705 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
1707 function blog_get_context_url($context=null) {
1708 throw new coding_exception('Function blog_get_context_url() is removed, getting params from context is not reliable for blogs.');
1712 * @deprecated since 2.5
1714 * To get list of all courses with course contacts ('managers') use
1715 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
1717 * To get list of courses inside particular category use
1718 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
1720 * Additionally you can specify sort order, offset and maximum number of courses,
1721 * see {@link coursecat::get_courses()}
1723 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
1724 throw new coding_exception('Function get_courses_wmanagers() is removed, please use coursecat::get_courses()');
1728 * @deprecated since 2.5
1730 function convert_tree_to_html($tree, $row=0) {
1731 throw new coding_exception('Function convert_tree_to_html() is removed. Consider using class tabtree and core_renderer::render_tabtree()');
1735 * @deprecated since 2.5
1737 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
1738 throw new coding_exception('Function convert_tabrows_to_tree() is removed. Consider using class tabtree');
1742 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
1744 function can_use_rotated_text() {
1745 debugging('can_use_rotated_text() is removed. JS feature detection is used automatically.');
1749 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
1750 * @see context::instance_by_id($id)
1752 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
1753 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
1757 * Returns system context or null if can not be created yet.
1759 * @see context_system::instance()
1760 * @deprecated since 2.2
1761 * @param bool $cache use caching
1762 * @return context system context (null if context table not created yet)
1764 function get_system_context($cache = true) {
1765 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
1766 return context_system::instance(0, IGNORE_MISSING, $cache);
1770 * @see context::get_parent_context_ids()
1771 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
1773 function get_parent_contexts(context $context, $includeself = false) {
1774 throw new coding_exception('get_parent_contexts() is removed, please use $context->get_parent_context_ids() instead.');
1778 * @deprecated since Moodle 2.2
1779 * @see context::get_parent_context()
1781 function get_parent_contextid(context $context) {
1782 throw new coding_exception('get_parent_contextid() is removed, please use $context->get_parent_context() instead.');
1786 * @see context::get_child_contexts()
1787 * @deprecated since 2.2
1789 function get_child_contexts(context $context) {
1790 throw new coding_exception('get_child_contexts() is removed, please use $context->get_child_contexts() instead.');
1794 * @see context_helper::create_instances()
1795 * @deprecated since 2.2
1797 function create_contexts($contextlevel = null, $buildpaths = true) {
1798 throw new coding_exception('create_contexts() is removed, please use context_helper::create_instances() instead.');
1802 * @see context_helper::cleanup_instances()
1803 * @deprecated since 2.2
1805 function cleanup_contexts() {
1806 throw new coding_exception('cleanup_contexts() is removed, please use context_helper::cleanup_instances() instead.');
1810 * Populate context.path and context.depth where missing.
1812 * @deprecated since 2.2
1814 function build_context_path($force = false) {
1815 throw new coding_exception('build_context_path() is removed, please use context_helper::build_all_paths() instead.');
1819 * @deprecated since 2.2
1821 function rebuild_contexts(array $fixcontexts) {
1822 throw new coding_exception('rebuild_contexts() is removed, please use $context->reset_paths(true) instead.');
1826 * @deprecated since Moodle 2.2
1827 * @see context_helper::preload_course()
1829 function preload_course_contexts($courseid) {
1830 throw new coding_exception('preload_course_contexts() is removed, please use context_helper::preload_course() instead.');
1834 * @deprecated since Moodle 2.2
1835 * @see context::update_moved()
1837 function context_moved(context $context, context $newparent) {
1838 throw new coding_exception('context_moved() is removed, please use context::update_moved() instead.');
1842 * @see context::get_capabilities()
1843 * @deprecated since 2.2
1845 function fetch_context_capabilities(context $context) {
1846 throw new coding_exception('fetch_context_capabilities() is removed, please use $context->get_capabilities() instead.');
1850 * @deprecated since 2.2
1851 * @see context_helper::preload_from_record()
1853 function context_instance_preload(stdClass $rec) {
1854 throw new coding_exception('context_instance_preload() is removed, please use context_helper::preload_from_record() instead.');
1858 * Returns context level name
1860 * @deprecated since 2.2
1861 * @see context_helper::get_level_name()
1863 function get_contextlevel_name($contextlevel) {
1864 throw new coding_exception('get_contextlevel_name() is removed, please use context_helper::get_level_name() instead.');
1868 * @deprecated since 2.2
1869 * @see context::get_context_name()
1871 function print_context_name(context $context, $withprefix = true, $short = false) {
1872 throw new coding_exception('print_context_name() is removed, please use $context->get_context_name() instead.');
1876 * @deprecated since 2.2, use $context->mark_dirty() instead
1877 * @see context::mark_dirty()
1879 function mark_context_dirty($path) {
1880 throw new coding_exception('mark_context_dirty() is removed, please use $context->mark_dirty() instead.');
1884 * @deprecated since Moodle 2.2
1885 * @see context_helper::delete_instance() or context::delete_content()
1887 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1888 if ($deleterecord) {
1889 throw new coding_exception('delete_context() is removed, please use context_helper::delete_instance() instead.');
1890 } else {
1891 throw new coding_exception('delete_context() is removed, please use $context->delete_content() instead.');
1896 * @deprecated since 2.2
1897 * @see context::get_url()
1899 function get_context_url(context $context) {
1900 throw new coding_exception('get_context_url() is removed, please use $context->get_url() instead.');
1904 * @deprecated since 2.2
1905 * @see context::get_course_context()
1907 function get_course_context(context $context) {
1908 throw new coding_exception('get_course_context() is removed, please use $context->get_course_context(true) instead.');
1912 * @deprecated since 2.2
1913 * @see enrol_get_users_courses()
1915 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1917 throw new coding_exception('get_user_courses_bycap() is removed, please use enrol_get_users_courses() instead.');
1921 * @deprecated since Moodle 2.2
1923 function get_role_context_caps($roleid, context $context) {
1924 throw new coding_exception('get_role_context_caps() is removed, it is really slow. Don\'t use it.');
1928 * @see context::get_course_context()
1929 * @deprecated since 2.2
1931 function get_courseid_from_context(context $context) {
1932 throw new coding_exception('get_courseid_from_context() is removed, please use $context->get_course_context(false) instead.');
1936 * If you are using this methid, you should have something like this:
1938 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1940 * To prevent the use of this deprecated function, replace the line above with something similar to this:
1942 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1944 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1945 * ^ ^ ^ ^
1946 * $params = array('contextlevel' => CONTEXT_COURSE);
1948 * @see context_helper:;get_preload_record_columns_sql()
1949 * @deprecated since 2.2
1951 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
1952 throw new coding_exception('context_instance_preload_sql() is removed, please use context_helper::get_preload_record_columns_sql() instead.');
1956 * @deprecated since 2.2
1957 * @see context::get_parent_context_ids()
1959 function get_related_contexts_string(context $context) {
1960 throw new coding_exception('get_related_contexts_string() is removed, please use $context->get_parent_context_ids(true) instead.');
1964 * @deprecated since 2.6
1965 * @see core_component::get_plugin_list_with_file()
1967 function get_plugin_list_with_file($plugintype, $file, $include = false) {
1968 throw new coding_exception('get_plugin_list_with_file() is removed, please use core_component::get_plugin_list_with_file() instead.');
1972 * @deprecated since 2.6
1974 function check_browser_operating_system($brand) {
1975 throw new coding_exception('check_browser_operating_system is removed, please update your code to use core_useragent instead.');
1979 * @deprecated since 2.6
1981 function check_browser_version($brand, $version = null) {
1982 throw new coding_exception('check_browser_version is removed, please update your code to use core_useragent instead.');
1986 * @deprecated since 2.6
1988 function get_device_type() {
1989 throw new coding_exception('get_device_type is removed, please update your code to use core_useragent instead.');
1993 * @deprecated since 2.6
1995 function get_device_type_list($incusertypes = true) {
1996 throw new coding_exception('get_device_type_list is removed, please update your code to use core_useragent instead.');
2000 * @deprecated since 2.6
2002 function get_selected_theme_for_device_type($devicetype = null) {
2003 throw new coding_exception('get_selected_theme_for_device_type is removed, please update your code to use core_useragent instead.');
2007 * @deprecated since 2.6
2009 function get_device_cfg_var_name($devicetype = null) {
2010 throw new coding_exception('get_device_cfg_var_name is removed, please update your code to use core_useragent instead.');
2014 * @deprecated since 2.6
2016 function set_user_device_type($newdevice) {
2017 throw new coding_exception('set_user_device_type is removed, please update your code to use core_useragent instead.');
2021 * @deprecated since 2.6
2023 function get_user_device_type() {
2024 throw new coding_exception('get_user_device_type is removed, please update your code to use core_useragent instead.');
2028 * @deprecated since 2.6
2030 function get_browser_version_classes() {
2031 throw new coding_exception('get_browser_version_classes is removed, please update your code to use core_useragent instead.');
2035 * @deprecated since Moodle 2.6
2036 * @see core_user::get_support_user()
2038 function generate_email_supportuser() {
2039 throw new coding_exception('generate_email_supportuser is removed, please use core_user::get_support_user');
2043 * @deprecated since Moodle 2.6
2045 function badges_get_issued_badge_info($hash) {
2046 throw new coding_exception('Function badges_get_issued_badge_info() is removed. Please use core_badges_assertion class and methods to generate badge assertion.');
2050 * @deprecated since 2.6
2052 function can_use_html_editor() {
2053 throw new coding_exception('can_use_html_editor is removed, please update your code to assume it returns true.');
2058 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
2060 function count_login_failures($mode, $username, $lastlogin) {
2061 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
2065 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
2067 function ajaxenabled(array $browsers = null) {
2068 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
2072 * @deprecated Since Moodle 2.7 MDL-44070
2074 function coursemodule_visible_for_user($cm, $userid=0) {
2075 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
2076 please use \core_availability\info_module::is_user_visible()');
2080 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
2082 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
2083 throw new coding_exception('Function enrol_cohort_get_cohorts() is removed, use enrol_cohort_search_cohorts() or '.
2084 'cohort_get_available_cohorts() instead');
2088 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
2089 * takes into account current context
2091 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
2093 function enrol_cohort_can_view_cohort($cohortid) {
2094 throw new coding_exception('Function enrol_cohort_can_view_cohort() is removed, use cohort_can_view_cohort() instead');
2098 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
2100 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
2102 function cohort_get_visible_list($course, $onlyenrolled=true) {
2103 throw new coding_exception('Function cohort_get_visible_list() is removed. Please use function cohort_get_available_cohorts() ".
2104 "that correctly checks capabilities.');
2108 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2110 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
2111 throw new coding_exception('enrol_cohort_enrol_all_users() is removed. This functionality is moved to enrol_manual.');
2115 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2117 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
2118 throw new coding_exception('enrol_cohort_search_cohorts() is removed. This functionality is moved to enrol_manual.');
2121 /* === Apis deprecated in since Moodle 2.9 === */
2124 * Is $USER one of the supplied users?
2126 * $user2 will be null if viewing a user's recent conversations
2128 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
2130 function message_current_user_is_involved($user1, $user2) {
2131 throw new coding_exception('message_current_user_is_involved() can not be used any more.');
2135 * Print badges on user profile page.
2137 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
2139 function profile_display_badges($userid, $courseid = 0) {
2140 throw new coding_exception('profile_display_badges() can not be used any more.');
2144 * Adds user preferences elements to user edit form.
2146 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
2148 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
2149 throw new coding_exception('useredit_shared_definition_preferences() can not be used any more.');
2154 * Convert region timezone to php supported timezone
2156 * @deprecated since Moodle 2.9
2158 function calendar_normalize_tz($tz) {
2159 throw new coding_exception('calendar_normalize_tz() can not be used any more, please use core_date::normalise_timezone() instead.');
2163 * Returns a float which represents the user's timezone difference from GMT in hours
2164 * Checks various settings and picks the most dominant of those which have a value
2165 * @deprecated since Moodle 2.9
2167 function get_user_timezone_offset($tz = 99) {
2168 throw new coding_exception('get_user_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2173 * Returns an int which represents the systems's timezone difference from GMT in seconds
2174 * @deprecated since Moodle 2.9
2176 function get_timezone_offset($tz) {
2177 throw new coding_exception('get_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2181 * Returns a list of timezones in the current language.
2182 * @deprecated since Moodle 2.9
2184 function get_list_of_timezones() {
2185 throw new coding_exception('get_list_of_timezones() can not be used any more, please use core_date::get_list_of_timezones() instead');
2189 * Previous internal API, it was not supposed to be used anywhere.
2190 * @deprecated since Moodle 2.9
2192 function update_timezone_records($timezones) {
2193 throw new coding_exception('update_timezone_records() can not be used any more, please use standard PHP DateTime class instead');
2197 * Previous internal API, it was not supposed to be used anywhere.
2198 * @deprecated since Moodle 2.9
2200 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2201 throw new coding_exception('calculate_user_dst_table() can not be used any more, please use standard PHP DateTime class instead');
2205 * Previous internal API, it was not supposed to be used anywhere.
2206 * @deprecated since Moodle 2.9
2208 function dst_changes_for_year($year, $timezone) {
2209 throw new coding_exception('dst_changes_for_year() can not be used any more, please use standard DateTime class instead');
2213 * Previous internal API, it was not supposed to be used anywhere.
2214 * @deprecated since Moodle 2.9
2216 function get_timezone_record($timezonename) {
2217 throw new coding_exception('get_timezone_record() can not be used any more, please use standard PHP DateTime class instead');
2220 /* === Apis deprecated since Moodle 3.0 === */
2222 * Returns the URL of the HTTP_REFERER, less the querystring portion if required.
2224 * @deprecated since Moodle 3.0 MDL-49360 - please do not use this function any more.
2225 * @todo MDL-50265 Remove this function in Moodle 3.4.
2226 * @param boolean $stripquery if true, also removes the query part of the url.
2227 * @return string The resulting referer or empty string.
2229 function get_referer($stripquery = true) {
2230 debugging('get_referer() is deprecated. Please use get_local_referer() instead.', DEBUG_DEVELOPER);
2231 if (isset($_SERVER['HTTP_REFERER'])) {
2232 if ($stripquery) {
2233 return strip_querystring($_SERVER['HTTP_REFERER']);
2234 } else {
2235 return $_SERVER['HTTP_REFERER'];
2237 } else {
2238 return '';
2243 * Checks if current user is a web crawler.
2245 * This list can not be made complete, this is not a security
2246 * restriction, we make the list only to help these sites
2247 * especially when automatic guest login is disabled.
2249 * If admin needs security they should enable forcelogin
2250 * and disable guest access!!
2252 * @return bool
2253 * @deprecated since Moodle 3.0 use \core_useragent::is_web_crawler instead.
2255 function is_web_crawler() {
2256 debugging('is_web_crawler() has been deprecated, please use core_useragent::is_web_crawler() instead.', DEBUG_DEVELOPER);
2257 return core_useragent::is_web_crawler();
2261 * Update user's course completion statuses
2263 * First update all criteria completions, then aggregate all criteria completions
2264 * and update overall course completions.
2266 * @deprecated since Moodle 3.0 MDL-50287 - please do not use this function any more.
2267 * @todo Remove this function in Moodle 3.2 MDL-51226.
2269 function completion_cron() {
2270 global $CFG;
2271 require_once($CFG->dirroot.'/completion/cron.php');
2273 debugging('completion_cron() is deprecated. Functionality has been moved to scheduled tasks.', DEBUG_DEVELOPER);
2274 completion_cron_mark_started();
2276 completion_cron_criteria();
2278 completion_cron_completions();
2282 * Returns an ordered array of tags associated with visible courses
2283 * (boosted replacement of get_all_tags() allowing association with user and tagtype).
2285 * @deprecated since 3.0
2286 * @package core_tag
2287 * @category tag
2288 * @param int $courseid A course id. Passing 0 will return all distinct tags for all visible courses
2289 * @param int $userid (optional) the user id, a default of 0 will return all users tags for the course
2290 * @param string $tagtype (optional) The type of tag, empty string returns all types. Currently (Moodle 2.2) there are two
2291 * types of tags which are used within Moodle, they are 'official' and 'default'.
2292 * @param int $numtags (optional) number of tags to display, default of 80 is set in the block, 0 returns all
2293 * @param string $unused (optional) was selected sorting, moved to tag_print_cloud()
2294 * @return array
2296 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $unused = '') {
2297 debugging('Function coursetag_get_tags() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2299 global $CFG, $DB;
2301 // get visible course ids
2302 $courselist = array();
2303 if ($courseid === 0) {
2304 if ($courses = $DB->get_records_select('course', 'visible=1 AND category>0', null, '', 'id')) {
2305 foreach ($courses as $key => $value) {
2306 $courselist[] = $key;
2311 // get tags from the db ordered by highest count first
2312 $params = array();
2313 $sql = "SELECT id as tkey, name, id, isstandard, rawname, f.timemodified, flag, count
2314 FROM {tag} t,
2315 (SELECT tagid, MAX(timemodified) as timemodified, COUNT(id) as count
2316 FROM {tag_instance}
2317 WHERE itemtype = 'course' ";
2319 if ($courseid > 0) {
2320 $sql .= " AND itemid = :courseid ";
2321 $params['courseid'] = $courseid;
2322 } else {
2323 if (!empty($courselist)) {
2324 list($usql, $uparams) = $DB->get_in_or_equal($courselist, SQL_PARAMS_NAMED);
2325 $sql .= "AND itemid $usql ";
2326 $params = $params + $uparams;
2330 if ($userid > 0) {
2331 $sql .= " AND tiuserid = :userid ";
2332 $params['userid'] = $userid;
2335 $sql .= " GROUP BY tagid) f
2336 WHERE t.id = f.tagid ";
2337 if ($tagtype != '') {
2338 $sql .= "AND isstandard = :isstandard ";
2339 $params['isstandard'] = ($tagtype === 'official') ? 1 : 0;
2341 $sql .= "ORDER BY count DESC, name ASC";
2343 // limit the number of tags for output
2344 if ($numtags == 0) {
2345 $tags = $DB->get_records_sql($sql, $params);
2346 } else {
2347 $tags = $DB->get_records_sql($sql, $params, 0, $numtags);
2350 // prepare the return
2351 $return = array();
2352 if ($tags) {
2353 // avoid print_tag_cloud()'s ksort upsetting ordering by setting the key here
2354 foreach ($tags as $value) {
2355 $return[] = $value;
2359 return $return;
2364 * Returns an ordered array of tags
2365 * (replaces popular_tags_count() allowing sorting).
2367 * @deprecated since 3.0
2368 * @package core_tag
2369 * @category tag
2370 * @param string $unused (optional) was selected sorting - moved to tag_print_cloud()
2371 * @param int $numtags (optional) number of tags to display, default of 20 is set in the block, 0 returns all
2372 * @return array
2374 function coursetag_get_all_tags($unused='', $numtags=0) {
2375 debugging('Function coursetag_get_all_tag() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2377 global $CFG, $DB;
2379 // note that this selects all tags except for courses that are not visible
2380 $sql = "SELECT id, name, isstandard, rawname, f.timemodified, flag, count
2381 FROM {tag} t,
2382 (SELECT tagid, MAX(timemodified) as timemodified, COUNT(id) as count
2383 FROM {tag_instance} WHERE tagid NOT IN
2384 (SELECT tagid FROM {tag_instance} ti, {course} c
2385 WHERE c.visible = 0
2386 AND ti.itemtype = 'course'
2387 AND ti.itemid = c.id)
2388 GROUP BY tagid) f
2389 WHERE t.id = f.tagid
2390 ORDER BY count DESC, name ASC";
2391 if ($numtags == 0) {
2392 $tags = $DB->get_records_sql($sql);
2393 } else {
2394 $tags = $DB->get_records_sql($sql, null, 0, $numtags);
2397 $return = array();
2398 if ($tags) {
2399 foreach ($tags as $value) {
2400 $return[] = $value;
2404 return $return;
2408 * Returns javascript for use in tags block and supporting pages
2410 * @deprecated since 3.0
2411 * @package core_tag
2412 * @category tag
2413 * @return null
2415 function coursetag_get_jscript() {
2416 debugging('Function coursetag_get_jscript() is deprecated and obsolete.', DEBUG_DEVELOPER);
2417 return '';
2421 * Returns javascript to create the links in the tag block footer.
2423 * @deprecated since 3.0
2424 * @package core_tag
2425 * @category tag
2426 * @param string $elementid the element to attach the footer to
2427 * @param array $coursetagslinks links arrays each consisting of 'title', 'onclick' and 'text' elements
2428 * @return string always returns a blank string
2430 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
2431 debugging('Function coursetag_get_jscript_links() is deprecated and obsolete.', DEBUG_DEVELOPER);
2432 return '';
2436 * Returns all tags created by a user for a course
2438 * @deprecated since 3.0
2439 * @package core_tag
2440 * @category tag
2441 * @param int $courseid tags are returned for the course that has this courseid
2442 * @param int $userid return tags which were created by this user
2444 function coursetag_get_records($courseid, $userid) {
2445 debugging('Function coursetag_get_records() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2447 global $CFG, $DB;
2449 $sql = "SELECT t.id, name, rawname
2450 FROM {tag} t, {tag_instance} ti
2451 WHERE t.id = ti.tagid
2452 AND ti.tiuserid = :userid
2453 AND ti.itemid = :courseid
2454 ORDER BY name ASC";
2456 return $DB->get_records_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid));
2460 * Stores a tag for a course for a user
2462 * @deprecated since 3.0
2463 * @package core_tag
2464 * @category tag
2465 * @param array $tags simple array of keywords to be stored
2466 * @param int $courseid the id of the course we wish to store a tag for
2467 * @param int $userid the id of the user we wish to store a tag for
2468 * @param string $tagtype official or default only
2469 * @param string $myurl (optional) for logging creation of course tags
2471 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
2472 debugging('Function coursetag_store_keywords() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2474 global $CFG;
2476 if (is_array($tags) and !empty($tags)) {
2477 if ($tagtype === 'official') {
2478 $tagcoll = core_tag_area::get_collection('core', 'course');
2479 // We don't normally need to create tags, they are created automatically when added to items. but we do here because we want them to be official.
2480 core_tag_tag::create_if_missing($tagcoll, $tags, true);
2482 foreach ($tags as $tag) {
2483 $tag = trim($tag);
2484 if (strlen($tag) > 0) {
2485 core_tag_tag::add_item_tag('core', 'course', $courseid, context_course::instance($courseid), $tag, $userid);
2493 * Deletes a personal tag for a user for a course.
2495 * @deprecated since 3.0
2496 * @package core_tag
2497 * @category tag
2498 * @param int $tagid the tag we wish to delete
2499 * @param int $userid the user that the tag is associated with
2500 * @param int $courseid the course that the tag is associated with
2502 function coursetag_delete_keyword($tagid, $userid, $courseid) {
2503 debugging('Function coursetag_delete_keyword() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2505 $tag = core_tag_tag::get($tagid);
2506 core_tag_tag::remove_item_tag('core', 'course', $courseid, $tag->rawname, $userid);
2510 * Get courses tagged with a tag
2512 * @deprecated since 3.0
2513 * @package core_tag
2514 * @category tag
2515 * @param int $tagid
2516 * @return array of course objects
2518 function coursetag_get_tagged_courses($tagid) {
2519 debugging('Function coursetag_get_tagged_courses() is deprecated. Userid is no longer used for tagging courses.', DEBUG_DEVELOPER);
2521 global $DB;
2523 $courses = array();
2525 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2527 $sql = "SELECT c.*, $ctxselect
2528 FROM {course} c
2529 JOIN {tag_instance} t ON t.itemid = c.id
2530 JOIN {context} ctx ON ctx.instanceid = c.id
2531 WHERE t.tagid = :tagid AND
2532 t.itemtype = 'course' AND
2533 ctx.contextlevel = :contextlevel
2534 ORDER BY c.sortorder ASC";
2535 $params = array('tagid' => $tagid, 'contextlevel' => CONTEXT_COURSE);
2536 $rs = $DB->get_recordset_sql($sql, $params);
2537 foreach ($rs as $course) {
2538 context_helper::preload_from_record($course);
2539 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2540 $courses[$course->id] = $course;
2543 return $courses;
2547 * Course tagging function used only during the deletion of a course (called by lib/moodlelib.php) to clean up associated tags
2549 * @package core_tag
2550 * @deprecated since 3.0
2551 * @param int $courseid the course we wish to delete tag instances from
2552 * @param bool $showfeedback if we should output a notification of the delete to the end user
2554 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
2555 debugging('Function coursetag_delete_course_tags() is deprecated. Use core_tag_tag::remove_all_item_tags().', DEBUG_DEVELOPER);
2557 global $OUTPUT;
2558 core_tag_tag::remove_all_item_tags('core', 'course', $courseid);
2560 if ($showfeedback) {
2561 echo $OUTPUT->notification(get_string('deletedcoursetags', 'tag'), 'notifysuccess');
2566 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
2567 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
2569 * @package core_tag
2570 * @deprecated since 3.1
2571 * @param string $tagid tagid to modify
2572 * @param string $type either 'default' or 'official'
2573 * @return bool true on success, false otherwise
2575 function tag_type_set($tagid, $type) {
2576 debugging('Function tag_type_set() is deprecated and can be replaced with use core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2577 if ($tag = core_tag_tag::get($tagid, '*')) {
2578 return $tag->update(array('isstandard' => ($type === 'official') ? 1 : 0));
2580 return false;
2584 * Set the description of a tag
2586 * @package core_tag
2587 * @deprecated since 3.1
2588 * @param int $tagid the id of the tag
2589 * @param string $description the tag's description string to be set
2590 * @param int $descriptionformat the moodle text format of the description
2591 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
2592 * @return bool true on success, false otherwise
2594 function tag_description_set($tagid, $description, $descriptionformat) {
2595 debugging('Function tag_type_set() is deprecated and can be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2596 if ($tag = core_tag_tag::get($tagid, '*')) {
2597 return $tag->update(array('description' => $description, 'descriptionformat' => $descriptionformat));
2599 return false;
2603 * Get the array of db record of tags associated to a record (instances).
2605 * @package core_tag
2606 * @deprecated since 3.1
2607 * @param string $record_type the record type for which we want to get the tags
2608 * @param int $record_id the record id for which we want to get the tags
2609 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2610 * @param int $userid (optional) only required for course tagging
2611 * @return array the array of tags
2613 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
2614 debugging('Method tag_get_tags() is deprecated and replaced with core_tag_tag::get_item_tags(). ' .
2615 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2616 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2617 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2618 $tags = core_tag_tag::get_item_tags(null, $record_type, $record_id, $standardonly, $userid);
2619 $rv = array();
2620 foreach ($tags as $id => $t) {
2621 $rv[$id] = $t->to_object();
2623 return $rv;
2627 * Get the array of tags display names, indexed by id.
2629 * @package core_tag
2630 * @deprecated since 3.1
2631 * @param string $record_type the record type for which we want to get the tags
2632 * @param int $record_id the record id for which we want to get the tags
2633 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2634 * @return array the array of tags (with the value returned by core_tag_tag::make_display_name), indexed by id
2636 function tag_get_tags_array($record_type, $record_id, $type=null) {
2637 debugging('Method tag_get_tags_array() is deprecated and replaced with core_tag_tag::get_item_tags_array(). ' .
2638 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2639 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2640 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2641 return core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly);
2645 * Get a comma-separated string of tags associated to a record.
2647 * Use {@link tag_get_tags()} to get the same information in an array.
2649 * @package core_tag
2650 * @deprecated since 3.1
2651 * @param string $record_type the record type for which we want to get the tags
2652 * @param int $record_id the record id for which we want to get the tags
2653 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
2654 * @param string $type either 'official' or 'default', if null, all tags are returned
2655 * @return string the comma-separated list of tags.
2657 function tag_get_tags_csv($record_type, $record_id, $html=null, $type=null) {
2658 global $CFG, $OUTPUT;
2659 debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' .
2660 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' .
2661 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2662 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2663 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2664 if ($html != TAG_RETURN_TEXT) {
2665 return $OUTPUT->tag_list(core_tag_tag::get_item_tags('', $record_type, $record_id, $standardonly), '');
2666 } else {
2667 return join(', ', core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false));
2672 * Get an array of tag ids associated to a record.
2674 * @package core_tag
2675 * @deprecated since 3.1
2676 * @param string $record_type the record type for which we want to get the tags
2677 * @param int $record_id the record id for which we want to get the tags
2678 * @return array tag ids, indexed and sorted by 'ordering'
2680 function tag_get_tags_ids($record_type, $record_id) {
2681 debugging('Method tag_get_tags_ids() is deprecated. Please consider using core_tag_tag::get_item_tags() or similar methods.', DEBUG_DEVELOPER);
2682 $tag_ids = array();
2683 $tagobjects = core_tag_tag::get_item_tags(null, $record_type, $record_id);
2684 foreach ($tagobjects as $tagobject) {
2685 $tag = $tagobject->to_object();
2686 if ( array_key_exists($tag->ordering, $tag_ids) ) {
2687 $tag->ordering++;
2689 $tag_ids[$tag->ordering] = $tag->id;
2691 ksort($tag_ids);
2692 return $tag_ids;
2696 * Returns the database ID of a set of tags.
2698 * @deprecated since 3.1
2699 * @param mixed $tags one tag, or array of tags, to look for.
2700 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
2701 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
2702 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
2703 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
2705 function tag_get_id($tags, $return_value = null) {
2706 global $CFG, $DB;
2707 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(). ' .
2708 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2710 if (!is_array($tags)) {
2711 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
2712 if ($tagobject = core_tag_tag::get_by_name(core_tag_collection::get_default(), $tags)) {
2713 return $tagobject->id;
2714 } else {
2715 return 0;
2718 $tags = array($tags);
2721 $records = core_tag_tag::get_by_name_bulk(core_tag_collection::get_default(), $tags,
2722 $return_value == TAG_RETURN_OBJECT ? '*' : 'id, name');
2723 foreach ($records as $name => $record) {
2724 if ($return_value != TAG_RETURN_OBJECT) {
2725 $records[$name] = $record->id ? $record->id : null;
2726 } else {
2727 $records[$name] = $record->to_object();
2730 return $records;
2734 * Change the "value" of a tag, and update the associated 'name'.
2736 * @package core_tag
2737 * @deprecated since 3.1
2738 * @param int $tagid the id of the tag to modify
2739 * @param string $newrawname the new rawname
2740 * @return bool true on success, false otherwise
2742 function tag_rename($tagid, $newrawname) {
2743 debugging('Function tag_rename() is deprecated and may be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2744 if ($tag = core_tag_tag::get($tagid, '*')) {
2745 return $tag->update(array('rawname' => $newrawname));
2747 return false;
2751 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
2753 * @package core_tag
2754 * @deprecated since 3.1
2755 * @param string $record_type the type of the record for which to remove the instance
2756 * @param int $record_id the id of the record for which to remove the instance
2757 * @param int $tagid the tagid that needs to be removed
2758 * @param int $userid (optional) the userid
2759 * @return bool true on success, false otherwise
2761 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
2762 debugging('Function tag_delete_instance() is deprecated and replaced with core_tag_tag::remove_item_tag() instead. ' .
2763 'Component is required for retrieving instances', DEBUG_DEVELOPER);
2764 $tag = core_tag_tag::get($tagid);
2765 core_tag_tag::remove_item_tag('', $record_type, $record_id, $tag->rawname, $userid);
2769 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
2771 * @package core_tag
2772 * @deprecated since 3.1
2773 * @category tag
2774 * @param string $tag tag to look for
2775 * @param string $type type to restrict search to. If null, every matching record will be returned
2776 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
2777 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
2778 * @return array of matching objects, indexed by record id, from the table containing the type requested
2780 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
2781 debugging('Function tag_find_records() is deprecated and replaced with core_tag_tag::get_by_name()->get_tagged_items(). '.
2782 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2784 if (!$tag || !$type) {
2785 return array();
2788 $tagobject = core_tag_tag::get_by_name(core_tag_area::get_collection('', $type), $tag);
2789 return $tagobject->get_tagged_items('', $type, $limitfrom, $limitnum);
2793 * Adds one or more tag in the database. This function should not be called directly : you should
2794 * use tag_set.
2796 * @package core_tag
2797 * @deprecated since 3.1
2798 * @param mixed $tags one tag, or an array of tags, to be created
2799 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
2800 * value at this time). An official tag is kept even if there are no records tagged with it.
2801 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
2802 * adding the tag.
2804 function tag_add($tags, $type="default") {
2805 debugging('Function tag_add() is deprecated. You can use core_tag_tag::create_if_missing(), however it should not be necessary ' .
2806 'since tags are created automatically when assigned to items', DEBUG_DEVELOPER);
2807 if (!is_array($tags)) {
2808 $tags = array($tags);
2810 $objects = core_tag_tag::create_if_missing(core_tag_collection::get_default(), $tags,
2811 $type === 'official');
2813 // New function returns the tags in different format, for BC we keep the format that this function used to have.
2814 $rv = array();
2815 foreach ($objects as $name => $tagobject) {
2816 if (isset($tagobject->id)) {
2817 $rv[$tagobject->name] = $tagobject->id;
2818 } else {
2819 $rv[$name] = false;
2822 return $rv;
2826 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
2828 * @package core_tag
2829 * @deprecated since 3.1
2830 * @param string $record_type the type of the record that will be tagged
2831 * @param int $record_id the id of the record that will be tagged
2832 * @param string $tagid the tag id to set on the record.
2833 * @param int $ordering the order of the instance for this record
2834 * @param int $userid (optional) only required for course tagging
2835 * @param string|null $component the component that was tagged
2836 * @param int|null $contextid the context id of where this tag was assigned
2837 * @return bool true on success, false otherwise
2839 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
2840 global $DB;
2841 $message = 'Function tag_assign() is deprecated. Use core_tag_tag::set_item_tags() or core_tag_tag::add_item_tag() instead. ' .
2842 'Tag instance ordering should not be set manually';
2843 if ($component === null || $contextid === null) {
2844 $message .= '. You should specify the component and contextid of the item being tagged in your call to tag_assign.';
2846 debugging($message, DEBUG_DEVELOPER);
2848 if ($contextid) {
2849 $context = context::instance_by_id($contextid);
2850 } else {
2851 $context = context_system::instance();
2854 // Get the tag.
2855 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
2857 $taginstanceid = core_tag_tag::add_item_tag($component, $record_type, $record_id, $context, $tag->rawname, $userid);
2859 // Alter the "ordering" of tag_instance. This should never be done manually and only remains here for the backward compatibility.
2860 $taginstance = new stdClass();
2861 $taginstance->id = $taginstanceid;
2862 $taginstance->ordering = $ordering;
2863 $taginstance->timemodified = time();
2865 $DB->update_record('tag_instance', $taginstance);
2867 return true;
2871 * Count how many records are tagged with a specific tag.
2873 * @package core_tag
2874 * @deprecated since 3.1
2875 * @param string $record_type record to look for ('post', 'user', etc.)
2876 * @param int $tagid is a single tag id
2877 * @return int number of mathing tags.
2879 function tag_record_count($record_type, $tagid) {
2880 debugging('Method tag_record_count() is deprecated and replaced with core_tag_tag::get($tagid)->count_tagged_items(). '.
2881 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2882 return core_tag_tag::get($tagid)->count_tagged_items('', $record_type);
2886 * Determine if a record is tagged with a specific tag
2888 * @package core_tag
2889 * @deprecated since 3.1
2890 * @param string $record_type the record type to look for
2891 * @param int $record_id the record id to look for
2892 * @param string $tag a tag name
2893 * @return bool/int true if it is tagged, 0 (false) otherwise
2895 function tag_record_tagged_with($record_type, $record_id, $tag) {
2896 debugging('Method tag_record_tagged_with() is deprecated and replaced with core_tag_tag::get($tagid)->is_item_tagged_with(). '.
2897 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2898 return core_tag_tag::is_item_tagged_with('', $record_type, $record_id, $tag);
2902 * Flag a tag as inappropriate.
2904 * @deprecated since 3.1
2905 * @param int|array $tagids a single tagid, or an array of tagids
2907 function tag_set_flag($tagids) {
2908 debugging('Function tag_set_flag() is deprecated and replaced with core_tag_tag::get($tagid)->flag().', DEBUG_DEVELOPER);
2909 $tagids = (array) $tagids;
2910 foreach ($tagids as $tagid) {
2911 if ($tag = core_tag_tag::get($tagid, '*')) {
2912 $tag->flag();
2918 * Remove the inappropriate flag on a tag.
2920 * @deprecated since 3.1
2921 * @param int|array $tagids a single tagid, or an array of tagids
2923 function tag_unset_flag($tagids) {
2924 debugging('Function tag_unset_flag() is deprecated and replaced with core_tag_tag::get($tagid)->reset_flag().', DEBUG_DEVELOPER);
2925 $tagids = (array) $tagids;
2926 foreach ($tagids as $tagid) {
2927 if ($tag = core_tag_tag::get($tagid, '*')) {
2928 $tag->reset_flag();
2934 * Prints or returns a HTML tag cloud with varying classes styles depending on the popularity and type of each tag.
2936 * @deprecated since 3.1
2938 * @param array $tagset Array of tags to display
2939 * @param int $nr_of_tags Limit for the number of tags to return/display, used if $tagset is null
2940 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2941 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
2942 * @return string|null a HTML string or null if this function does the output
2944 function tag_print_cloud($tagset=null, $nr_of_tags=150, $return=false, $sort='') {
2945 global $OUTPUT;
2947 debugging('Function tag_print_cloud() is deprecated and replaced with function core_tag_collection::get_tag_cloud(), '
2948 . 'templateable core_tag\output\tagcloud and template core_tag/tagcloud.', DEBUG_DEVELOPER);
2950 // Set up sort global - used to pass sort type into core_tag_collection::cloud_sort through usort() avoiding multiple sort functions.
2951 if ($sort == 'popularity') {
2952 $sort = 'count';
2953 } else if ($sort == 'date') {
2954 $sort = 'timemodified';
2955 } else {
2956 $sort = 'name';
2959 if (is_null($tagset)) {
2960 // No tag set received, so fetch tags from database.
2961 // Always add query by tagcollid even when it's not known to make use of the table index.
2962 $tagcloud = core_tag_collection::get_tag_cloud(0, false, $nr_of_tags, $sort);
2963 } else {
2964 $tagsincloud = $tagset;
2966 $etags = array();
2967 foreach ($tagsincloud as $tag) {
2968 $etags[] = $tag;
2971 core_tag_collection::$cloudsortfield = $sort;
2972 usort($tagsincloud, "core_tag_collection::cloud_sort");
2974 $tagcloud = new \core_tag\output\tagcloud($tagsincloud);
2977 $output = $OUTPUT->render_from_template('core_tag/tagcloud', $tagcloud->export_for_template($OUTPUT));
2978 if ($return) {
2979 return $output;
2980 } else {
2981 echo $output;
2986 * Function that returns tags that start with some text, for use by the autocomplete feature
2988 * @package core_tag
2989 * @deprecated since 3.0
2990 * @access private
2991 * @param string $text string that the tag names will be matched against
2992 * @return mixed an array of objects, or false if no records were found or an error occured.
2994 function tag_autocomplete($text) {
2995 debugging('Function tag_autocomplete() is deprecated without replacement. ' .
2996 'New form element "tags" does proper autocomplete.', DEBUG_DEVELOPER);
2997 global $DB;
2998 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
2999 FROM {tag} tg
3000 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
3004 * Prints a box with the description of a tag and its related tags
3006 * @package core_tag
3007 * @deprecated since 3.1
3008 * @param stdClass $tag_object
3009 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
3010 * @return string/null a HTML box showing a description of the tag object and it's relationsips or null if output is done directly
3011 * in the function.
3013 function tag_print_description_box($tag_object, $return=false) {
3014 global $USER, $CFG, $OUTPUT;
3015 require_once($CFG->libdir.'/filelib.php');
3017 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
3018 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
3020 $relatedtags = array();
3021 if ($tag = core_tag_tag::get($tag_object->id)) {
3022 $relatedtags = $tag->get_related_tags();
3025 $content = !empty($tag_object->description);
3026 $output = '';
3028 if ($content) {
3029 $output .= $OUTPUT->box_start('generalbox tag-description');
3032 if (!empty($tag_object->description)) {
3033 $options = new stdClass();
3034 $options->para = false;
3035 $options->overflowdiv = true;
3036 $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', context_system::instance()->id, 'tag', 'description', $tag_object->id);
3037 $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options);
3040 if ($content) {
3041 $output .= $OUTPUT->box_end();
3044 if ($relatedtags) {
3045 $output .= $OUTPUT->tag_list($relatedtags, get_string('relatedtags', 'tag'), 'tag-relatedtags');
3048 if ($return) {
3049 return $output;
3050 } else {
3051 echo $output;
3056 * Prints a box that contains the management links of a tag
3058 * @deprecated since 3.1
3059 * @param core_tag_tag|stdClass $tag_object
3060 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
3061 * @return string|null a HTML string or null if this function does the output
3063 function tag_print_management_box($tag_object, $return=false) {
3064 global $USER, $CFG, $OUTPUT;
3066 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
3067 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
3069 $tagname = core_tag_tag::make_display_name($tag_object);
3070 $output = '';
3072 if (!isguestuser()) {
3073 $output .= $OUTPUT->box_start('box','tag-management-box');
3074 $systemcontext = context_system::instance();
3075 $links = array();
3077 // Add a link for users to add/remove this from their interests
3078 if (core_tag_tag::is_enabled('core', 'user') && core_tag_area::get_collection('core', 'user') == $tag_object->tagcollid) {
3079 if (core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $tag_object->name)) {
3080 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=removeinterest&amp;sesskey='. sesskey() .
3081 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
3082 get_string('removetagfrommyinterests', 'tag', $tagname) .'</a>';
3083 } else {
3084 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=addinterest&amp;sesskey='. sesskey() .
3085 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
3086 get_string('addtagtomyinterests', 'tag', $tagname) .'</a>';
3090 // Flag as inappropriate link. Only people with moodle/tag:flag capability.
3091 if (has_capability('moodle/tag:flag', $systemcontext)) {
3092 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=flaginappropriate&amp;sesskey='.
3093 sesskey() . '&amp;id='. $tag_object->id . '">'. get_string('flagasinappropriate',
3094 'tag', rawurlencode($tagname)) .'</a>';
3097 // Edit tag: Only people with moodle/tag:edit capability who either have it as an interest or can manage tags
3098 if (has_capability('moodle/tag:edit', $systemcontext) ||
3099 has_capability('moodle/tag:manage', $systemcontext)) {
3100 $links[] = '<a href="' . $CFG->wwwroot . '/tag/edit.php?id=' . $tag_object->id . '">' .
3101 get_string('edittag', 'tag') . '</a>';
3104 $output .= implode(' | ', $links);
3105 $output .= $OUTPUT->box_end();
3108 if ($return) {
3109 return $output;
3110 } else {
3111 echo $output;
3116 * Prints the tag search box
3118 * @deprecated since 3.1
3119 * @param bool $return if true return html string
3120 * @return string|null a HTML string or null if this function does the output
3122 function tag_print_search_box($return=false) {
3123 global $CFG, $OUTPUT;
3125 debugging('Function tag_print_search_box() is deprecated without replacement. ' .
3126 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
3128 $query = optional_param('query', '', PARAM_RAW);
3130 $output = $OUTPUT->box_start('','tag-search-box');
3131 $output .= '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
3132 $output .= '<div>';
3133 $output .= '<label class="accesshide" for="searchform_search">'.get_string('searchtags', 'tag').'</label>';
3134 $output .= '<input id="searchform_search" name="query" type="text" size="40" value="'.s($query).'" />';
3135 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
3136 $output .= '</div>';
3137 $output .= '</form>';
3138 $output .= $OUTPUT->box_end();
3140 if ($return) {
3141 return $output;
3143 else {
3144 echo $output;
3149 * Prints the tag search results
3151 * @deprecated since 3.1
3152 * @param string $query text that tag names will be matched against
3153 * @param int $page current page
3154 * @param int $perpage nr of users displayed per page
3155 * @param bool $return if true return html string
3156 * @return string|null a HTML string or null if this function does the output
3158 function tag_print_search_results($query, $page, $perpage, $return=false) {
3159 global $CFG, $USER, $OUTPUT;
3161 debugging('Function tag_print_search_results() is deprecated without replacement. ' .
3162 'In /tag/search.php the search results are printed using the core_tag/tagcloud template.', DEBUG_DEVELOPER);
3164 $query = clean_param($query, PARAM_TAG);
3166 $count = count(tag_find_tags($query, false));
3167 $tags = array();
3169 if ( $found_tags = tag_find_tags($query, true, $page * $perpage, $perpage) ) {
3170 $tags = array_values($found_tags);
3173 $baseurl = $CFG->wwwroot.'/tag/search.php?query='. rawurlencode($query);
3174 $output = '';
3176 // link "Add $query to my interests"
3177 $addtaglink = '';
3178 if (core_tag_tag::is_enabled('core', 'user') && !core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $query)) {
3179 $addtaglink = html_writer::link(new moodle_url('/tag/user.php', array('action' => 'addinterest', 'sesskey' => sesskey(),
3180 'tag' => $query)), get_string('addtagtomyinterests', 'tag', s($query)));
3183 if ( !empty($tags) ) { // there are results to display!!
3184 $output .= $OUTPUT->heading(get_string('searchresultsfor', 'tag', htmlspecialchars($query)) ." : {$count}", 3, 'main');
3186 //print a link "Add $query to my interests"
3187 if (!empty($addtaglink)) {
3188 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
3191 $nr_of_lis_per_ul = 6;
3192 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul );
3194 $output .= '<ul id="tag-search-results">';
3195 for($i = 0; $i < $nr_of_uls; $i++) {
3196 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul) as $tag) {
3197 $output .= '<li>';
3198 $tag_link = html_writer::link(core_tag_tag::make_url($tag->tagcollid, $tag->rawname),
3199 core_tag_tag::make_display_name($tag));
3200 $output .= $tag_link;
3201 $output .= '</li>';
3204 $output .= '</ul>';
3205 $output .= '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
3207 $output .= $OUTPUT->paging_bar($count, $page, $perpage, $baseurl);
3209 else { //no results were found!!
3210 $output .= $OUTPUT->heading(get_string('noresultsfor', 'tag', htmlspecialchars($query)), 3, 'main');
3212 //print a link "Add $query to my interests"
3213 if (!empty($addtaglink)) {
3214 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
3218 if ($return) {
3219 return $output;
3221 else {
3222 echo $output;
3227 * Prints a table of the users tagged with the tag passed as argument
3229 * @deprecated since 3.1
3230 * @param stdClass $tagobject the tag we wish to return data for
3231 * @param int $limitfrom (optional, required if $limitnum is set) prints users starting at this point.
3232 * @param int $limitnum (optional, required if $limitfrom is set) prints this many users.
3233 * @param bool $return if true return html string
3234 * @return string|null a HTML string or null if this function does the output
3236 function tag_print_tagged_users_table($tagobject, $limitfrom='', $limitnum='', $return=false) {
3238 debugging('Function tag_print_tagged_users_table() is deprecated without replacement. ' .
3239 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
3241 //List of users with this tag
3242 $tagobject = core_tag_tag::get($tagobject->id);
3243 $userlist = $tagobject->get_tagged_items('core', 'user', $limitfrom, $limitnum);
3245 $output = tag_print_user_list($userlist, true);
3247 if ($return) {
3248 return $output;
3250 else {
3251 echo $output;
3256 * Prints an individual user box
3258 * @deprecated since 3.1
3259 * @param user_object $user (contains the following fields: id, firstname, lastname and picture)
3260 * @param bool $return if true return html string
3261 * @return string|null a HTML string or null if this function does the output
3263 function tag_print_user_box($user, $return=false) {
3264 global $CFG, $OUTPUT;
3266 debugging('Function tag_print_user_box() is deprecated without replacement. ' .
3267 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
3269 $usercontext = context_user::instance($user->id);
3270 $profilelink = '';
3272 if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id))) {
3273 $profilelink = $CFG->wwwroot .'/user/view.php?id='. $user->id;
3276 $output = $OUTPUT->box_start('user-box', 'user'. $user->id);
3277 $fullname = fullname($user);
3278 $alt = '';
3280 if (!empty($profilelink)) {
3281 $output .= '<a href="'. $profilelink .'">';
3282 $alt = $fullname;
3285 $output .= $OUTPUT->user_picture($user, array('size'=>100));
3286 $output .= '<br />';
3288 if (!empty($profilelink)) {
3289 $output .= '</a>';
3292 //truncate name if it's too big
3293 if (core_text::strlen($fullname) > 26) {
3294 $fullname = core_text::substr($fullname, 0, 26) .'...';
3297 $output .= '<strong>'. $fullname .'</strong>';
3298 $output .= $OUTPUT->box_end();
3300 if ($return) {
3301 return $output;
3303 else {
3304 echo $output;
3309 * Prints a list of users
3311 * @deprecated since 3.1
3312 * @param array $userlist an array of user objects
3313 * @param bool $return if true return html string, otherwise output the result
3314 * @return string|null a HTML string or null if this function does the output
3316 function tag_print_user_list($userlist, $return=false) {
3318 debugging('Function tag_print_user_list() is deprecated without replacement. ' .
3319 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
3321 $output = '<div><ul class="inline-list">';
3323 foreach ($userlist as $user){
3324 $output .= '<li>'. tag_print_user_box($user, true) ."</li>\n";
3326 $output .= "</ul></div>\n";
3328 if ($return) {
3329 return $output;
3331 else {
3332 echo $output;
3337 * Function that returns the name that should be displayed for a specific tag
3339 * @package core_tag
3340 * @category tag
3341 * @deprecated since 3.1
3342 * @param stdClass|core_tag_tag $tagobject a line out of tag table, as returned by the adobd functions
3343 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
3344 * @return string
3346 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
3347 debugging('Function tag_display_name() is deprecated. Use core_tag_tag::make_display_name().', DEBUG_DEVELOPER);
3348 if (!isset($tagobject->name)) {
3349 return '';
3351 return core_tag_tag::make_display_name($tagobject, $html != TAG_RETURN_TEXT);
3355 * Function that normalizes a list of tag names.
3357 * @package core_tag
3358 * @deprecated since 3.1
3359 * @param array/string $rawtags array of tags, or a single tag.
3360 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
3361 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
3362 * (Eg: 'Banana' => 'banana').
3364 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
3365 debugging('Function tag_normalize() is deprecated. Use core_tag_tag::normalize().', DEBUG_DEVELOPER);
3367 if ( !is_array($rawtags) ) {
3368 $rawtags = array($rawtags);
3371 return core_tag_tag::normalize($rawtags, $case == TAG_CASE_LOWER);
3375 * Get a comma-separated list of tags related to another tag.
3377 * @package core_tag
3378 * @deprecated since 3.1
3379 * @param array $related_tags the array returned by tag_get_related_tags
3380 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
3381 * @return string comma-separated list
3383 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
3384 global $OUTPUT;
3385 debugging('Method tag_get_related_tags_csv() is deprecated. Consider '
3386 . 'looping through array or using $OUTPUT->tag_list(core_tag_tag::get_item_tags())',
3387 DEBUG_DEVELOPER);
3388 if ($html != TAG_RETURN_TEXT) {
3389 return $OUTPUT->tag_list($related_tags, '');
3392 $tagsnames = array();
3393 foreach ($related_tags as $tag) {
3394 $tagsnames[] = core_tag_tag::make_display_name($tag, false);
3396 return implode(', ', $tagsnames);
3400 * Used to require that the return value from a function is an array.
3401 * Only used in the deprecated function {@link tag_get_id()}
3402 * @deprecated since 3.1
3404 define('TAG_RETURN_ARRAY', 0);
3406 * Used to require that the return value from a function is an object.
3407 * Only used in the deprecated function {@link tag_get_id()}
3408 * @deprecated since 3.1
3410 define('TAG_RETURN_OBJECT', 1);
3412 * Use to specify that HTML free text is expected to be returned from a function.
3413 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3414 * {@link tag_get_related_tags_csv()}
3415 * @deprecated since 3.1
3417 define('TAG_RETURN_TEXT', 2);
3419 * Use to specify that encoded HTML is expected to be returned from a function.
3420 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3421 * {@link tag_get_related_tags_csv()}
3422 * @deprecated since 3.1
3424 define('TAG_RETURN_HTML', 3);
3427 * Used to specify that we wish a lowercased string to be returned
3428 * Only used in deprecated function {@link tag_normalize()}
3429 * @deprecated since 3.1
3431 define('TAG_CASE_LOWER', 0);
3433 * Used to specify that we do not wish the case of the returned string to change
3434 * Only used in deprecated function {@link tag_normalize()}
3435 * @deprecated since 3.1
3437 define('TAG_CASE_ORIGINAL', 1);
3440 * Used to specify that we want all related tags returned, no matter how they are related.
3441 * Only used in deprecated function {@link tag_get_related_tags()}
3442 * @deprecated since 3.1
3444 define('TAG_RELATED_ALL', 0);
3446 * Used to specify that we only want back tags that were manually related.
3447 * Only used in deprecated function {@link tag_get_related_tags()}
3448 * @deprecated since 3.1
3450 define('TAG_RELATED_MANUAL', 1);
3452 * Used to specify that we only want back tags where the relationship was automatically correlated.
3453 * Only used in deprecated function {@link tag_get_related_tags()}
3454 * @deprecated since 3.1
3456 define('TAG_RELATED_CORRELATED', 2);
3459 * Set the tags assigned to a record. This overwrites the current tags.
3461 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
3463 * Due to API change $component and $contextid are now required. Instead of
3464 * calling this function you can use {@link core_tag_tag::set_item_tags()} or
3465 * {@link core_tag_tag::set_related_tags()}
3467 * @package core_tag
3468 * @deprecated since 3.1
3469 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
3470 * @param int $itemid the id of the record to tag
3471 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
3472 * @param string|null $component the component that was tagged
3473 * @param int|null $contextid the context id of where this tag was assigned
3474 * @return bool|null
3476 function tag_set($itemtype, $itemid, $tags, $component = null, $contextid = null) {
3477 debugging('Function tag_set() is deprecated. Use ' .
3478 ' core_tag_tag::set_item_tags() instead', DEBUG_DEVELOPER);
3480 if ($itemtype === 'tag') {
3481 return core_tag_tag::get($itemid, '*', MUST_EXIST)->set_related_tags($tags);
3482 } else {
3483 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3484 return core_tag_tag::set_item_tags($component, $itemtype, $itemid, $context, $tags);
3489 * Adds a tag to a record, without overwriting the current tags.
3491 * This function remains here for backward compatiblity. It is recommended to use
3492 * {@link core_tag_tag::add_item_tag()} or {@link core_tag_tag::add_related_tags()} instead
3494 * @package core_tag
3495 * @deprecated since 3.1
3496 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3497 * @param int $itemid the id of the record to tag
3498 * @param string $tag the tag to add
3499 * @param string|null $component the component that was tagged
3500 * @param int|null $contextid the context id of where this tag was assigned
3501 * @return bool|null
3503 function tag_set_add($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3504 debugging('Function tag_set_add() is deprecated. Use ' .
3505 ' core_tag_tag::add_item_tag() instead', DEBUG_DEVELOPER);
3507 if ($itemtype === 'tag') {
3508 return core_tag_tag::get($itemid, '*', MUST_EXIST)->add_related_tags(array($tag));
3509 } else {
3510 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3511 return core_tag_tag::add_item_tag($component, $itemtype, $itemid, $context, $tag);
3516 * Removes a tag from a record, without overwriting other current tags.
3518 * This function remains here for backward compatiblity. It is recommended to use
3519 * {@link core_tag_tag::remove_item_tag()} instead
3521 * @package core_tag
3522 * @deprecated since 3.1
3523 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3524 * @param int $itemid the id of the record to tag
3525 * @param string $tag the tag to delete
3526 * @param string|null $component the component that was tagged
3527 * @param int|null $contextid the context id of where this tag was assigned
3528 * @return bool|null
3530 function tag_set_delete($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3531 debugging('Function tag_set_delete() is deprecated. Use ' .
3532 ' core_tag_tag::remove_item_tag() instead', DEBUG_DEVELOPER);
3533 return core_tag_tag::remove_item_tag($component, $itemtype, $itemid, $tag);
3537 * Simple function to just return a single tag object when you know the name or something
3539 * See also {@link core_tag_tag::get()} and {@link core_tag_tag::get_by_name()}
3541 * @package core_tag
3542 * @deprecated since 3.1
3543 * @param string $field which field do we use to identify the tag: id, name or rawname
3544 * @param string $value the required value of the aforementioned field
3545 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
3546 * 'id', 'name', 'rawname' or '*' to include all fields.
3547 * @return mixed tag object
3549 function tag_get($field, $value, $returnfields='id, name, rawname, tagcollid') {
3550 global $DB;
3551 debugging('Function tag_get() is deprecated. Use ' .
3552 ' core_tag_tag::get() or core_tag_tag::get_by_name()',
3553 DEBUG_DEVELOPER);
3554 if ($field === 'id') {
3555 $tag = core_tag_tag::get((int)$value, $returnfields);
3556 } else if ($field === 'name') {
3557 $tag = core_tag_tag::get_by_name(0, $value, $returnfields);
3558 } else {
3559 $params = array($field => $value);
3560 return $DB->get_record('tag', $params, $returnfields);
3562 if ($tag) {
3563 return $tag->to_object();
3565 return null;
3569 * Returns tags related to a tag
3571 * Related tags of a tag come from two sources:
3572 * - manually added related tags, which are tag_instance entries for that tag
3573 * - correlated tags, which are calculated
3575 * @package core_tag
3576 * @deprecated since 3.1
3577 * @param string $tagid is a single **normalized** tag name or the id of a tag
3578 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
3579 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
3580 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
3581 * @return array an array of tag objects
3583 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
3584 debugging('Method tag_get_related_tags() is deprecated, '
3585 . 'use core_tag_tag::get_correlated_tags(), core_tag_tag::get_related_tags() or '
3586 . 'core_tag_tag::get_manual_related_tags()', DEBUG_DEVELOPER);
3587 $result = array();
3588 if ($tag = core_tag_tag::get($tagid)) {
3589 if ($type == TAG_RELATED_CORRELATED) {
3590 $tags = $tag->get_correlated_tags();
3591 } else if ($type == TAG_RELATED_MANUAL) {
3592 $tags = $tag->get_manual_related_tags();
3593 } else {
3594 $tags = $tag->get_related_tags();
3596 $tags = array_slice($tags, 0, $limitnum);
3597 foreach ($tags as $id => $tag) {
3598 $result[$id] = $tag->to_object();
3601 return $result;
3605 * Delete one or more tag, and all their instances if there are any left.
3607 * @package core_tag
3608 * @deprecated since 3.1
3609 * @param mixed $tagids one tagid (int), or one array of tagids to delete
3610 * @return bool true on success, false otherwise
3612 function tag_delete($tagids) {
3613 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_tags()',
3614 DEBUG_DEVELOPER);
3615 return core_tag_tag::delete_tags($tagids);
3619 * Deletes all the tag instances given a component and an optional contextid.
3621 * @deprecated since 3.1
3622 * @param string $component
3623 * @param int $contextid if null, then we delete all tag instances for the $component
3625 function tag_delete_instances($component, $contextid = null) {
3626 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_instances()',
3627 DEBUG_DEVELOPER);
3628 core_tag_tag::delete_instances($component, null, $contextid);
3632 * Clean up the tag tables, making sure all tagged object still exists.
3634 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
3635 * 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
3636 * call: don't run at peak time.
3638 * @package core_tag
3639 * @deprecated since 3.1
3641 function tag_cleanup() {
3642 debugging('Method tag_cleanup() is deprecated, use \core\task\tag_cron_task::cleanup()',
3643 DEBUG_DEVELOPER);
3645 $task = new \core\task\tag_cron_task();
3646 return $task->cleanup();
3650 * This function will delete numerous tag instances efficiently.
3651 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
3653 * @deprecated since 3.1
3654 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
3655 * (used for recording a delete event).
3657 function tag_bulk_delete_instances($instances) {
3658 debugging('Method tag_bulk_delete_instances() is deprecated, '
3659 . 'use \core\task\tag_cron_task::bulk_delete_instances()',
3660 DEBUG_DEVELOPER);
3662 $task = new \core\task\tag_cron_task();
3663 return $task->bulk_delete_instances($instances);
3667 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
3669 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
3671 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
3672 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
3674 * @package core_tag
3675 * @deprecated since 3.1
3676 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
3678 function tag_compute_correlations($mincorrelation = 2) {
3679 debugging('Method tag_compute_correlations() is deprecated, '
3680 . 'use \core\task\tag_cron_task::compute_correlations()',
3681 DEBUG_DEVELOPER);
3683 $task = new \core\task\tag_cron_task();
3684 return $task->compute_correlations($mincorrelation);
3688 * This function processes a tag correlation and makes changes in the database as required.
3690 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
3692 * @package core_tag
3693 * @deprecated since 3.1
3694 * @param stdClass $tagcorrelation
3695 * @return int/bool The id of the tag correlation that was just processed or false.
3697 function tag_process_computed_correlation(stdClass $tagcorrelation) {
3698 debugging('Method tag_process_computed_correlation() is deprecated, '
3699 . 'use \core\task\tag_cron_task::process_computed_correlation()',
3700 DEBUG_DEVELOPER);
3702 $task = new \core\task\tag_cron_task();
3703 return $task->process_computed_correlation($tagcorrelation);
3707 * Tasks that should be performed at cron time
3709 * @package core_tag
3710 * @deprecated since 3.1
3712 function tag_cron() {
3713 debugging('Method tag_cron() is deprecated, use \core\task\tag_cron_task::execute()',
3714 DEBUG_DEVELOPER);
3716 $task = new \core\task\tag_cron_task();
3717 $task->execute();
3721 * Search for tags with names that match some text
3723 * @package core_tag
3724 * @deprecated since 3.1
3725 * @param string $text escaped string that the tag names will be matched against
3726 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
3727 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
3728 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
3729 * @param int $tagcollid
3730 * @return array/boolean an array of objects, or false if no records were found or an error occured.
3732 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='', $tagcollid = null) {
3733 debugging('Method tag_find_tags() is deprecated without replacement', DEBUG_DEVELOPER);
3734 global $DB;
3736 $text = core_text::strtolower(clean_param($text, PARAM_TAG));
3738 list($sql, $params) = $DB->get_in_or_equal($tagcollid ? array($tagcollid) :
3739 array_keys(core_tag_collection::get_collections(true)));
3740 array_unshift($params, "%{$text}%");
3742 if ($ordered) {
3743 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid, COUNT(ti.id) AS count
3744 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
3745 WHERE tg.name LIKE ? AND tg.tagcollid $sql
3746 GROUP BY tg.id, tg.name, tg.rawname
3747 ORDER BY count DESC";
3748 } else {
3749 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid
3750 FROM {tag} tg
3751 WHERE tg.name LIKE ? AND tg.tagcollid $sql";
3753 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
3757 * Get the name of a tag
3759 * @package core_tag
3760 * @deprecated since 3.1
3761 * @param mixed $tagids the id of the tag, or an array of ids
3762 * @return mixed string name of one tag, or id-indexed array of strings
3764 function tag_get_name($tagids) {
3765 debugging('Method tag_get_name() is deprecated without replacement', DEBUG_DEVELOPER);
3766 global $DB;
3768 if (!is_array($tagids)) {
3769 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
3770 return $tag->name;
3772 return false;
3775 $tag_names = array();
3776 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
3777 $tag_names[$tag->id] = $tag->name;
3780 return $tag_names;
3784 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
3785 * empty and this function won't return anything.
3787 * Correlated tags are calculated in cron based on existing tag instances.
3789 * @package core_tag
3790 * @deprecated since 3.1
3791 * @param int $tagid is a single tag id
3792 * @param int $notused this argument is no longer used
3793 * @return array an array of tag objects or an empty if no correlated tags are found
3795 function tag_get_correlated($tagid, $notused = null) {
3796 debugging('Method tag_get_correlated() is deprecated, '
3797 . 'use core_tag_tag::get_correlated_tags()', DEBUG_DEVELOPER);
3798 $result = array();
3799 if ($tag = core_tag_tag::get($tagid)) {
3800 $tags = $tag->get_correlated_tags(true);
3801 // Convert to objects for backward-compatibility.
3802 foreach ($tags as $id => $tag) {
3803 $result[$id] = $tag->to_object();
3806 return $result;
3810 * This function is used by print_tag_cloud, to usort() the tags in the cloud. See php.net/usort for the parameters documentation.
3811 * This was originally in blocks/blog_tags/block_blog_tags.php, named blog_tags_sort().
3813 * @package core_tag
3814 * @deprecated since 3.1
3815 * @param string $a Tag name to compare against $b
3816 * @param string $b Tag name to compare against $a
3817 * @return int The result of the comparison/validation 1, 0 or -1
3819 function tag_cloud_sort($a, $b) {
3820 debugging('Method tag_cloud_sort() is deprecated, similar method can be found in core_tag_collection::cloud_sort()', DEBUG_DEVELOPER);
3821 global $CFG;
3823 if (empty($CFG->tagsort)) {
3824 $tagsort = 'name'; // by default, sort by name
3825 } else {
3826 $tagsort = $CFG->tagsort;
3829 if (is_numeric($a->$tagsort)) {
3830 return ($a->$tagsort == $b->$tagsort) ? 0 : ($a->$tagsort > $b->$tagsort) ? 1 : -1;
3831 } elseif (is_string($a->$tagsort)) {
3832 return strcmp($a->$tagsort, $b->$tagsort);
3833 } else {
3834 return 0;
3839 * Loads the events definitions for the component (from file). If no
3840 * events are defined for the component, we simply return an empty array.
3842 * @access protected To be used from eventslib only
3843 * @deprecated since Moodle 3.1
3844 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3845 * @return array Array of capabilities or empty array if not exists
3847 function events_load_def($component) {
3848 global $CFG;
3849 if ($component === 'unittest') {
3850 $defpath = $CFG->dirroot.'/lib/tests/fixtures/events.php';
3851 } else {
3852 $defpath = core_component::get_component_directory($component).'/db/events.php';
3855 $handlers = array();
3857 if (file_exists($defpath)) {
3858 require($defpath);
3861 // make sure the definitions are valid and complete; tell devs what is wrong
3862 foreach ($handlers as $eventname => $handler) {
3863 if ($eventname === 'reset') {
3864 debugging("'reset' can not be used as event name.");
3865 unset($handlers['reset']);
3866 continue;
3868 if (!is_array($handler)) {
3869 debugging("Handler of '$eventname' must be specified as array'");
3870 unset($handlers[$eventname]);
3871 continue;
3873 if (!isset($handler['handlerfile'])) {
3874 debugging("Handler of '$eventname' must include 'handlerfile' key'");
3875 unset($handlers[$eventname]);
3876 continue;
3878 if (!isset($handler['handlerfunction'])) {
3879 debugging("Handler of '$eventname' must include 'handlerfunction' key'");
3880 unset($handlers[$eventname]);
3881 continue;
3883 if (!isset($handler['schedule'])) {
3884 $handler['schedule'] = 'instant';
3886 if ($handler['schedule'] !== 'instant' and $handler['schedule'] !== 'cron') {
3887 debugging("Handler of '$eventname' must include valid 'schedule' type (instant or cron)'");
3888 unset($handlers[$eventname]);
3889 continue;
3891 if (!isset($handler['internal'])) {
3892 $handler['internal'] = 1;
3894 $handlers[$eventname] = $handler;
3897 return $handlers;
3901 * Puts a handler on queue
3903 * @access protected To be used from eventslib only
3904 * @deprecated since Moodle 3.1
3905 * @param stdClass $handler event handler object from db
3906 * @param stdClass $event event data object
3907 * @param string $errormessage The error message indicating the problem
3908 * @return int id number of new queue handler
3910 function events_queue_handler($handler, $event, $errormessage) {
3911 global $DB;
3913 if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id, 'handlerid'=>$handler->id))) {
3914 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
3915 return $qhandler->id;
3918 // make a new queue handler
3919 $qhandler = new stdClass();
3920 $qhandler->queuedeventid = $event->id;
3921 $qhandler->handlerid = $handler->id;
3922 $qhandler->errormessage = $errormessage;
3923 $qhandler->timemodified = time();
3924 if ($handler->schedule === 'instant' and $handler->status == 1) {
3925 $qhandler->status = 1; //already one failed attempt to dispatch this event
3926 } else {
3927 $qhandler->status = 0;
3930 return $DB->insert_record('events_queue_handlers', $qhandler);
3934 * trigger a single event with a specified handler
3936 * @access protected To be used from eventslib only
3937 * @deprecated since Moodle 3.1
3938 * @param stdClass $handler This shoudl be a row from the events_handlers table.
3939 * @param stdClass $eventdata An object containing information about the event
3940 * @param string $errormessage error message indicating problem
3941 * @return bool|null True means event processed, false means retry event later; may throw exception, NULL means internal error
3943 function events_dispatch($handler, $eventdata, &$errormessage) {
3944 global $CFG;
3946 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3948 $function = unserialize($handler->handlerfunction);
3950 if (is_callable($function)) {
3951 // oki, no need for includes
3953 } else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
3954 include_once($CFG->dirroot.$handler->handlerfile);
3956 } else {
3957 $errormessage = "Handler file of component $handler->component: $handler->handlerfile can not be found!";
3958 return null;
3961 // checks for handler validity
3962 if (is_callable($function)) {
3963 $result = call_user_func($function, $eventdata);
3964 if ($result === false) {
3965 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction requested resending of event!";
3966 return false;
3968 return true;
3970 } else {
3971 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction not callable function or class method!";
3972 return null;
3977 * given a queued handler, call the respective event handler to process the event
3979 * @access protected To be used from eventslib only
3980 * @deprecated since Moodle 3.1
3981 * @param stdClass $qhandler events_queued_handler row from db
3982 * @return boolean true means event processed, false means retry later, NULL means fatal failure
3984 function events_process_queued_handler($qhandler) {
3985 global $DB;
3987 // get handler
3988 if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid))) {
3989 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
3990 //irrecoverable error, remove broken queue handler
3991 events_dequeue($qhandler);
3992 return NULL;
3995 // get event object
3996 if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid))) {
3997 // can't proceed with no event object - might happen when two crons running at the same time
3998 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
3999 //irrecoverable error, remove broken queue handler
4000 events_dequeue($qhandler);
4001 return NULL;
4004 // call the function specified by the handler
4005 try {
4006 $errormessage = 'Unknown error';
4007 if (events_dispatch($handler, unserialize(base64_decode($event->eventdata)), $errormessage)) {
4008 //everything ok
4009 events_dequeue($qhandler);
4010 return true;
4012 } catch (Exception $e) {
4013 // the problem here is that we do not want one broken handler to stop all others,
4014 // cron handlers are very tricky because the needed data might have been deleted before the cron execution
4015 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction threw exception :" .
4016 $e->getMessage() . "\n" . format_backtrace($e->getTrace(), true);
4017 if (!empty($e->debuginfo)) {
4018 $errormessage .= $e->debuginfo;
4022 //dispatching failed
4023 $qh = new stdClass();
4024 $qh->id = $qhandler->id;
4025 $qh->errormessage = $errormessage;
4026 $qh->timemodified = time();
4027 $qh->status = $qhandler->status + 1;
4028 $DB->update_record('events_queue_handlers', $qh);
4030 debugging($errormessage);
4032 return false;
4036 * Updates all of the event definitions within the database.
4038 * Unfortunately this isn't as simple as removing them all and then readding
4039 * the updated event definitions. Chances are queued items are referencing the
4040 * existing definitions.
4042 * Note that the absence of the db/events.php event definition file
4043 * will cause any queued events for the component to be removed from
4044 * the database.
4046 * @category event
4047 * @deprecated since Moodle 3.1
4048 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
4049 * @return boolean always returns true
4051 function events_update_definition($component='moodle') {
4052 global $DB;
4054 // load event definition from events.php
4055 $filehandlers = events_load_def($component);
4057 if ($filehandlers) {
4058 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
4061 // load event definitions from db tables
4062 // if we detect an event being already stored, we discard from this array later
4063 // the remaining needs to be removed
4064 $cachedhandlers = events_get_cached($component);
4066 foreach ($filehandlers as $eventname => $filehandler) {
4067 if (!empty($cachedhandlers[$eventname])) {
4068 if ($cachedhandlers[$eventname]['handlerfile'] === $filehandler['handlerfile'] &&
4069 $cachedhandlers[$eventname]['handlerfunction'] === serialize($filehandler['handlerfunction']) &&
4070 $cachedhandlers[$eventname]['schedule'] === $filehandler['schedule'] &&
4071 $cachedhandlers[$eventname]['internal'] == $filehandler['internal']) {
4072 // exact same event handler already present in db, ignore this entry
4074 unset($cachedhandlers[$eventname]);
4075 continue;
4077 } else {
4078 // same event name matches, this event has been updated, update the datebase
4079 $handler = new stdClass();
4080 $handler->id = $cachedhandlers[$eventname]['id'];
4081 $handler->handlerfile = $filehandler['handlerfile'];
4082 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
4083 $handler->schedule = $filehandler['schedule'];
4084 $handler->internal = $filehandler['internal'];
4086 $DB->update_record('events_handlers', $handler);
4088 unset($cachedhandlers[$eventname]);
4089 continue;
4092 } else {
4093 // if we are here, this event handler is not present in db (new)
4094 // add it
4095 $handler = new stdClass();
4096 $handler->eventname = $eventname;
4097 $handler->component = $component;
4098 $handler->handlerfile = $filehandler['handlerfile'];
4099 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
4100 $handler->schedule = $filehandler['schedule'];
4101 $handler->status = 0;
4102 $handler->internal = $filehandler['internal'];
4104 $DB->insert_record('events_handlers', $handler);
4108 // clean up the left overs, the entries in cached events array at this points are deprecated event handlers
4109 // and should be removed, delete from db
4110 events_cleanup($component, $cachedhandlers);
4112 events_get_handlers('reset');
4114 return true;
4118 * Events cron will try to empty the events queue by processing all the queued events handlers
4120 * @access public Part of the public API
4121 * @deprecated since Moodle 3.1
4122 * @category event
4123 * @param string $eventname empty means all
4124 * @return int number of dispatched events
4126 function events_cron($eventname='') {
4127 global $DB;
4129 $failed = array();
4130 $processed = 0;
4132 if ($eventname) {
4133 $sql = "SELECT qh.*
4134 FROM {events_queue_handlers} qh, {events_handlers} h
4135 WHERE qh.handlerid = h.id AND h.eventname=?
4136 ORDER BY qh.id";
4137 $params = array($eventname);
4138 } else {
4139 $sql = "SELECT *
4140 FROM {events_queue_handlers}
4141 ORDER BY id";
4142 $params = array();
4145 $rs = $DB->get_recordset_sql($sql, $params);
4146 if ($rs->valid()) {
4147 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
4150 foreach ($rs as $qhandler) {
4151 if (isset($failed[$qhandler->handlerid])) {
4152 // do not try to dispatch any later events when one already asked for retry or ended with exception
4153 continue;
4155 $status = events_process_queued_handler($qhandler);
4156 if ($status === false) {
4157 // handler is asking for retry, do not send other events to this handler now
4158 $failed[$qhandler->handlerid] = $qhandler->handlerid;
4159 } else if ($status === NULL) {
4160 // means completely broken handler, event data was purged
4161 $failed[$qhandler->handlerid] = $qhandler->handlerid;
4162 } else {
4163 $processed++;
4166 $rs->close();
4168 // remove events that do not have any handlers waiting
4169 $sql = "SELECT eq.id
4170 FROM {events_queue} eq
4171 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
4172 WHERE qh.id IS NULL";
4173 $rs = $DB->get_recordset_sql($sql);
4174 foreach ($rs as $event) {
4175 //debugging('Purging stale event '.$event->id);
4176 $DB->delete_records('events_queue', array('id'=>$event->id));
4178 $rs->close();
4180 return $processed;
4184 * Do not call directly, this is intended to be used from new event base only.
4186 * @private
4187 * @deprecated since Moodle 3.1
4188 * @param string $eventname name of the event
4189 * @param mixed $eventdata event data object
4190 * @return int number of failed events
4192 function events_trigger_legacy($eventname, $eventdata) {
4193 global $CFG, $USER, $DB;
4195 $failedcount = 0; // number of failed events.
4197 // pull out all registered event handlers
4198 if ($handlers = events_get_handlers($eventname)) {
4199 foreach ($handlers as $handler) {
4200 $errormessage = '';
4202 if ($handler->schedule === 'instant') {
4203 if ($handler->status) {
4204 //check if previous pending events processed
4205 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
4206 // ok, queue is empty, lets reset the status back to 0 == ok
4207 $handler->status = 0;
4208 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
4209 // reset static handler cache
4210 events_get_handlers('reset');
4214 // dispatch the event only if instant schedule and status ok
4215 if ($handler->status or (!$handler->internal and $DB->is_transaction_started())) {
4216 // increment the error status counter
4217 $handler->status++;
4218 $DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
4219 // reset static handler cache
4220 events_get_handlers('reset');
4222 } else {
4223 $errormessage = 'Unknown error';
4224 $result = events_dispatch($handler, $eventdata, $errormessage);
4225 if ($result === true) {
4226 // everything is fine - event dispatched
4227 continue;
4228 } else if ($result === false) {
4229 // retry later - set error count to 1 == send next instant into cron queue
4230 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
4231 // reset static handler cache
4232 events_get_handlers('reset');
4233 } else {
4234 // internal problem - ignore the event completely
4235 $failedcount ++;
4236 continue;
4240 // update the failed counter
4241 $failedcount ++;
4243 } else if ($handler->schedule === 'cron') {
4244 //ok - use queueing of events only
4246 } else {
4247 // unknown schedule - ignore event completely
4248 debugging("Unknown handler schedule type: $handler->schedule");
4249 $failedcount ++;
4250 continue;
4253 // if even type is not instant, or dispatch asked for retry, queue it
4254 $event = new stdClass();
4255 $event->userid = $USER->id;
4256 $event->eventdata = base64_encode(serialize($eventdata));
4257 $event->timecreated = time();
4258 if (debugging()) {
4259 $dump = '';
4260 $callers = debug_backtrace();
4261 foreach ($callers as $caller) {
4262 if (!isset($caller['line'])) {
4263 $caller['line'] = '?';
4265 if (!isset($caller['file'])) {
4266 $caller['file'] = '?';
4268 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
4269 if (isset($caller['function'])) {
4270 $dump .= ': call to ';
4271 if (isset($caller['class'])) {
4272 $dump .= $caller['class'] . $caller['type'];
4274 $dump .= $caller['function'] . '()';
4276 $dump .= "\n";
4278 $event->stackdump = $dump;
4279 } else {
4280 $event->stackdump = '';
4282 $event->id = $DB->insert_record('events_queue', $event);
4283 events_queue_handler($handler, $event, $errormessage);
4285 } else {
4286 // No handler found for this event name - this is ok!
4289 return $failedcount;
4293 * checks if an event is registered for this component
4295 * @access public Part of the public API
4296 * @deprecated since Moodle 3.1
4297 * @param string $eventname name of the event
4298 * @param string $component component name, can be mod/data or moodle
4299 * @return bool
4301 function events_is_registered($eventname, $component) {
4302 global $DB;
4304 debugging('events_is_registered() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
4305 ' please use it instead.', DEBUG_DEVELOPER);
4307 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
4311 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
4313 * @access public Part of the public API
4314 * @deprecated since Moodle 3.1
4315 * @param string $eventname name of the event
4316 * @return int number of queued events
4318 function events_pending_count($eventname) {
4319 global $DB;
4321 debugging('events_pending_count() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
4322 ' please use it instead.', DEBUG_DEVELOPER);
4324 $sql = "SELECT COUNT('x')
4325 FROM {events_queue_handlers} qh
4326 JOIN {events_handlers} h ON h.id = qh.handlerid
4327 WHERE h.eventname = ?";
4329 return $DB->count_records_sql($sql, array($eventname));
4333 * Emails admins about a clam outcome
4335 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
4336 * @param string $notice The body of the email to be sent.
4337 * @return void
4339 function clam_message_admins($notice) {
4340 debugging('clam_message_admins() is deprecated, please use message_admins() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
4342 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
4343 $antivirus->message_admins($notice);
4347 * Returns the string equivalent of a numeric clam error code
4349 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
4350 * @param int $returncode The numeric error code in question.
4351 * @return string The definition of the error code
4353 function get_clam_error_code($returncode) {
4354 debugging('get_clam_error_code() is deprecated, please use get_clam_error_code() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
4356 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
4357 return $antivirus->get_clam_error_code($returncode);
4361 * Returns the rename action.
4363 * @deprecated since 3.1
4364 * @param cm_info $mod The module to produce editing buttons for
4365 * @param int $sr The section to link back to (used for creating the links)
4366 * @return The markup for the rename action, or an empty string if not available.
4368 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
4369 global $COURSE, $OUTPUT;
4371 static $str;
4372 static $baseurl;
4374 debugging('Function course_get_cm_rename_action() is deprecated. Please use inplace_editable ' .
4375 'https://docs.moodle.org/dev/Inplace_editable', DEBUG_DEVELOPER);
4377 $modcontext = context_module::instance($mod->id);
4378 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
4380 if (!isset($str)) {
4381 $str = get_strings(array('edittitle'));
4384 if (!isset($baseurl)) {
4385 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
4388 if ($sr !== null) {
4389 $baseurl->param('sr', $sr);
4392 // AJAX edit title.
4393 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
4394 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
4395 // we will not display link if we are on some other-course page (where we should not see this module anyway)
4396 return html_writer::span(
4397 html_writer::link(
4398 new moodle_url($baseurl, array('update' => $mod->id)),
4399 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
4400 array(
4401 'class' => 'editing_title',
4402 'data-action' => 'edittitle',
4403 'title' => $str->edittitle,
4408 return '';
4412 * This function returns the number of activities using the given scale in the given course.
4414 * @deprecated since Moodle 3.1
4415 * @param int $courseid The course ID to check.
4416 * @param int $scaleid The scale ID to check
4417 * @return int
4419 function course_scale_used($courseid, $scaleid) {
4420 global $CFG, $DB;
4422 debugging('course_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4423 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4425 $return = 0;
4427 if (!empty($scaleid)) {
4428 if ($cms = get_course_mods($courseid)) {
4429 foreach ($cms as $cm) {
4430 // Check cm->name/lib.php exists.
4431 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
4432 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
4433 $functionname = $cm->modname.'_scale_used';
4434 if (function_exists($functionname)) {
4435 if ($functionname($cm->instance, $scaleid)) {
4436 $return++;
4443 // Check if any course grade item makes use of the scale.
4444 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
4446 // Check if any outcome in the course makes use of the scale.
4447 $return += $DB->count_records_sql("SELECT COUNT('x')
4448 FROM {grade_outcomes_courses} goc,
4449 {grade_outcomes} go
4450 WHERE go.id = goc.outcomeid
4451 AND go.scaleid = ? AND goc.courseid = ?",
4452 array($scaleid, $courseid));
4454 return $return;
4458 * This function returns the number of activities using scaleid in the entire site
4460 * @deprecated since Moodle 3.1
4461 * @param int $scaleid
4462 * @param array $courses
4463 * @return int
4465 function site_scale_used($scaleid, &$courses) {
4466 $return = 0;
4468 debugging('site_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4469 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4471 if (!is_array($courses) || count($courses) == 0) {
4472 $courses = get_courses("all", false, "c.id, c.shortname");
4475 if (!empty($scaleid)) {
4476 if (is_array($courses) && count($courses) > 0) {
4477 foreach ($courses as $course) {
4478 $return += course_scale_used($course->id, $scaleid);
4482 return $return;
4486 * Returns detailed function information
4488 * @deprecated since Moodle 3.1
4489 * @param string|object $function name of external function or record from external_function
4490 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4491 * MUST_EXIST means throw exception if no record or multiple records found
4492 * @return stdClass description or false if not found or exception thrown
4493 * @since Moodle 2.0
4495 function external_function_info($function, $strictness=MUST_EXIST) {
4496 debugging('external_function_info() is deprecated. Please use external_api::external_function_info() instead.',
4497 DEBUG_DEVELOPER);
4498 return external_api::external_function_info($function, $strictness);
4502 * Retrieves an array of records from a CSV file and places
4503 * them into a given table structure
4504 * This function is deprecated. Please use csv_import_reader() instead.
4506 * @deprecated since Moodle 3.2 MDL-55126
4507 * @todo MDL-55195 for final deprecation in Moodle 3.6
4508 * @see csv_import_reader::load_csv_content()
4509 * @global stdClass $CFG
4510 * @global moodle_database $DB
4511 * @param string $file The path to a CSV file
4512 * @param string $table The table to retrieve columns from
4513 * @return bool|array Returns an array of CSV records or false
4515 function get_records_csv($file, $table) {
4516 global $CFG, $DB;
4518 debugging('get_records_csv() is deprecated. Please use lib/csvlib.class.php csv_import_reader() instead.');
4520 if (!$metacolumns = $DB->get_columns($table)) {
4521 return false;
4524 if(!($handle = @fopen($file, 'r'))) {
4525 print_error('get_records_csv failed to open '.$file);
4528 $fieldnames = fgetcsv($handle, 4096);
4529 if(empty($fieldnames)) {
4530 fclose($handle);
4531 return false;
4534 $columns = array();
4536 foreach($metacolumns as $metacolumn) {
4537 $ord = array_search($metacolumn->name, $fieldnames);
4538 if(is_int($ord)) {
4539 $columns[$metacolumn->name] = $ord;
4543 $rows = array();
4545 while (($data = fgetcsv($handle, 4096)) !== false) {
4546 $item = new stdClass;
4547 foreach($columns as $name => $ord) {
4548 $item->$name = $data[$ord];
4550 $rows[] = $item;
4553 fclose($handle);
4554 return $rows;
4558 * Create a file with CSV contents
4559 * This function is deprecated. Please use download_as_dataformat() instead.
4561 * @deprecated since Moodle 3.2 MDL-55126
4562 * @todo MDL-55195 for final deprecation in Moodle 3.6
4563 * @see download_as_dataformat (lib/dataformatlib.php)
4564 * @global stdClass $CFG
4565 * @global moodle_database $DB
4566 * @param string $file The file to put the CSV content into
4567 * @param array $records An array of records to write to a CSV file
4568 * @param string $table The table to get columns from
4569 * @return bool success
4571 function put_records_csv($file, $records, $table = NULL) {
4572 global $CFG, $DB;
4574 debugging('put_records_csv() is deprecated. Please use lib/dataformatlib.php download_as_dataformat()');
4576 if (empty($records)) {
4577 return true;
4580 $metacolumns = NULL;
4581 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
4582 return false;
4585 echo "x";
4587 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
4588 print_error('put_records_csv failed to open '.$file);
4591 $proto = reset($records);
4592 if(is_object($proto)) {
4593 $fields_records = array_keys(get_object_vars($proto));
4595 else if(is_array($proto)) {
4596 $fields_records = array_keys($proto);
4598 else {
4599 return false;
4601 echo "x";
4603 if(!empty($metacolumns)) {
4604 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
4605 $fields = array_intersect($fields_records, $fields_table);
4607 else {
4608 $fields = $fields_records;
4611 fwrite($fp, implode(',', $fields));
4612 fwrite($fp, "\r\n");
4614 foreach($records as $record) {
4615 $array = (array)$record;
4616 $values = array();
4617 foreach($fields as $field) {
4618 if(strpos($array[$field], ',')) {
4619 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
4621 else {
4622 $values[] = $array[$field];
4625 fwrite($fp, implode(',', $values)."\r\n");
4628 fclose($fp);
4629 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
4630 return true;
4634 * Determines if the given value is a valid CSS colour.
4636 * A CSS colour can be one of the following:
4637 * - Hex colour: #AA66BB
4638 * - RGB colour: rgb(0-255, 0-255, 0-255)
4639 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
4640 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
4641 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
4643 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
4645 * @deprecated since Moodle 3.2
4646 * @todo MDL-56173 for final deprecation in Moodle 3.6
4647 * @param string $value The colour value to check
4648 * @return bool
4650 function css_is_colour($value) {
4651 debugging('css_is_colour() is deprecated without a replacement. Please copy the implementation '.
4652 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4654 $value = trim($value);
4656 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
4657 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
4658 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4659 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
4660 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4662 if (in_array(strtolower($value), array('inherit'))) {
4663 return true;
4664 } else if (preg_match($hex, $value)) {
4665 return true;
4666 } else if (in_array(strtolower($value), array_keys(css_optimiser::$htmlcolours))) {
4667 return true;
4668 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4669 // It is an RGB colour.
4670 return true;
4671 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4672 // It is an RGBA colour.
4673 return true;
4674 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4675 // It is an HSL colour.
4676 return true;
4677 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4678 // It is an HSLA colour.
4679 return true;
4681 // Doesn't look like a colour.
4682 return false;
4686 * Returns true is the passed value looks like a CSS width.
4687 * In order to pass this test the value must be purely numerical or end with a
4688 * valid CSS unit term.
4690 * @param string|int $value
4691 * @return boolean
4692 * @deprecated since Moodle 3.2
4693 * @todo MDL-56173 for final deprecation in Moodle 3.6
4695 function css_is_width($value) {
4696 debugging('css_is_width() is deprecated without a replacement. Please copy the implementation '.
4697 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4699 $value = trim($value);
4700 if (in_array(strtolower($value), array('auto', 'inherit'))) {
4701 return true;
4703 if ((string)$value === '0' || preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
4704 return true;
4706 return false;
4710 * A simple sorting function to sort two array values on the number of items they contain
4712 * @param array $a
4713 * @param array $b
4714 * @return int
4715 * @deprecated since Moodle 3.2
4716 * @todo MDL-56173 for final deprecation in Moodle 3.6
4718 function css_sort_by_count(array $a, array $b) {
4719 debugging('css_sort_by_count() is deprecated without a replacement. Please copy the implementation '.
4720 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4722 $a = count($a);
4723 $b = count($b);
4724 if ($a == $b) {
4725 return 0;
4727 return ($a > $b) ? -1 : 1;
4731 * A basic CSS optimiser that strips out unwanted things and then processes CSS organising and cleaning styles.
4732 * @deprecated since Moodle 3.2
4733 * @todo MDL-56173 for final deprecation in Moodle 3.6
4735 class css_optimiser {
4737 * An array of the common HTML colours that are supported by most browsers.
4739 * This reference table is used to allow us to unify colours, and will aid
4740 * us in identifying buggy CSS using unsupported colours.
4742 * @var string[]
4743 * @deprecated since Moodle 3.2
4744 * @todo MDL-56173 for final deprecation in Moodle 3.6
4746 public static $htmlcolours = array(
4747 'aliceblue' => '#F0F8FF',
4748 'antiquewhite' => '#FAEBD7',
4749 'aqua' => '#00FFFF',
4750 'aquamarine' => '#7FFFD4',
4751 'azure' => '#F0FFFF',
4752 'beige' => '#F5F5DC',
4753 'bisque' => '#FFE4C4',
4754 'black' => '#000000',
4755 'blanchedalmond' => '#FFEBCD',
4756 'blue' => '#0000FF',
4757 'blueviolet' => '#8A2BE2',
4758 'brown' => '#A52A2A',
4759 'burlywood' => '#DEB887',
4760 'cadetblue' => '#5F9EA0',
4761 'chartreuse' => '#7FFF00',
4762 'chocolate' => '#D2691E',
4763 'coral' => '#FF7F50',
4764 'cornflowerblue' => '#6495ED',
4765 'cornsilk' => '#FFF8DC',
4766 'crimson' => '#DC143C',
4767 'cyan' => '#00FFFF',
4768 'darkblue' => '#00008B',
4769 'darkcyan' => '#008B8B',
4770 'darkgoldenrod' => '#B8860B',
4771 'darkgray' => '#A9A9A9',
4772 'darkgrey' => '#A9A9A9',
4773 'darkgreen' => '#006400',
4774 'darkKhaki' => '#BDB76B',
4775 'darkmagenta' => '#8B008B',
4776 'darkolivegreen' => '#556B2F',
4777 'arkorange' => '#FF8C00',
4778 'darkorchid' => '#9932CC',
4779 'darkred' => '#8B0000',
4780 'darksalmon' => '#E9967A',
4781 'darkseagreen' => '#8FBC8F',
4782 'darkslateblue' => '#483D8B',
4783 'darkslategray' => '#2F4F4F',
4784 'darkslategrey' => '#2F4F4F',
4785 'darkturquoise' => '#00CED1',
4786 'darkviolet' => '#9400D3',
4787 'deeppink' => '#FF1493',
4788 'deepskyblue' => '#00BFFF',
4789 'dimgray' => '#696969',
4790 'dimgrey' => '#696969',
4791 'dodgerblue' => '#1E90FF',
4792 'firebrick' => '#B22222',
4793 'floralwhite' => '#FFFAF0',
4794 'forestgreen' => '#228B22',
4795 'fuchsia' => '#FF00FF',
4796 'gainsboro' => '#DCDCDC',
4797 'ghostwhite' => '#F8F8FF',
4798 'gold' => '#FFD700',
4799 'goldenrod' => '#DAA520',
4800 'gray' => '#808080',
4801 'grey' => '#808080',
4802 'green' => '#008000',
4803 'greenyellow' => '#ADFF2F',
4804 'honeydew' => '#F0FFF0',
4805 'hotpink' => '#FF69B4',
4806 'indianred ' => '#CD5C5C',
4807 'indigo ' => '#4B0082',
4808 'ivory' => '#FFFFF0',
4809 'khaki' => '#F0E68C',
4810 'lavender' => '#E6E6FA',
4811 'lavenderblush' => '#FFF0F5',
4812 'lawngreen' => '#7CFC00',
4813 'lemonchiffon' => '#FFFACD',
4814 'lightblue' => '#ADD8E6',
4815 'lightcoral' => '#F08080',
4816 'lightcyan' => '#E0FFFF',
4817 'lightgoldenrodyellow' => '#FAFAD2',
4818 'lightgray' => '#D3D3D3',
4819 'lightgrey' => '#D3D3D3',
4820 'lightgreen' => '#90EE90',
4821 'lightpink' => '#FFB6C1',
4822 'lightsalmon' => '#FFA07A',
4823 'lightseagreen' => '#20B2AA',
4824 'lightskyblue' => '#87CEFA',
4825 'lightslategray' => '#778899',
4826 'lightslategrey' => '#778899',
4827 'lightsteelblue' => '#B0C4DE',
4828 'lightyellow' => '#FFFFE0',
4829 'lime' => '#00FF00',
4830 'limegreen' => '#32CD32',
4831 'linen' => '#FAF0E6',
4832 'magenta' => '#FF00FF',
4833 'maroon' => '#800000',
4834 'mediumaquamarine' => '#66CDAA',
4835 'mediumblue' => '#0000CD',
4836 'mediumorchid' => '#BA55D3',
4837 'mediumpurple' => '#9370D8',
4838 'mediumseagreen' => '#3CB371',
4839 'mediumslateblue' => '#7B68EE',
4840 'mediumspringgreen' => '#00FA9A',
4841 'mediumturquoise' => '#48D1CC',
4842 'mediumvioletred' => '#C71585',
4843 'midnightblue' => '#191970',
4844 'mintcream' => '#F5FFFA',
4845 'mistyrose' => '#FFE4E1',
4846 'moccasin' => '#FFE4B5',
4847 'navajowhite' => '#FFDEAD',
4848 'navy' => '#000080',
4849 'oldlace' => '#FDF5E6',
4850 'olive' => '#808000',
4851 'olivedrab' => '#6B8E23',
4852 'orange' => '#FFA500',
4853 'orangered' => '#FF4500',
4854 'orchid' => '#DA70D6',
4855 'palegoldenrod' => '#EEE8AA',
4856 'palegreen' => '#98FB98',
4857 'paleturquoise' => '#AFEEEE',
4858 'palevioletred' => '#D87093',
4859 'papayawhip' => '#FFEFD5',
4860 'peachpuff' => '#FFDAB9',
4861 'peru' => '#CD853F',
4862 'pink' => '#FFC0CB',
4863 'plum' => '#DDA0DD',
4864 'powderblue' => '#B0E0E6',
4865 'purple' => '#800080',
4866 'red' => '#FF0000',
4867 'rosybrown' => '#BC8F8F',
4868 'royalblue' => '#4169E1',
4869 'saddlebrown' => '#8B4513',
4870 'salmon' => '#FA8072',
4871 'sandybrown' => '#F4A460',
4872 'seagreen' => '#2E8B57',
4873 'seashell' => '#FFF5EE',
4874 'sienna' => '#A0522D',
4875 'silver' => '#C0C0C0',
4876 'skyblue' => '#87CEEB',
4877 'slateblue' => '#6A5ACD',
4878 'slategray' => '#708090',
4879 'slategrey' => '#708090',
4880 'snow' => '#FFFAFA',
4881 'springgreen' => '#00FF7F',
4882 'steelblue' => '#4682B4',
4883 'tan' => '#D2B48C',
4884 'teal' => '#008080',
4885 'thistle' => '#D8BFD8',
4886 'tomato' => '#FF6347',
4887 'transparent' => 'transparent',
4888 'turquoise' => '#40E0D0',
4889 'violet' => '#EE82EE',
4890 'wheat' => '#F5DEB3',
4891 'white' => '#FFFFFF',
4892 'whitesmoke' => '#F5F5F5',
4893 'yellow' => '#FFFF00',
4894 'yellowgreen' => '#9ACD32'
4898 * Used to orocesses incoming CSS optimising it and then returning it. Now just returns
4899 * what is sent to it. Do not use.
4901 * @param string $css The raw CSS to optimise
4902 * @return string The optimised CSS
4903 * @deprecated since Moodle 3.2
4904 * @todo MDL-56173 for final deprecation in Moodle 3.6
4906 public function process($css) {
4907 debugging('class css_optimiser is deprecated and no longer does anything, '.
4908 'please consider using stylelint to optimise your css.', DEBUG_DEVELOPER);
4910 return $css;
4915 * Load the course contexts for all of the users courses
4917 * @deprecated since Moodle 3.2
4918 * @param array $courses array of course objects. The courses the user is enrolled in.
4919 * @return array of course contexts
4921 function message_get_course_contexts($courses) {
4922 debugging('message_get_course_contexts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4924 $coursecontexts = array();
4926 foreach($courses as $course) {
4927 $coursecontexts[$course->id] = context_course::instance($course->id);
4930 return $coursecontexts;
4934 * strip off action parameters like 'removecontact'
4936 * @deprecated since Moodle 3.2
4937 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
4938 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
4940 function message_remove_url_params($moodleurl) {
4941 debugging('message_remove_url_params() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4943 $newurl = new moodle_url($moodleurl);
4944 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
4945 return $newurl->out();
4949 * Count the number of messages with a field having a specified value.
4950 * if $field is empty then return count of the whole array
4951 * if $field is non-existent then return 0
4953 * @deprecated since Moodle 3.2
4954 * @param array $messagearray array of message objects
4955 * @param string $field the field to inspect on the message objects
4956 * @param string $value the value to test the field against
4958 function message_count_messages($messagearray, $field='', $value='') {
4959 debugging('message_count_messages() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4961 if (!is_array($messagearray)) return 0;
4962 if ($field == '' or empty($messagearray)) return count($messagearray);
4964 $count = 0;
4965 foreach ($messagearray as $message) {
4966 $count += ($message->$field == $value) ? 1 : 0;
4968 return $count;
4972 * Count the number of users blocked by $user1
4974 * @deprecated since Moodle 3.2
4975 * @param object $user1 user object
4976 * @return int the number of blocked users
4978 function message_count_blocked_users($user1=null) {
4979 debugging('message_count_blocked_users() is deprecated, please use \core_message\api::count_blocked_users() instead.',
4980 DEBUG_DEVELOPER);
4982 return \core_message\api::count_blocked_users($user1);
4986 * Print a message contact link
4988 * @deprecated since Moodle 3.2
4989 * @param int $userid the ID of the user to apply to action to
4990 * @param string $linktype can be add, remove, block or unblock
4991 * @param bool $return if true return the link as a string. If false echo the link.
4992 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4993 * @param bool $text include text next to the icons?
4994 * @param bool $icon include a graphical icon?
4995 * @return string if $return is true otherwise bool
4997 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
4998 debugging('message_contact_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5000 global $OUTPUT, $PAGE;
5002 //hold onto the strings as we're probably creating a bunch of links
5003 static $str;
5005 if (empty($script)) {
5006 //strip off previous action params like 'removecontact'
5007 $script = message_remove_url_params($PAGE->url);
5010 if (empty($str->blockcontact)) {
5011 $str = new stdClass();
5012 $str->blockcontact = get_string('blockcontact', 'message');
5013 $str->unblockcontact = get_string('unblockcontact', 'message');
5014 $str->removecontact = get_string('removecontact', 'message');
5015 $str->addcontact = get_string('addcontact', 'message');
5018 $command = $linktype.'contact';
5019 $string = $str->{$command};
5021 $safealttext = s($string);
5023 $safestring = '';
5024 if (!empty($text)) {
5025 $safestring = $safealttext;
5028 $img = '';
5029 if ($icon) {
5030 $iconpath = null;
5031 switch ($linktype) {
5032 case 'block':
5033 $iconpath = 't/block';
5034 break;
5035 case 'unblock':
5036 $iconpath = 't/unblock';
5037 break;
5038 case 'remove':
5039 $iconpath = 't/removecontact';
5040 break;
5041 case 'add':
5042 default:
5043 $iconpath = 't/addcontact';
5046 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
5049 $output = '<span class="'.$linktype.'contact">'.
5050 '<a href="'.$script.'&amp;'.$command.'='.$userid.
5051 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
5052 $img.
5053 $safestring.'</a></span>';
5055 if ($return) {
5056 return $output;
5057 } else {
5058 echo $output;
5059 return true;
5064 * Get the users recent event notifications
5066 * @deprecated since Moodle 3.2
5067 * @param object $user the current user
5068 * @param int $limitfrom can be used for paging
5069 * @param int $limitto can be used for paging
5070 * @return array
5072 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
5073 debugging('message_get_recent_notifications() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5075 global $DB;
5077 $userfields = user_picture::fields('u', array('lastaccess'));
5078 $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
5079 FROM {message_read} mr
5080 JOIN {user} u ON u.id=mr.useridfrom
5081 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
5082 ORDER BY mr.timecreated DESC";
5083 $params = array('userid1' => $user->id, 'notification' => 1);
5085 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
5086 return $notifications;
5090 * echo or return a link to take the user to the full message history between themselves and another user
5092 * @deprecated since Moodle 3.2
5093 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
5094 * @param int $userid2 the ID of the other user
5095 * @param bool $return true to return the link as a string. False to echo the link.
5096 * @param string $keywords any keywords to highlight in the message history
5097 * @param string $position anchor name to jump to within the message history
5098 * @param string $linktext optionally specify the link text
5099 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
5101 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
5102 debugging('message_history_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5104 global $OUTPUT, $PAGE;
5105 static $strmessagehistory;
5107 if (empty($strmessagehistory)) {
5108 $strmessagehistory = get_string('messagehistory', 'message');
5111 if ($position) {
5112 $position = "#$position";
5114 if ($keywords) {
5115 $keywords = "&search=".urlencode($keywords);
5118 if ($linktext == 'icon') { // Icon only
5119 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
5120 } else if ($linktext == 'both') { // Icon and standard name
5121 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
5122 $fulllink .= '&nbsp;'.$strmessagehistory;
5123 } else if ($linktext) { // Custom name
5124 $fulllink = $linktext;
5125 } else { // Standard name only
5126 $fulllink = $strmessagehistory;
5129 $popupoptions = array(
5130 'height' => 500,
5131 'width' => 500,
5132 'menubar' => false,
5133 'location' => false,
5134 'status' => true,
5135 'scrollbars' => true,
5136 'resizable' => true);
5138 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
5139 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
5140 $link->param('viewing', $PAGE->url->get_param('viewing'));
5142 $action = null;
5143 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
5145 $str = '<span class="history">'.$str.'</span>';
5147 if ($return) {
5148 return $str;
5149 } else {
5150 echo $str;
5151 return true;
5156 * Search a user's messages
5158 * Returns a list of posts found using an array of search terms
5159 * eg word +word -word
5161 * @deprecated since Moodle 3.2
5162 * @param array $searchterms an array of search terms (strings)
5163 * @param bool $fromme include messages from the user?
5164 * @param bool $tome include messages to the user?
5165 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
5166 * @param int $userid the user ID of the current user
5167 * @return mixed An array of messages or false if no matching messages were found
5169 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
5170 debugging('message_search() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5172 global $CFG, $USER, $DB;
5174 // If user is searching all messages check they are allowed to before doing anything else.
5175 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
5176 print_error('accessdenied','admin');
5179 // If no userid sent then assume current user.
5180 if ($userid == 0) $userid = $USER->id;
5182 // Some differences in SQL syntax.
5183 if ($DB->sql_regex_supported()) {
5184 $REGEXP = $DB->sql_regex(true);
5185 $NOTREGEXP = $DB->sql_regex(false);
5188 $searchcond = array();
5189 $params = array();
5190 $i = 0;
5192 // Preprocess search terms to check whether we have at least 1 eligible search term.
5193 // If we do we can drop words around it like 'a'.
5194 $dropshortwords = false;
5195 foreach ($searchterms as $searchterm) {
5196 if (strlen($searchterm) >= 2) {
5197 $dropshortwords = true;
5201 foreach ($searchterms as $searchterm) {
5202 $i++;
5204 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
5206 if ($dropshortwords && strlen($searchterm) < 2) {
5207 continue;
5209 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
5210 if (!$DB->sql_regex_supported()) {
5211 if (substr($searchterm, 0, 1) == '-') {
5212 $NOT = true;
5214 $searchterm = trim($searchterm, '+-');
5217 if (substr($searchterm,0,1) == "+") {
5218 $searchterm = substr($searchterm,1);
5219 $searchterm = preg_quote($searchterm, '|');
5220 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
5221 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
5223 } else if (substr($searchterm,0,1) == "-") {
5224 $searchterm = substr($searchterm,1);
5225 $searchterm = preg_quote($searchterm, '|');
5226 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
5227 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
5229 } else {
5230 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
5231 $params['ss'.$i] = "%$searchterm%";
5235 if (empty($searchcond)) {
5236 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
5237 $params['ss1'] = "%";
5238 } else {
5239 $searchcond = implode(" AND ", $searchcond);
5242 // There are several possibilities
5243 // 1. courseid = SITEID : The admin is searching messages by all users
5244 // 2. courseid = ?? : A teacher is searching messages by users in
5245 // one of their courses - currently disabled
5246 // 3. courseid = none : User is searching their own messages;
5247 // a. Messages from user
5248 // b. Messages to user
5249 // c. Messages to and from user
5251 if ($fromme && $tome) {
5252 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
5253 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
5254 $params['useridto'] = $userid;
5255 $params['useridfrom'] = $userid;
5256 } else if ($fromme) {
5257 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
5258 $params['useridfrom'] = $userid;
5259 } else if ($tome) {
5260 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
5261 $params['useridto'] = $userid;
5263 if ($courseid == SITEID) { // Admin is searching all messages.
5264 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
5265 FROM {message_read} m
5266 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
5267 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
5268 FROM {message} m
5269 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
5271 } else if ($courseid !== 'none') {
5272 // This has not been implemented due to security concerns.
5273 $m_read = array();
5274 $m_unread = array();
5276 } else {
5278 if ($fromme and $tome) {
5279 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
5280 $params['userid1'] = $userid;
5281 $params['userid2'] = $userid;
5283 } else if ($fromme) {
5284 $searchcond .= " AND m.useridfrom=:userid";
5285 $params['userid'] = $userid;
5287 } else if ($tome) {
5288 $searchcond .= " AND m.useridto=:userid";
5289 $params['userid'] = $userid;
5292 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
5293 FROM {message_read} m
5294 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
5295 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
5296 FROM {message} m
5297 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
5301 /// The keys may be duplicated in $m_read and $m_unread so we can't
5302 /// do a simple concatenation
5303 $messages = array();
5304 foreach ($m_read as $m) {
5305 $messages[] = $m;
5307 foreach ($m_unread as $m) {
5308 $messages[] = $m;
5311 return (empty($messages)) ? false : $messages;
5315 * Given a message object that we already know has a long message
5316 * this function truncates the message nicely to the first
5317 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
5319 * @deprecated since Moodle 3.2
5320 * @param string $message the message
5321 * @param int $minlength the minimum length to trim the message to
5322 * @return string the shortened message
5324 function message_shorten_message($message, $minlength = 0) {
5325 debugging('message_shorten_message() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5327 $i = 0;
5328 $tag = false;
5329 $length = strlen($message);
5330 $count = 0;
5331 $stopzone = false;
5332 $truncate = 0;
5333 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
5336 for ($i=0; $i<$length; $i++) {
5337 $char = $message[$i];
5339 switch ($char) {
5340 case "<":
5341 $tag = true;
5342 break;
5343 case ">":
5344 $tag = false;
5345 break;
5346 default:
5347 if (!$tag) {
5348 if ($stopzone) {
5349 if ($char == '.' or $char == ' ') {
5350 $truncate = $i+1;
5351 break 2;
5354 $count++;
5356 break;
5358 if (!$stopzone) {
5359 if ($count > $minlength) {
5360 $stopzone = true;
5365 if (!$truncate) {
5366 $truncate = $i;
5369 return substr($message, 0, $truncate);
5373 * Given a string and an array of keywords, this function looks
5374 * for the first keyword in the string, and then chops out a
5375 * small section from the text that shows that word in context.
5377 * @deprecated since Moodle 3.2
5378 * @param string $message the text to search
5379 * @param array $keywords array of keywords to find
5381 function message_get_fragment($message, $keywords) {
5382 debugging('message_get_fragment() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5384 $fullsize = 160;
5385 $halfsize = (int)($fullsize/2);
5387 $message = strip_tags($message);
5389 foreach ($keywords as $keyword) { // Just get the first one
5390 if ($keyword !== '') {
5391 break;
5394 if (empty($keyword)) { // None found, so just return start of message
5395 return message_shorten_message($message, 30);
5398 $leadin = $leadout = '';
5400 /// Find the start of the fragment
5401 $start = 0;
5402 $length = strlen($message);
5404 $pos = strpos($message, $keyword);
5405 if ($pos > $halfsize) {
5406 $start = $pos - $halfsize;
5407 $leadin = '...';
5409 /// Find the end of the fragment
5410 $end = $start + $fullsize;
5411 if ($end > $length) {
5412 $end = $length;
5413 } else {
5414 $leadout = '...';
5417 /// Pull out the fragment and format it
5419 $fragment = substr($message, $start, $end - $start);
5420 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
5421 return $fragment;
5425 * Retrieve the messages between two users
5427 * @deprecated since Moodle 3.2
5428 * @param object $user1 the current user
5429 * @param object $user2 the other user
5430 * @param int $limitnum the maximum number of messages to retrieve
5431 * @param bool $viewingnewmessages are we currently viewing new messages?
5433 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
5434 debugging('message_get_history() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5436 global $DB, $CFG;
5438 $messages = array();
5440 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
5441 //desc to get the last $limitnum messages then flip the order in php
5442 $sort = 'asc';
5443 if ($limitnum>0) {
5444 $sort = 'desc';
5447 $notificationswhere = null;
5448 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
5449 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
5450 $notificationswhere = 'AND notification=0';
5453 //prevent notifications of your own actions appearing in your own message history
5454 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
5456 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
5457 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
5458 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
5459 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
5460 "timecreated $sort", '*', 0, $limitnum)) {
5461 foreach ($messages_read as $message) {
5462 $messages[] = $message;
5465 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
5466 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
5467 "timecreated $sort", '*', 0, $limitnum)) {
5468 foreach ($messages_new as $message) {
5469 $messages[] = $message;
5473 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
5475 //if we only want the last $limitnum messages
5476 $messagecount = count($messages);
5477 if ($limitnum > 0 && $messagecount > $limitnum) {
5478 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
5481 return $messages;
5485 * Constructs the add/remove contact link to display next to other users
5487 * @deprecated since Moodle 3.2
5488 * @param bool $incontactlist is the user a contact
5489 * @param bool $isblocked is the user blocked
5490 * @param stdClass $contact contact object
5491 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5492 * @param bool $text include text next to the icons?
5493 * @param bool $icon include a graphical icon?
5494 * @return string
5496 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5497 debugging('message_get_contact_add_remove_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5499 $strcontact = '';
5501 if($incontactlist){
5502 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
5503 } else if ($isblocked) {
5504 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
5505 } else{
5506 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
5509 return $strcontact;
5513 * Constructs the block contact link to display next to other users
5515 * @deprecated since Moodle 3.2
5516 * @param bool $incontactlist is the user a contact?
5517 * @param bool $isblocked is the user blocked?
5518 * @param stdClass $contact contact object
5519 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
5520 * @param bool $text include text next to the icons?
5521 * @param bool $icon include a graphical icon?
5522 * @return string
5524 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
5525 debugging('message_get_contact_block_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5527 $strblock = '';
5529 //commented out to allow the user to block a contact without having to remove them first
5530 /*if ($incontactlist) {
5531 //$strblock = '';
5532 } else*/
5533 if ($isblocked) {
5534 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
5535 } else{
5536 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
5539 return $strblock;
5543 * marks ALL messages being sent from $fromuserid to $touserid as read
5545 * @deprecated since Moodle 3.2
5546 * @param int $touserid the id of the message recipient
5547 * @param int $fromuserid the id of the message sender
5548 * @return void
5550 function message_mark_messages_read($touserid, $fromuserid) {
5551 debugging('message_mark_messages_read() is deprecated and is no longer used, please use
5552 \core_message\api::mark_all_read_for_user() instead.', DEBUG_DEVELOPER);
5554 \core_message\api::mark_all_read_for_user($touserid, $fromuserid);
5558 * Return a list of page types
5560 * @deprecated since Moodle 3.2
5561 * @param string $pagetype current page type
5562 * @param stdClass $parentcontext Block's parent context
5563 * @param stdClass $currentcontext Current context of block
5565 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
5566 debugging('message_page_type_list() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5568 return array('messages-*'=>get_string('page-message-x', 'message'));
5572 * Determines if a user is permitted to send another user a private message.
5573 * If no sender is provided then it defaults to the logged in user.
5575 * @deprecated since Moodle 3.2
5576 * @param object $recipient User object.
5577 * @param object $sender User object.
5578 * @return bool true if user is permitted, false otherwise.
5580 function message_can_post_message($recipient, $sender = null) {
5581 debugging('message_can_post_message() is deprecated and is no longer used, please use
5582 \core_message\api::can_post_message() instead.', DEBUG_DEVELOPER);
5584 return \core_message\api::can_post_message($recipient, $sender);
5588 * Checks if the recipient is allowing messages from users that aren't a
5589 * contact. If not then it checks to make sure the sender is in the
5590 * recipient's contacts.
5592 * @deprecated since Moodle 3.2
5593 * @param object $recipient User object.
5594 * @param object $sender User object.
5595 * @return bool true if $sender is blocked, false otherwise.
5597 function message_is_user_non_contact_blocked($recipient, $sender = null) {
5598 debugging('message_is_user_non_contact_blocked() is deprecated and is no longer used, please use
5599 \core_message\api::is_user_non_contact_blocked() instead.', DEBUG_DEVELOPER);
5601 return \core_message\api::is_user_non_contact_blocked($recipient, $sender);
5605 * Checks if the recipient has specifically blocked the sending user.
5607 * Note: This function will always return false if the sender has the
5608 * readallmessages capability at the system context level.
5610 * @deprecated since Moodle 3.2
5611 * @param object $recipient User object.
5612 * @param object $sender User object.
5613 * @return bool true if $sender is blocked, false otherwise.
5615 function message_is_user_blocked($recipient, $sender = null) {
5616 debugging('message_is_user_blocked() is deprecated and is no longer used, please use
5617 \core_message\api::is_user_blocked() instead.', DEBUG_DEVELOPER);
5619 return \core_message\api::is_user_blocked($recipient, $sender);
5623 * Display logs.
5625 * @deprecated since 3.2
5627 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5628 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5629 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5631 global $CFG, $DB, $OUTPUT;
5633 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
5634 $modname, $modid, $modaction, $groupid)) {
5635 echo $OUTPUT->notification("No logs found!");
5636 echo $OUTPUT->footer();
5637 exit;
5640 $courses = array();
5642 if ($course->id == SITEID) {
5643 $courses[0] = '';
5644 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5645 foreach ($ccc as $cc) {
5646 $courses[$cc->id] = $cc->shortname;
5649 } else {
5650 $courses[$course->id] = $course->shortname;
5653 $totalcount = $logs['totalcount'];
5654 $ldcache = array();
5656 $strftimedatetime = get_string("strftimedatetime");
5658 echo "<div class=\"info\">\n";
5659 print_string("displayingrecords", "", $totalcount);
5660 echo "</div>\n";
5662 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5664 $table = new html_table();
5665 $table->classes = array('logtable','generaltable');
5666 $table->align = array('right', 'left', 'left');
5667 $table->head = array(
5668 get_string('time'),
5669 get_string('ip_address'),
5670 get_string('fullnameuser'),
5671 get_string('action'),
5672 get_string('info')
5674 $table->data = array();
5676 if ($course->id == SITEID) {
5677 array_unshift($table->align, 'left');
5678 array_unshift($table->head, get_string('course'));
5681 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
5682 if (empty($logs['logs'])) {
5683 $logs['logs'] = array();
5686 foreach ($logs['logs'] as $log) {
5688 if (isset($ldcache[$log->module][$log->action])) {
5689 $ld = $ldcache[$log->module][$log->action];
5690 } else {
5691 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5692 $ldcache[$log->module][$log->action] = $ld;
5694 if ($ld && is_numeric($log->info)) {
5695 // ugly hack to make sure fullname is shown correctly
5696 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
5697 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5698 } else {
5699 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5703 //Filter log->info
5704 $log->info = format_string($log->info);
5706 // If $log->url has been trimmed short by the db size restriction
5707 // code in add_to_log, keep a note so we don't add a link to a broken url
5708 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
5710 $row = array();
5711 if ($course->id == SITEID) {
5712 if (empty($log->course)) {
5713 $row[] = get_string('site');
5714 } else {
5715 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
5719 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
5721 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5722 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
5724 $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))));
5726 $displayaction="$log->module $log->action";
5727 if ($brokenurl) {
5728 $row[] = $displayaction;
5729 } else {
5730 $link = make_log_url($log->module,$log->url);
5731 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
5733 $row[] = $log->info;
5734 $table->data[] = $row;
5737 echo html_writer::table($table);
5738 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5742 * Display MNET logs.
5744 * @deprecated since 3.2
5746 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5747 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5748 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5750 global $CFG, $DB, $OUTPUT;
5752 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
5753 $modname, $modid, $modaction, $groupid)) {
5754 echo $OUTPUT->notification("No logs found!");
5755 echo $OUTPUT->footer();
5756 exit;
5759 if ($course->id == SITEID) {
5760 $courses[0] = '';
5761 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
5762 foreach ($ccc as $cc) {
5763 $courses[$cc->id] = $cc->shortname;
5768 $totalcount = $logs['totalcount'];
5769 $ldcache = array();
5771 $strftimedatetime = get_string("strftimedatetime");
5773 echo "<div class=\"info\">\n";
5774 print_string("displayingrecords", "", $totalcount);
5775 echo "</div>\n";
5777 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5779 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
5780 echo "<tr>";
5781 if ($course->id == SITEID) {
5782 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
5784 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
5785 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
5786 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
5787 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
5788 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
5789 echo "</tr>\n";
5791 if (empty($logs['logs'])) {
5792 echo "</table>\n";
5793 return;
5796 $row = 1;
5797 foreach ($logs['logs'] as $log) {
5799 $log->info = $log->coursename;
5800 $row = ($row + 1) % 2;
5802 if (isset($ldcache[$log->module][$log->action])) {
5803 $ld = $ldcache[$log->module][$log->action];
5804 } else {
5805 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5806 $ldcache[$log->module][$log->action] = $ld;
5808 if (0 && $ld && !empty($log->info)) {
5809 // ugly hack to make sure fullname is shown correctly
5810 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5811 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5812 } else {
5813 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5817 //Filter log->info
5818 $log->info = format_string($log->info);
5820 echo '<tr class="r'.$row.'">';
5821 if ($course->id == SITEID) {
5822 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
5823 echo "<td class=\"r$row c0\" >\n";
5824 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
5825 echo "</td>\n";
5827 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
5828 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
5829 echo "<td class=\"r$row c2\" >\n";
5830 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5831 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
5832 echo "</td>\n";
5833 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
5834 echo "<td class=\"r$row c3\" >\n";
5835 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
5836 echo "</td>\n";
5837 echo "<td class=\"r$row c4\">\n";
5838 echo $log->action .': '.$log->module;
5839 echo "</td>\n";
5840 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
5841 echo "</tr>\n";
5843 echo "</table>\n";
5845 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5849 * Display logs in CSV format.
5851 * @deprecated since 3.2
5853 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
5854 $modid, $modaction, $groupid) {
5855 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5857 global $DB, $CFG;
5859 require_once($CFG->libdir . '/csvlib.class.php');
5861 $csvexporter = new csv_export_writer('tab');
5863 $header = array();
5864 $header[] = get_string('course');
5865 $header[] = get_string('time');
5866 $header[] = get_string('ip_address');
5867 $header[] = get_string('fullnameuser');
5868 $header[] = get_string('action');
5869 $header[] = get_string('info');
5871 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5872 $modname, $modid, $modaction, $groupid)) {
5873 return false;
5876 $courses = array();
5878 if ($course->id == SITEID) {
5879 $courses[0] = '';
5880 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5881 foreach ($ccc as $cc) {
5882 $courses[$cc->id] = $cc->shortname;
5885 } else {
5886 $courses[$course->id] = $course->shortname;
5889 $count=0;
5890 $ldcache = array();
5891 $tt = getdate(time());
5892 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5894 $strftimedatetime = get_string("strftimedatetime");
5896 $csvexporter->set_filename('logs', '.txt');
5897 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
5898 $csvexporter->add_data($title);
5899 $csvexporter->add_data($header);
5901 if (empty($logs['logs'])) {
5902 return true;
5905 foreach ($logs['logs'] as $log) {
5906 if (isset($ldcache[$log->module][$log->action])) {
5907 $ld = $ldcache[$log->module][$log->action];
5908 } else {
5909 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5910 $ldcache[$log->module][$log->action] = $ld;
5912 if ($ld && is_numeric($log->info)) {
5913 // ugly hack to make sure fullname is shown correctly
5914 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5915 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5916 } else {
5917 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5921 //Filter log->info
5922 $log->info = format_string($log->info);
5923 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5925 $coursecontext = context_course::instance($course->id);
5926 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
5927 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5928 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5929 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
5930 $csvexporter->add_data($row);
5932 $csvexporter->download_file();
5933 return true;
5937 * Display logs in XLS format.
5939 * @deprecated since 3.2
5941 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
5942 $modid, $modaction, $groupid) {
5943 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5945 global $CFG, $DB;
5947 require_once("$CFG->libdir/excellib.class.php");
5949 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5950 $modname, $modid, $modaction, $groupid)) {
5951 return false;
5954 $courses = array();
5956 if ($course->id == SITEID) {
5957 $courses[0] = '';
5958 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5959 foreach ($ccc as $cc) {
5960 $courses[$cc->id] = $cc->shortname;
5963 } else {
5964 $courses[$course->id] = $course->shortname;
5967 $count=0;
5968 $ldcache = array();
5969 $tt = getdate(time());
5970 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5972 $strftimedatetime = get_string("strftimedatetime");
5974 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5975 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5976 $filename .= '.xls';
5978 $workbook = new MoodleExcelWorkbook('-');
5979 $workbook->send($filename);
5981 $worksheet = array();
5982 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5983 get_string('fullnameuser'), get_string('action'), get_string('info'));
5985 // Creating worksheets
5986 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5987 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5988 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5989 $worksheet[$wsnumber]->set_column(1, 1, 30);
5990 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5991 userdate(time(), $strftimedatetime));
5992 $col = 0;
5993 foreach ($headers as $item) {
5994 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5995 $col++;
5999 if (empty($logs['logs'])) {
6000 $workbook->close();
6001 return true;
6004 $formatDate =& $workbook->add_format();
6005 $formatDate->set_num_format(get_string('log_excel_date_format'));
6007 $row = FIRSTUSEDEXCELROW;
6008 $wsnumber = 1;
6009 $myxls =& $worksheet[$wsnumber];
6010 foreach ($logs['logs'] as $log) {
6011 if (isset($ldcache[$log->module][$log->action])) {
6012 $ld = $ldcache[$log->module][$log->action];
6013 } else {
6014 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
6015 $ldcache[$log->module][$log->action] = $ld;
6017 if ($ld && is_numeric($log->info)) {
6018 // ugly hack to make sure fullname is shown correctly
6019 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
6020 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
6021 } else {
6022 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
6026 // Filter log->info
6027 $log->info = format_string($log->info);
6028 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
6030 if ($nroPages>1) {
6031 if ($row > EXCELROWS) {
6032 $wsnumber++;
6033 $myxls =& $worksheet[$wsnumber];
6034 $row = FIRSTUSEDEXCELROW;
6038 $coursecontext = context_course::instance($course->id);
6040 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
6041 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
6042 $myxls->write($row, 2, $log->ip, '');
6043 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
6044 $myxls->write($row, 3, $fullname, '');
6045 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
6046 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
6047 $myxls->write($row, 5, $log->info, '');
6049 $row++;
6052 $workbook->close();
6053 return true;
6057 * Display logs in ODS format.
6059 * @deprecated since 3.2
6061 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
6062 $modid, $modaction, $groupid) {
6063 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6065 global $CFG, $DB;
6067 require_once("$CFG->libdir/odslib.class.php");
6069 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
6070 $modname, $modid, $modaction, $groupid)) {
6071 return false;
6074 $courses = array();
6076 if ($course->id == SITEID) {
6077 $courses[0] = '';
6078 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
6079 foreach ($ccc as $cc) {
6080 $courses[$cc->id] = $cc->shortname;
6083 } else {
6084 $courses[$course->id] = $course->shortname;
6087 $ldcache = array();
6089 $strftimedatetime = get_string("strftimedatetime");
6091 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
6092 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
6093 $filename .= '.ods';
6095 $workbook = new MoodleODSWorkbook('-');
6096 $workbook->send($filename);
6098 $worksheet = array();
6099 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
6100 get_string('fullnameuser'), get_string('action'), get_string('info'));
6102 // Creating worksheets
6103 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
6104 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
6105 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
6106 $worksheet[$wsnumber]->set_column(1, 1, 30);
6107 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
6108 userdate(time(), $strftimedatetime));
6109 $col = 0;
6110 foreach ($headers as $item) {
6111 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
6112 $col++;
6116 if (empty($logs['logs'])) {
6117 $workbook->close();
6118 return true;
6121 $formatDate =& $workbook->add_format();
6122 $formatDate->set_num_format(get_string('log_excel_date_format'));
6124 $row = FIRSTUSEDEXCELROW;
6125 $wsnumber = 1;
6126 $myxls =& $worksheet[$wsnumber];
6127 foreach ($logs['logs'] as $log) {
6128 if (isset($ldcache[$log->module][$log->action])) {
6129 $ld = $ldcache[$log->module][$log->action];
6130 } else {
6131 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
6132 $ldcache[$log->module][$log->action] = $ld;
6134 if ($ld && is_numeric($log->info)) {
6135 // ugly hack to make sure fullname is shown correctly
6136 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
6137 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
6138 } else {
6139 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
6143 // Filter log->info
6144 $log->info = format_string($log->info);
6145 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
6147 if ($nroPages>1) {
6148 if ($row > EXCELROWS) {
6149 $wsnumber++;
6150 $myxls =& $worksheet[$wsnumber];
6151 $row = FIRSTUSEDEXCELROW;
6155 $coursecontext = context_course::instance($course->id);
6157 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
6158 $myxls->write_date($row, 1, $log->time);
6159 $myxls->write_string($row, 2, $log->ip);
6160 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
6161 $myxls->write_string($row, 3, $fullname);
6162 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
6163 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
6164 $myxls->write_string($row, 5, $log->info);
6166 $row++;
6169 $workbook->close();
6170 return true;
6174 * Build an array of logs.
6176 * @deprecated since 3.2
6178 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
6179 $modname="", $modid=0, $modaction="", $groupid=0) {
6180 global $DB, $SESSION, $USER;
6182 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6183 // It is assumed that $date is the GMT time of midnight for that day,
6184 // and so the next 86400 seconds worth of logs are printed.
6186 // Setup for group handling.
6188 // If the group mode is separate, and this user does not have editing privileges,
6189 // then only the user's group can be viewed.
6190 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
6191 if (isset($SESSION->currentgroup[$course->id])) {
6192 $groupid = $SESSION->currentgroup[$course->id];
6193 } else {
6194 $groupid = groups_get_all_groups($course->id, $USER->id);
6195 if (is_array($groupid)) {
6196 $groupid = array_shift(array_keys($groupid));
6197 $SESSION->currentgroup[$course->id] = $groupid;
6198 } else {
6199 $groupid = 0;
6203 // If this course doesn't have groups, no groupid can be specified.
6204 else if (!$course->groupmode) {
6205 $groupid = 0;
6208 $joins = array();
6209 $params = array();
6211 if ($course->id != SITEID || $modid != 0) {
6212 $joins[] = "l.course = :courseid";
6213 $params['courseid'] = $course->id;
6216 if ($modname) {
6217 $joins[] = "l.module = :modname";
6218 $params['modname'] = $modname;
6221 if ('site_errors' === $modid) {
6222 $joins[] = "( l.action='error' OR l.action='infected' )";
6223 } else if ($modid) {
6224 $joins[] = "l.cmid = :modid";
6225 $params['modid'] = $modid;
6228 if ($modaction) {
6229 $firstletter = substr($modaction, 0, 1);
6230 if ($firstletter == '-') {
6231 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
6232 $params['modaction'] = '%'.substr($modaction, 1).'%';
6233 } else {
6234 $joins[] = $DB->sql_like('l.action', ':modaction', false);
6235 $params['modaction'] = '%'.$modaction.'%';
6240 /// Getting all members of a group.
6241 if ($groupid and !$user) {
6242 if ($gusers = groups_get_members($groupid)) {
6243 $gusers = array_keys($gusers);
6244 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
6245 } else {
6246 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
6249 else if ($user) {
6250 $joins[] = "l.userid = :userid";
6251 $params['userid'] = $user;
6254 if ($date) {
6255 $enddate = $date + 86400;
6256 $joins[] = "l.time > :date AND l.time < :enddate";
6257 $params['date'] = $date;
6258 $params['enddate'] = $enddate;
6261 $selector = implode(' AND ', $joins);
6263 $totalcount = 0; // Initialise
6264 $result = array();
6265 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
6266 $result['totalcount'] = $totalcount;
6267 return $result;
6271 * Select all log records for a given course and user.
6273 * @deprecated since 3.2
6274 * @param int $userid The id of the user as found in the 'user' table.
6275 * @param int $courseid The id of the course as found in the 'course' table.
6276 * @param string $coursestart unix timestamp representing course start date and time.
6277 * @return array
6279 function get_logs_usercourse($userid, $courseid, $coursestart) {
6280 global $DB;
6282 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6284 $params = array();
6286 $courseselect = '';
6287 if ($courseid) {
6288 $courseselect = "AND course = :courseid";
6289 $params['courseid'] = $courseid;
6291 $params['userid'] = $userid;
6292 // We have to sanitize this param ourselves here instead of relying on DB.
6293 // Postgres complains if you use name parameter or column alias in GROUP BY.
6294 // See MDL-27696 and 51c3e85 for details.
6295 $coursestart = (int)$coursestart;
6297 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
6298 FROM {log}
6299 WHERE userid = :userid
6300 AND time > $coursestart $courseselect
6301 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
6305 * Select all log records for a given course, user, and day.
6307 * @deprecated since 3.2
6308 * @param int $userid The id of the user as found in the 'user' table.
6309 * @param int $courseid The id of the course as found in the 'course' table.
6310 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
6311 * @return array
6313 function get_logs_userday($userid, $courseid, $daystart) {
6314 global $DB;
6316 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6318 $params = array('userid'=>$userid);
6320 $courseselect = '';
6321 if ($courseid) {
6322 $courseselect = "AND course = :courseid";
6323 $params['courseid'] = $courseid;
6325 // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
6326 $daystart = (int) $daystart;
6328 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
6329 FROM {log}
6330 WHERE userid = :userid
6331 AND time > $daystart $courseselect
6332 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
6336 * Select all log records based on SQL criteria.
6338 * @deprecated since 3.2
6339 * @param string $select SQL select criteria
6340 * @param array $params named sql type params
6341 * @param string $order SQL order by clause to sort the records returned
6342 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
6343 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
6344 * @param int $totalcount Passed in by reference.
6345 * @return array
6347 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
6348 global $DB;
6350 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
6352 if ($order) {
6353 $order = "ORDER BY $order";
6356 if ($select) {
6357 $select = "WHERE $select";
6360 $sql = "SELECT COUNT(*)
6361 FROM {log} l
6362 $select";
6364 $totalcount = $DB->count_records_sql($sql, $params);
6365 $allnames = get_all_user_name_fields(true, 'u');
6366 $sql = "SELECT l.*, $allnames, u.picture
6367 FROM {log} l
6368 LEFT JOIN {user} u ON l.userid = u.id
6369 $select
6370 $order";
6372 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;