Merge branch 'MDL-38035-m24' of git://github.com/sammarshallou/moodle into MOODLE_24_...
[moodle.git] / tag / lib.php
blob0afc5636cd9734dbbb3f2f1a5f612eb1777ef768
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 = textlib::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 = textlib::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] = textlib::strtolower($tag);
459 $result[textlib::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 $norm = tag_normalize($newrawname, TAG_CASE_ORIGINAL);
562 if (! $newrawname_clean = array_shift($norm) ) {
563 return false;
566 if (! $newname_clean = textlib::strtolower($newrawname_clean)) {
567 return false;
570 // Prevent the rename if a tag with that name already exists
571 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
572 if ($existing->id != $tagid) { // Another tag already exists with this name
573 return false;
577 if ($tag = tag_get('id', $tagid, 'id, name, rawname')) {
578 $tag->rawname = $newrawname_clean;
579 $tag->name = $newname_clean;
580 $tag->timemodified = time();
581 return $DB->update_record('tag', $tag);
583 return false;
588 * Delete one or more tag, and all their instances if there are any left.
590 * @package core_tag
591 * @category tag
592 * @access public
593 * @param mixed $tagids one tagid (int), or one array of tagids to delete
594 * @return bool true on success, false otherwise
596 function tag_delete($tagids) {
597 global $DB;
599 if (!is_array($tagids)) {
600 $tagids = array($tagids);
603 $success = true;
604 $context = context_system::instance();
605 foreach ($tagids as $tagid) {
606 if (is_null($tagid)) { // can happen if tag doesn't exists
607 continue;
609 // only delete the main entry if there were no problems deleting all the
610 // instances - that (and the fact we won't often delete lots of tags)
611 // is the reason for not using $DB->delete_records_select()
612 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid)) && $DB->delete_records('tag_correlation', array('tagid' => $tagid))) {
613 $success &= (bool) $DB->delete_records('tag', array('id'=>$tagid));
614 // Delete all files associated with this tag
615 $fs = get_file_storage();
616 $files = $fs->get_area_files($context->id, 'tag', 'description', $tagid);
617 foreach ($files as $file) {
618 $file->delete();
623 return $success;
627 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
629 * @package core_tag
630 * @category tag
631 * @access public
632 * @param string $record_type the type of the record for which to remove the instance
633 * @param int $record_id the id of the record for which to remove the instance
634 * @param int $tagid the tagid that needs to be removed
635 * @return bool true on success, false otherwise
637 function tag_delete_instance($record_type, $record_id, $tagid) {
638 global $CFG, $DB;
640 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id))) {
641 if (!$DB->record_exists_sql("SELECT * ".
642 "FROM {tag} tg ".
643 "WHERE tg.id = ? AND ( tg.tagtype = 'official' OR ".
644 "EXISTS (SELECT 1
645 FROM {tag_instance} ti
646 WHERE ti.tagid = ?) )",
647 array($tagid, $tagid))) {
648 return tag_delete($tagid);
650 } else {
651 return false;
654 return true;
659 * Function that returns the name that should be displayed for a specific tag
661 * @package core_tag
662 * @category tag
663 * @access public
664 * @param object $tagobject a line out of tag table, as returned by the adobd functions
665 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
666 * @return string
668 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
669 global $CFG;
671 if (!isset($tagobject->name)) {
672 return '';
675 if (empty($CFG->keeptagnamecase)) {
676 //this is the normalized tag name
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 = textlib::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(textlib::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 $norm = tag_normalize($text, TAG_CASE_LOWER);
1025 $text = array_shift($norm);
1027 if ($ordered) {
1028 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
1029 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
1030 WHERE tg.name LIKE ?
1031 GROUP BY tg.id, tg.name, tg.rawname
1032 ORDER BY count DESC";
1033 } else {
1034 $query = "SELECT tg.id, tg.name, tg.rawname
1035 FROM {tag} tg
1036 WHERE tg.name LIKE ?";
1038 $params = array("%{$text}%");
1039 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
1043 * Get the name of a tag
1045 * @package core_tag
1046 * @access private
1047 * @param mixed $tagids the id of the tag, or an array of ids
1048 * @return mixed string name of one tag, or id-indexed array of strings
1050 function tag_get_name($tagids) {
1051 global $DB;
1053 if (!is_array($tagids)) {
1054 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
1055 return $tag->name;
1057 return false;
1060 $tag_names = array();
1061 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
1062 $tag_names[$tag->id] = $tag->name;
1065 return $tag_names;
1069 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
1070 * empty and this function won't return anything.
1072 * @package core_tag
1073 * @access private
1074 * @param int $tag_id is a single tag id
1075 * @param int $limitnum this parameter does not appear to have any function???
1076 * @return array an array of tag objects or an empty if no correlated tags are found
1078 function tag_get_correlated($tag_id, $limitnum=null) {
1079 global $DB;
1081 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
1083 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
1084 return array();
1087 // this is (and has to) return the same fields as the query in tag_get_tags
1088 $sql = "SELECT DISTINCT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
1089 FROM {tag} tg
1090 INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
1091 WHERE tg.id IN ({$tag_correlation->correlatedtags})";
1092 $result = $DB->get_records_sql($sql);
1093 if (!$result) {
1094 return array();
1097 return $result;
1101 * Function that normalizes a list of tag names.
1103 * @package core_tag
1104 * @access private
1105 * @param array/string $rawtags array of tags, or a single tag.
1106 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
1107 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
1108 * (Eg: 'Banana' => 'banana').
1110 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
1112 // cache normalized tags, to prevent costly repeated calls to clean_param
1113 static $cleaned_tags_lc = array(); // lower case - use for comparison
1114 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
1116 if ( !is_array($rawtags) ) {
1117 $rawtags = array($rawtags);
1120 $result = array();
1121 foreach($rawtags as $rawtag) {
1122 $rawtag = trim($rawtag);
1123 if (!$rawtag) {
1124 continue;
1126 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
1127 $cleaned_tags_lc[$rawtag] = textlib::strtolower( clean_param($rawtag, PARAM_TAG) );
1128 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
1130 if ( $case == TAG_CASE_LOWER ) {
1131 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
1132 } else { // TAG_CASE_ORIGINAL
1133 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
1137 return $result;
1141 * Count how many records are tagged with a specific tag.
1143 * @package core_tag
1144 * @access private
1145 * @param string $record_type record to look for ('post', 'user', etc.)
1146 * @param int $tagid is a single tag id
1147 * @return int number of mathing tags.
1149 function tag_record_count($record_type, $tagid) {
1150 global $DB;
1151 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
1155 * Determine if a record is tagged with a specific tag
1157 * @package core_tag
1158 * @access private
1159 * @param string $record_type the record type to look for
1160 * @param int $record_id the record id to look for
1161 * @param string $tag a tag name
1162 * @return bool/int true if it is tagged, 0 (false) otherwise
1164 function tag_record_tagged_with($record_type, $record_id, $tag) {
1165 global $DB;
1166 if ($tagid = tag_get_id($tag)) {
1167 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
1168 } else {
1169 return 0; // tag doesn't exist
1174 * Flag a tag as inapropriate
1176 * @package core_tag
1177 * @access private
1178 * @param int|array $tagids a single tagid, or an array of tagids
1180 function tag_set_flag($tagids) {
1181 global $DB;
1183 $tagids = (array)$tagids;
1184 foreach ($tagids as $tagid) {
1185 $tag = $DB->get_record('tag', array('id'=>$tagid), 'id, flag');
1186 $tag->flag++;
1187 $tag->timemodified = time();
1188 $DB->update_record('tag', $tag);
1193 * Remove the inapropriate flag on a tag
1195 * @package core_tag
1196 * @access private
1197 * @param int|array $tagids a single tagid, or an array of tagids
1198 * @return bool true if function succeeds, false otherwise
1200 function tag_unset_flag($tagids) {
1201 global $DB;
1203 if ( is_array($tagids) ) {
1204 $tagids = implode(',', $tagids);
1206 $timemodified = time();
1207 return $DB->execute("UPDATE {tag} SET flag = 0, timemodified = ? WHERE id IN ($tagids)", array($timemodified));
1212 * Return a list of page types
1214 * @package core_tag
1215 * @access private
1216 * @param string $pagetype current page type
1217 * @param stdClass $parentcontext Block's parent context
1218 * @param stdClass $currentcontext Current context of block
1220 function tag_page_type_list($pagetype, $parentcontext, $currentcontext) {
1221 return array(
1222 'tag-*'=>get_string('page-tag-x', 'tag'),
1223 'tag-index'=>get_string('page-tag-index', 'tag'),
1224 'tag-search'=>get_string('page-tag-search', 'tag'),
1225 'tag-manage'=>get_string('page-tag-manage', 'tag')