MDL-31794 theme_formalwhite: Fixed up tabs
[moodle.git] / tag / lib.php
blob2859162b61d8fb02b06c6ca119e780dc18091312
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Moodle tag library
21 * Tag strings : you can use any character in tags, except the comma (which is the separator) and
22 * the '\' (backslash). Note that many spaces (or other blank characters) will get "compressed"
23 * into one. A tag string is always a rawurlencode'd string. This is the same behavior as
24 * http://del.icio.us.
26 * A "record" is a php array (note that an object will work too) that contains the following
27 * variables :
28 * - type: The database table containing the record that we are tagging (eg: for a blog, this is
29 * the table named 'post', and for a user it is the table name 'user')
30 * - id: The id of the record
32 * BASIC INSTRUCTIONS :
33 * - to "tag a blog post" (for example):
34 * tag_set('post', $blog_post->id, $array_of_tags);
36 * - to "remove all the tags on a blog post":
37 * tag_set('post', $blog_post->id, array());
39 * Tag set will create tags that need to be created.
41 * @package core_tag
42 * @category tag
43 * @todo MDL-31090 turn this into a full-fledged categorization system. This could start by
44 * modifying (removing, probably) the 'tag type' to use another table describing the
45 * relationship between tags (parents, sibling, etc.), which could then be merged with
46 * the 'course categorization' system.
47 * @see http://www.php.net/manual/en/function.urlencode.php
48 * @copyright 2007 Luiz Cruz <luiz.laydner@gmail.com>
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 /**
53 * Used to require that the return value from a function is an array.
54 * @see tag_set()
56 define('TAG_RETURN_ARRAY', 0);
57 /**
58 * Used to require that the return value from a function is an object.
59 * @see tag_set()
61 define('TAG_RETURN_OBJECT', 1);
62 /**
63 * Use to specify that HTML free text is expected to be returned from a function.
64 * @see tag_display_name()
66 define('TAG_RETURN_TEXT', 2);
67 /**
68 * Use to specify that encoded HTML is expected to be returned from a function.
69 * @see tag_display_name()
71 define('TAG_RETURN_HTML', 3);
73 /**
74 * Used to specify that we wish a lowercased string to be returned
75 * @see tag_normal()
77 define('TAG_CASE_LOWER', 0);
78 /**
79 * Used to specify that we do not wish the case of the returned string to change
80 * @see tag_normal()
82 define('TAG_CASE_ORIGINAL', 1);
84 /**
85 * Used to specify that we want all related tags returned, no matter how they are related.
86 * @see tag_get_related_tags()
88 define('TAG_RELATED_ALL', 0);
89 /**
90 * Used to specify that we only want back tags that were manually related.
91 * @see tag_get_related_tags()
93 define('TAG_RELATED_MANUAL', 1);
94 /**
95 * Used to specify that we only want back tags where the relationship was automatically correlated.
96 * @see tag_get_related_tags()
98 define('TAG_RELATED_CORRELATED', 2);
100 ///////////////////////////////////////////////////////
101 /////////////////// PUBLIC TAG API ////////////////////
103 /// Functions for settings tags //////////////////////
106 * Set the tags assigned to a record. This overwrites the current tags.
108 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
110 * @package core_tag
111 * @category tag
112 * @access public
113 * @param string $record_type the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
114 * @param int $record_id the id of the record to tag
115 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
116 * @return bool|null
118 function tag_set($record_type, $record_id, $tags) {
120 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
121 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
122 $current_tagged_tag_name = tag_get_name($record_id);
125 $tags_ids = tag_get_id($tags, TAG_RETURN_ARRAY); // force an array, even if we only have one tag.
126 $cleaned_tags = tag_normalize($tags);
127 //echo 'tags-in-tag_set'; var_dump($tags); var_dump($tags_ids); var_dump($cleaned_tags);
129 $current_ids = tag_get_tags_ids($record_type, $record_id);
130 //var_dump($current_ids);
132 // for data coherence reasons, it's better to remove deleted tags
133 // before adding new data: ordering could be duplicated.
134 foreach($current_ids as $current_id) {
135 if (!in_array($current_id, $tags_ids)) {
136 tag_delete_instance($record_type, $record_id, $current_id);
137 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
138 // if we are removing a tag-on-a-tag (manually related tag),
139 // we need to remove the opposite relationship as well.
140 tag_delete_instance('tag', $current_id, $record_id);
145 if (empty($tags)) {
146 return true;
149 foreach($tags as $ordering => $tag) {
150 $tag = trim($tag);
151 if (!$tag) {
152 continue;
155 $clean_tag = $cleaned_tags[$tag];
156 $tag_current_id = $tags_ids[$clean_tag];
158 if ( is_null($tag_current_id) ) {
159 // create new tags
160 //echo "call to add tag $tag\n";
161 $new_tag = tag_add($tag);
162 $tag_current_id = $new_tag[$clean_tag];
165 tag_assign($record_type, $record_id, $tag_current_id, $ordering);
167 // if we are tagging a tag (adding a manually-assigned related tag), we
168 // need to create the opposite relationship as well.
169 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
170 $in_recursion_semaphore = true;
171 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name);
172 $in_recursion_semaphore = false;
178 * Adds a tag to a record, without overwriting the current tags.
180 * @package core_tag
181 * @category tag
182 * @access public
183 * @param string $record_type the type of record to tag ('post' for blogs, 'user' for users, etc.)
184 * @param int $record_id the id of the record to tag
185 * @param string $tag the tag to add
187 function tag_set_add($record_type, $record_id, $tag) {
189 $new_tags = array();
190 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
191 $new_tags[] = $current_tag->rawname;
193 $new_tags[] = $tag;
195 return tag_set($record_type, $record_id, $new_tags);
199 * Removes a tag from a record, without overwriting other current tags.
201 * @package core_tag
202 * @category tag
203 * @access public
204 * @param string $record_type the type of record to tag ('post' for blogs, 'user' for users, etc.)
205 * @param int $record_id the id of the record to tag
206 * @param string $tag the tag to delete
208 function tag_set_delete($record_type, $record_id, $tag) {
210 $new_tags = array();
211 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
212 if ($current_tag->name != $tag) { // Keep all tags but the one specified
213 $new_tags[] = $current_tag->name;
217 return tag_set($record_type, $record_id, $new_tags);
221 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
222 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
224 * @package core_tag
225 * @category tag
226 * @access public
227 * @param string $tagid tagid to modify
228 * @param string $type either 'default' or 'official'
229 * @return bool true on success, false otherwise
231 function tag_type_set($tagid, $type) {
232 global $DB;
234 if ($tag = $DB->get_record('tag', array('id'=>$tagid), 'id')) {
235 $tag->tagtype = $type;
236 $tag->timemodified = time();
237 return $DB->update_record('tag', $tag);
239 return false;
243 * Set the description of a tag
245 * @package core_tag
246 * @category tag
247 * @access public
248 * @param int $tagid the id of the tag
249 * @param string $description the tag's description string to be set
250 * @param int $descriptionformat the moodle text format of the description
251 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
252 * @return bool true on success, false otherwise
254 function tag_description_set($tagid, $description, $descriptionformat) {
255 global $DB;
257 if ($tag = $DB->get_record('tag', array('id'=>$tagid),'id')) {
258 $tag->description = $description;
259 $tag->descriptionformat = $descriptionformat;
260 $tag->timemodified = time();
261 return $DB->update_record('tag', $tag);
263 return false;
271 /// Functions for getting information about tags //////
274 * Simple function to just return a single tag object when you know the name or something
276 * @package core_tag
277 * @category tag
278 * @access public
279 * @param string $field which field do we use to identify the tag: id, name or rawname
280 * @param string $value the required value of the aforementioned field
281 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
282 * 'id', 'name', 'rawname' or '*' to include all fields.
283 * @return mixed tag object
285 function tag_get($field, $value, $returnfields='id, name, rawname') {
286 global $DB;
288 if ($field == 'name') {
289 $value = moodle_strtolower($value); // To cope with input that might just be wrong case
291 return $DB->get_record('tag', array($field=>$value), $returnfields);
296 * Get the array of db record of tags associated to a record (instances). Use {@see tag_get_tags_csv()} if you wish to get the same
297 * data in a comma-separated string, for instances such as needing to simply display a list of tags to the end user. This should
298 * really be called tag_get_tag_instances().
300 * @package core_tag
301 * @category tag
302 * @access public
303 * @param string $record_type the record type for which we want to get the tags
304 * @param int $record_id the record id for which we want to get the tags
305 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
306 * @param int $userid (optional) only required for course tagging
307 * @return array the array of tags
309 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
310 global $CFG, $DB;
312 $params = array();
314 if ($type) {
315 $sql_type = "AND tg.tagtype = :type";
316 $params['type'] = $type;
317 } else {
318 $sql_type = '';
321 $u = null;
322 if ($userid) {
323 $u = "AND ti.tiuserid = :userid ";
324 $params['userid'] = $userid;
327 $sql = "SELECT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
328 FROM {tag_instance} ti
329 JOIN {tag} tg ON tg.id = ti.tagid
330 WHERE ti.itemtype = :recordtype AND ti.itemid = :recordid $u $sql_type
331 ORDER BY ti.ordering ASC";
332 $params['recordtype'] = $record_type;
333 $params['recordid'] = $record_id;
335 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
336 return $DB->get_records_sql($sql, $params);
337 // This version of the query, reversing the ON clause, "correctly" returns
338 // a row with NULL values for instances that are still in the DB even though
339 // the tag has been deleted. This shouldn't happen, but if it did, using
340 // this query could help "clean it up". This causes bugs at this time.
341 //$tags = $DB->get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
342 // "FROM {tag_instance} ti LEFT JOIN {tag} tg ON ti.tagid = tg.id ".
343 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
344 // "ORDER BY ti.ordering ASC");
348 * Get the array of tags display names, indexed by id.
350 * @package core_tag
351 * @category tag
352 * @access public
353 * @param string $record_type the record type for which we want to get the tags
354 * @param int $record_id the record id for which we want to get the tags
355 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
356 * @return array the array of tags (with the value returned by tag_display_name), indexed by id
358 function tag_get_tags_array($record_type, $record_id, $type=null) {
359 $tags = array();
360 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
361 $tags[$tag->id] = tag_display_name($tag);
363 return $tags;
367 * Get a comma-separated string of tags associated to a record. Use {@see tag_get_tags()} to get the same information in an array.
369 * @package core_tag
370 * @category tag
371 * @access public
372 * @param string $record_type the record type for which we want to get the tags
373 * @param int $record_id the record id for which we want to get the tags
374 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
375 * @param string $type either 'official' or 'default', if null, all tags are returned
376 * @return string the comma-separated list of tags.
378 function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML, $type=null) {
379 global $CFG;
381 $tags_names = array();
382 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
383 if ($html == TAG_RETURN_TEXT) {
384 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
385 } else { // TAG_RETURN_HTML
386 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
389 return implode(', ', $tags_names);
393 * Get an array of tag ids associated to a record.
395 * @package core_tag
396 * @category tag
397 * @access public
398 * @todo MDL-31150 Update ordering property
399 * @param string $record_type the record type for which we want to get the tags
400 * @param int $record_id the record id for which we want to get the tags
401 * @return array tag ids, indexed and sorted by 'ordering'
403 function tag_get_tags_ids($record_type, $record_id) {
404 $tag_ids = array();
405 foreach (tag_get_tags($record_type, $record_id) as $tag) {
406 if ( array_key_exists($tag->ordering, $tag_ids) ) {
407 // until we can add a unique constraint, in table tag_instance,
408 // on (itemtype, itemid, ordering), this is needed to prevent a bug
409 // TODO MDL-31150 modify database in 2.0
410 $tag->ordering++;
412 $tag_ids[$tag->ordering] = $tag->id;
414 ksort($tag_ids);
415 return $tag_ids;
419 * Returns the database ID of a set of tags.
421 * @package core_tag
422 * @category tag
423 * @access public
424 * @todo MDL-31152 Test the commented MDL-31152 todo in this function to see if it helps performance
425 * without breaking anything.
426 * @param mixed $tags one tag, or array of tags, to look for.
427 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
428 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
429 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
430 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
432 function tag_get_id($tags, $return_value=null) {
433 global $CFG, $DB;
435 static $tag_id_cache = array();
437 $return_an_int = false;
438 if (!is_array($tags)) {
439 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
440 $return_an_int = true;
442 $tags = array($tags);
445 $result = array();
447 //TODO MDL-31152 test this and see if it helps performance without breaking anything
448 //foreach($tags as $key => $tag) {
449 // $clean_tag = moodle_strtolower($tag);
450 // if ( array_key_exists($clean_tag), $tag_id_cache) ) {
451 // $result[$clean_tag] = $tag_id_cache[$clean_tag];
452 // $tags[$key] = ''; // prevent further processing for this one.
453 // }
456 $tags = array_values(tag_normalize($tags));
457 foreach($tags as $key => $tag) {
458 $tags[$key] = moodle_strtolower($tag);
459 $result[moodle_strtolower($tag)] = null; // key must exists : no value for a key means the tag wasn't found.
462 if (empty($tags)) {
463 return array();
466 list($tag_string, $params) = $DB->get_in_or_equal($tags);
468 $rs = $DB->get_recordset_sql("SELECT * FROM {tag} WHERE name $tag_string ORDER BY name", $params);
469 foreach ($rs as $record) {
470 if ($return_value == TAG_RETURN_OBJECT) {
471 $result[$record->name] = $record;
472 } else { // TAG_RETURN_ARRAY
473 $result[$record->name] = $record->id;
476 $rs->close();
478 if ($return_an_int) {
479 return array_pop($result);
482 return $result;
487 * Returns tags related to a tag
489 * Related tags of a tag come from two sources:
490 * - manually added related tags, which are tag_instance entries for that tag
491 * - correlated tags, which are calculated
493 * @package core_tag
494 * @category tag
495 * @access public
496 * @param string $tagid is a single **normalized** tag name or the id of a tag
497 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
498 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
499 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
500 * @return array an array of tag objects
502 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
504 $related_tags = array();
506 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_MANUAL) {
507 //gets the manually added related tags
508 $related_tags = tag_get_tags('tag', $tagid);
511 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_CORRELATED ) {
512 //gets the correlated tags
513 $automatic_related_tags = tag_get_correlated($tagid, $limitnum);
514 if (is_array($automatic_related_tags)) {
515 $related_tags = array_merge($related_tags, $automatic_related_tags);
519 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
523 * Get a comma-separated list of tags related to another tag.
525 * @package core_tag
526 * @category tag
527 * @access public
528 * @param array $related_tags the array returned by tag_get_related_tags
529 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
530 * @return string comma-separated list
532 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
533 global $CFG;
535 $tags_names = array();
536 foreach($related_tags as $tag) {
537 if ( $html == TAG_RETURN_TEXT) {
538 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
539 } else {
540 // TAG_RETURN_HTML
541 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
545 return implode(', ', $tags_names);
549 * Change the "value" of a tag, and update the associated 'name'.
551 * @package core_tag
552 * @category tag
553 * @access public
554 * @param int $tagid the id of the tag to modify
555 * @param string $newrawname the new rawname
556 * @return bool true on success, false otherwise
558 function tag_rename($tagid, $newrawname) {
559 global $DB;
561 if (! $newrawname_clean = array_shift(tag_normalize($newrawname, TAG_CASE_ORIGINAL)) ) {
562 return false;
565 if (! $newname_clean = moodle_strtolower($newrawname_clean)) {
566 return false;
569 // Prevent the rename if a tag with that name already exists
570 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
571 if ($existing->id != $tagid) { // Another tag already exists with this name
572 return false;
576 if ($tag = tag_get('id', $tagid, 'id, name, rawname')) {
577 $tag->rawname = $newrawname_clean;
578 $tag->name = $newname_clean;
579 $tag->timemodified = time();
580 return $DB->update_record('tag', $tag);
582 return false;
587 * Delete one or more tag, and all their instances if there are any left.
589 * @package core_tag
590 * @category tag
591 * @access public
592 * @param mixed $tagids one tagid (int), or one array of tagids to delete
593 * @return bool true on success, false otherwise
595 function tag_delete($tagids) {
596 global $DB;
598 if (!is_array($tagids)) {
599 $tagids = array($tagids);
602 $success = true;
603 $context = get_context_instance(CONTEXT_SYSTEM);
604 foreach ($tagids as $tagid) {
605 if (is_null($tagid)) { // can happen if tag doesn't exists
606 continue;
608 // only delete the main entry if there were no problems deleting all the
609 // instances - that (and the fact we won't often delete lots of tags)
610 // is the reason for not using $DB->delete_records_select()
611 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid)) && $DB->delete_records('tag_correlation', array('tagid' => $tagid))) {
612 $success &= (bool) $DB->delete_records('tag', array('id'=>$tagid));
613 // Delete all files associated with this tag
614 $fs = get_file_storage();
615 $files = $fs->get_area_files($context->id, 'tag', 'description', $tagid);
616 foreach ($files as $file) {
617 $file->delete();
622 return $success;
626 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
628 * @package core_tag
629 * @category tag
630 * @access public
631 * @param string $record_type the type of the record for which to remove the instance
632 * @param int $record_id the id of the record for which to remove the instance
633 * @param int $tagid the tagid that needs to be removed
634 * @return bool true on success, false otherwise
636 function tag_delete_instance($record_type, $record_id, $tagid) {
637 global $CFG, $DB;
639 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id))) {
640 if (!$DB->record_exists_sql("SELECT * ".
641 "FROM {tag} tg ".
642 "WHERE tg.id = ? AND ( tg.tagtype = 'official' OR ".
643 "EXISTS (SELECT 1
644 FROM {tag_instance} ti
645 WHERE ti.tagid = ?) )",
646 array($tagid, $tagid))) {
647 return tag_delete($tagid);
649 } else {
650 return false;
653 return true;
658 * Function that returns the name that should be displayed for a specific tag
660 * @package core_tag
661 * @category tag
662 * @access public
663 * @param object $tagobject a line out of tag table, as returned by the adobd functions
664 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
665 * @return string
667 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
668 global $CFG;
670 if (!isset($tagobject->name)) {
671 return '';
674 if (empty($CFG->keeptagnamecase)) {
675 //this is the normalized tag name
676 $textlib = textlib_get_instance();
677 $tagname = $textlib->strtotitle($tagobject->name);
678 } else {
679 //original casing of the tag name
680 $tagname = $tagobject->rawname;
683 // clean up a bit just in case the rules change again
684 $tagname = clean_param($tagname, PARAM_TAG);
686 if ($html == TAG_RETURN_TEXT) {
687 return $tagname;
688 } else { // TAG_RETURN_HTML
689 return htmlspecialchars($tagname);
694 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
696 * @package core_tag
697 * @category tag
698 * @access public
699 * @param string $tag tag to look for
700 * @param string $type type to restrict search to. If null, every matching record will be returned
701 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
702 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
703 * @return array of matching objects, indexed by record id, from the table containing the type requested
705 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
706 global $CFG, $DB;
708 if (!$tag || !$type) {
709 return array();
712 $tagid = tag_get_id($tag);
714 $query = "SELECT it.*
715 FROM {".$type."} it INNER JOIN {tag_instance} tt ON it.id = tt.itemid
716 WHERE tt.itemtype = ? AND tt.tagid = ?";
717 $params = array($type, $tagid);
719 return $DB->get_records_sql($query, $params, $limitfrom, $limitnum);
725 ///////////////////////////////////////////////////////
726 /////////////////// PRIVATE TAG API ///////////////////
729 * Adds one or more tag in the database. This function should not be called directly : you should
730 * use tag_set.
732 * @package core_tag
733 * @access private
734 * @param mixed $tags one tag, or an array of tags, to be created
735 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
736 * value at this time). An official tag is kept even if there are no records tagged with it.
737 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
738 * adding the tag.
740 function tag_add($tags, $type="default") {
741 global $USER, $DB;
743 if (!is_array($tags)) {
744 $tags = array($tags);
747 $tag_object = new StdClass;
748 $tag_object->tagtype = $type;
749 $tag_object->userid = $USER->id;
750 $tag_object->timemodified = time();
752 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL);
754 $tags_ids = array();
755 foreach($clean_tags as $tag) {
756 $tag = trim($tag);
757 if (!$tag) {
758 $tags_ids[$tag] = false;
759 } else {
760 // note that the difference between rawname and name is only
761 // capitalization : the rawname is NOT the same at the rawtag.
762 $tag_object->rawname = $tag;
763 $tag_name_lc = moodle_strtolower($tag);
764 $tag_object->name = $tag_name_lc;
765 //var_dump($tag_object);
766 $tags_ids[$tag_name_lc] = $DB->insert_record('tag', $tag_object);
770 return $tags_ids;
774 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
776 * @package core_tag
777 * @access private
778 * @param string $record_type the type of the record that will be tagged
779 * @param int $record_id the id of the record that will be tagged
780 * @param string $tagid the tag id to set on the record.
781 * @param int $ordering the order of the instance for this record
782 * @param int $userid (optional) only required for course tagging
783 * @return bool true on success, false otherwise
785 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0) {
786 global $DB;
788 if ( $tag_instance_object = $DB->get_record('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id, 'tiuserid'=>$userid), 'id')) {
789 $tag_instance_object->ordering = $ordering;
790 $tag_instance_object->timemodified = time();
791 return $DB->update_record('tag_instance', $tag_instance_object);
792 } else {
793 $tag_instance_object = new StdClass;
794 $tag_instance_object->tagid = $tagid;
795 $tag_instance_object->itemid = $record_id;
796 $tag_instance_object->itemtype = $record_type;
797 $tag_instance_object->ordering = $ordering;
798 $tag_instance_object->timemodified = time();
799 $tag_instance_object->tiuserid = $userid;
800 return $DB->insert_record('tag_instance', $tag_instance_object);
805 * Function that returns tags that start with some text, for use by the autocomplete feature
807 * @package core_tag
808 * @access private
809 * @param string $text string that the tag names will be matched against
810 * @return mixed an array of objects, or false if no records were found or an error occured.
812 function tag_autocomplete($text) {
813 global $DB;
814 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
815 FROM {tag} tg
816 WHERE tg.name LIKE ?", array(moodle_strtolower($text)."%"));
820 * Clean up the tag tables, making sure all tagged object still exists.
822 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
823 * 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
824 * call: don't run at peak time.
826 * @package core_tag
827 * @access private
828 * @todo MDL-31212 Update tag cleanup sql so that it supports multiple types of tags
830 function tag_cleanup() {
831 global $DB;
833 $instances = $DB->get_recordset('tag_instance');
835 // cleanup tag instances
836 foreach ($instances as $instance) {
837 $delete = false;
839 if (!$DB->record_exists('tag', array('id'=>$instance->tagid))) {
840 // if the tag has been removed, instance should be deleted.
841 $delete = true;
842 } else {
843 switch ($instance->itemtype) {
844 case 'user': // users are marked as deleted, but not actually deleted
845 if ($DB->record_exists('user', array('id'=>$instance->itemid, 'deleted'=>1))) {
846 $delete = true;
848 break;
849 default: // anything else, if the instance is not there, delete.
850 if (!$DB->record_exists($instance->itemtype, array('id'=>$instance->itemid))) {
851 $delete = true;
853 break;
856 if ($delete) {
857 tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid);
858 //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER);
861 $instances->close();
863 // TODO MDL-31212 this will only clean tags of type 'default'. This is good as
864 // it won't delete 'official' tags, but the day we get more than two
865 // types, we need to fix this.
866 $unused_tags = $DB->get_recordset_sql("SELECT tg.id
867 FROM {tag} tg
868 WHERE tg.tagtype = 'default'
869 AND NOT EXISTS (
870 SELECT 'x'
871 FROM {tag_instance} ti
872 WHERE ti.tagid = tg.id
873 )");
875 // cleanup tags
876 foreach ($unused_tags as $unused_tag) {
877 tag_delete($unused_tag->id);
878 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
880 $unused_tags->close();
884 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
886 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
888 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
889 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
891 * @package core_tag
892 * @access private
893 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
895 function tag_compute_correlations($mincorrelation = 2) {
896 global $DB;
898 // This mighty one line query fetches a row from the database for every
899 // individual tag correlation. We then need to process the rows collecting
900 // the correlations for each tag id.
901 // The fields used by this query are as follows:
902 // tagid : This is the tag id, there should be at least $mincorrelation
903 // rows for each tag id.
904 // correlation : This is the tag id that correlates to the above tagid field.
905 // correlationid : This is the id of the row in the tag_correlation table that
906 // relates to the tagid field and will be NULL if there are no
907 // existing correlations
908 $sql = 'SELECT pairs.tagid, pairs.correlation, pairs.ocurrences, co.id AS correlationid
909 FROM (
910 SELECT ta.tagid, tb.tagid AS correlation, COUNT(*) AS ocurrences
911 FROM {tag_instance} ta
912 JOIN {tag_instance} tb ON (ta.itemtype = tb.itemtype AND ta.itemid = tb.itemid AND ta.tagid <> tb.tagid)
913 GROUP BY ta.tagid, tb.tagid
914 HAVING COUNT(*) > :mincorrelation
915 ) pairs
916 LEFT JOIN {tag_correlation} co ON co.tagid = pairs.tagid
917 ORDER BY pairs.tagid ASC, pairs.ocurrences DESC, pairs.correlation ASC';
918 $rs = $DB->get_recordset_sql($sql, array('mincorrelation' => $mincorrelation));
920 // Set up an empty tag correlation object
921 $tagcorrelation = new stdClass;
922 $tagcorrelation->id = null;
923 $tagcorrelation->tagid = null;
924 $tagcorrelation->correlatedtags = array();
926 // We store each correlation id in this array so we can remove any correlations
927 // that no longer exist.
928 $correlations = array();
930 // Iterate each row of the result set and build them into tag correlations.
931 // We add all of a tag's correlations to $tagcorrelation->correlatedtags[]
932 // then save the $tagcorrelation object
933 foreach ($rs as $row) {
934 if ($row->tagid != $tagcorrelation->tagid) {
935 // The tag id has changed so we have all of the correlations for this tag
936 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
937 if ($tagcorrelationid) {
938 $correlations[] = $tagcorrelationid;
940 // Now we reset the tag correlation object so we can reuse it and set it
941 // up for the current record.
942 $tagcorrelation = new stdClass;
943 $tagcorrelation->id = $row->correlationid;
944 $tagcorrelation->tagid = $row->tagid;
945 $tagcorrelation->correlatedtags = array();
947 //Save the correlation on the tag correlation object
948 $tagcorrelation->correlatedtags[] = $row->correlation;
950 // Update the current correlation after the last record.
951 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
952 if ($tagcorrelationid) {
953 $correlations[] = $tagcorrelationid;
957 // Close the recordset
958 $rs->close();
960 // Remove any correlations that weren't just identified
961 if (empty($correlations)) {
962 //there are no tag correlations
963 $DB->delete_records('tag_correlation');
964 } else {
965 list($sql, $params) = $DB->get_in_or_equal($correlations, SQL_PARAMS_NAMED, 'param0000', false);
966 $DB->delete_records_select('tag_correlation', 'id '.$sql, $params);
971 * This function processes a tag correlation and makes changes in the database as required.
973 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
975 * @package core_tag
976 * @access private
977 * @param stdClass $tagcorrelation
978 * @return int/bool The id of the tag correlation that was just processed or false.
980 function tag_process_computed_correlation(stdClass $tagcorrelation) {
981 global $DB;
983 // You must provide a tagid and correlatedtags must be set and be an array
984 if (empty($tagcorrelation->tagid) || !isset($tagcorrelation->correlatedtags) || !is_array($tagcorrelation->correlatedtags)) {
985 return false;
988 $tagcorrelation->correlatedtags = join(',', $tagcorrelation->correlatedtags);
989 if (!empty($tagcorrelation->id)) {
990 // The tag correlation already exists so update it
991 $DB->update_record('tag_correlation', $tagcorrelation);
992 } else {
993 // This is a new correlation to insert
994 $tagcorrelation->id = $DB->insert_record('tag_correlation', $tagcorrelation);
996 return $tagcorrelation->id;
1000 * Tasks that should be performed at cron time
1002 * @package core_tag
1003 * @access private
1005 function tag_cron() {
1006 tag_compute_correlations();
1007 tag_cleanup();
1011 * Search for tags with names that match some text
1013 * @package core_tag
1014 * @access private
1015 * @param string $text escaped string that the tag names will be matched against
1016 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
1017 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
1018 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
1019 * @return array/boolean an array of objects, or false if no records were found or an error occured.
1021 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
1022 global $DB;
1024 $text = array_shift(tag_normalize($text, TAG_CASE_LOWER));
1026 if ($ordered) {
1027 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
1028 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
1029 WHERE tg.name LIKE ?
1030 GROUP BY tg.id, tg.name, tg.rawname
1031 ORDER BY count DESC";
1032 } else {
1033 $query = "SELECT tg.id, tg.name, tg.rawname
1034 FROM {tag} tg
1035 WHERE tg.name LIKE ?";
1037 $params = array("%{$text}%");
1038 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
1042 * Get the name of a tag
1044 * @package core_tag
1045 * @access private
1046 * @param mixed $tagids the id of the tag, or an array of ids
1047 * @return mixed string name of one tag, or id-indexed array of strings
1049 function tag_get_name($tagids) {
1050 global $DB;
1052 if (!is_array($tagids)) {
1053 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
1054 return $tag->name;
1056 return false;
1059 $tag_names = array();
1060 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
1061 $tag_names[$tag->id] = $tag->name;
1064 return $tag_names;
1068 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
1069 * empty and this function won't return anything.
1071 * @package core_tag
1072 * @access private
1073 * @param int $tag_id is a single tag id
1074 * @param int $limitnum this parameter does not appear to have any function???
1075 * @return array an array of tag objects or an empty if no correlated tags are found
1077 function tag_get_correlated($tag_id, $limitnum=null) {
1078 global $DB;
1080 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
1082 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
1083 return array();
1086 // this is (and has to) return the same fields as the query in tag_get_tags
1087 $sql = "SELECT DISTINCT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
1088 FROM {tag} tg
1089 INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
1090 WHERE tg.id IN ({$tag_correlation->correlatedtags})";
1091 $result = $DB->get_records_sql($sql);
1092 if (!$result) {
1093 return array();
1096 return $result;
1100 * Function that normalizes a list of tag names.
1102 * @package core_tag
1103 * @access private
1104 * @param array/string $rawtags array of tags, or a single tag.
1105 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
1106 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
1107 * (Eg: 'Banana' => 'banana').
1109 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
1111 // cache normalized tags, to prevent costly repeated calls to clean_param
1112 static $cleaned_tags_lc = array(); // lower case - use for comparison
1113 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
1115 if ( !is_array($rawtags) ) {
1116 $rawtags = array($rawtags);
1119 $result = array();
1120 foreach($rawtags as $rawtag) {
1121 $rawtag = trim($rawtag);
1122 if (!$rawtag) {
1123 continue;
1125 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
1126 $cleaned_tags_lc[$rawtag] = moodle_strtolower( clean_param($rawtag, PARAM_TAG) );
1127 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
1129 if ( $case == TAG_CASE_LOWER ) {
1130 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
1131 } else { // TAG_CASE_ORIGINAL
1132 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
1136 return $result;
1140 * Count how many records are tagged with a specific tag.
1142 * @package core_tag
1143 * @access private
1144 * @param string $record_type record to look for ('post', 'user', etc.)
1145 * @param int $tagid is a single tag id
1146 * @return int number of mathing tags.
1148 function tag_record_count($record_type, $tagid) {
1149 global $DB;
1150 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
1154 * Determine if a record is tagged with a specific tag
1156 * @package core_tag
1157 * @access private
1158 * @param string $record_type the record type to look for
1159 * @param int $record_id the record id to look for
1160 * @param string $tag a tag name
1161 * @return bool/int true if it is tagged, 0 (false) otherwise
1163 function tag_record_tagged_with($record_type, $record_id, $tag) {
1164 global $DB;
1165 if ($tagid = tag_get_id($tag)) {
1166 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
1167 } else {
1168 return 0; // tag doesn't exist
1173 * Flag a tag as inapropriate
1175 * @package core_tag
1176 * @access private
1177 * @param int|array $tagids a single tagid, or an array of tagids
1179 function tag_set_flag($tagids) {
1180 global $DB;
1182 $tagids = (array)$tagids;
1183 foreach ($tagids as $tagid) {
1184 $tag = $DB->get_record('tag', array('id'=>$tagid), 'id, flag');
1185 $tag->flag++;
1186 $tag->timemodified = time();
1187 $DB->update_record('tag', $tag);
1192 * Remove the inapropriate flag on a tag
1194 * @package core_tag
1195 * @access private
1196 * @param int|array $tagids a single tagid, or an array of tagids
1197 * @return bool true if function succeeds, false otherwise
1199 function tag_unset_flag($tagids) {
1200 global $DB;
1202 if ( is_array($tagids) ) {
1203 $tagids = implode(',', $tagids);
1205 $timemodified = time();
1206 return $DB->execute("UPDATE {tag} SET flag = 0, timemodified = ? WHERE id IN ($tagids)", array($timemodified));
1211 * Return a list of page types
1213 * @package core_tag
1214 * @access private
1215 * @param string $pagetype current page type
1216 * @param stdClass $parentcontext Block's parent context
1217 * @param stdClass $currentcontext Current context of block
1219 function tag_page_type_list($pagetype, $parentcontext, $currentcontext) {
1220 return array(
1221 'tag-*'=>get_string('page-tag-x', 'tag'),
1222 'tag-index'=>get_string('page-tag-index', 'tag'),
1223 'tag-search'=>get_string('page-tag-search', 'tag'),
1224 'tag-manage'=>get_string('page-tag-manage', 'tag')