Merge branch 'MDL-51720-28' of git://github.com/damyon/moodle into MOODLE_28_STABLE
[moodle.git] / tag / lib.php
blob102704cbc2b4866604c21cc4cdb40e3b64b9d844
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, 'core', $thecontext);
36 * - to "remove all the tags on a blog post":
37 * tag_set('post', $blog_post->id, array(), 'core', $thecontext);
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 * @param string|null $component the component that was tagged
117 * @param int|null $contextid the context id of where this tag was assigned
118 * @return bool|null
120 function tag_set($record_type, $record_id, $tags, $component = null, $contextid = null) {
122 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
124 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
125 $current_tagged_tag_name = tag_get_name($record_id);
128 $tags_ids = tag_get_id($tags, TAG_RETURN_ARRAY); // force an array, even if we only have one tag.
129 $cleaned_tags = tag_normalize($tags);
130 //echo 'tags-in-tag_set'; var_dump($tags); var_dump($tags_ids); var_dump($cleaned_tags);
132 $current_ids = tag_get_tags_ids($record_type, $record_id);
133 //var_dump($current_ids);
135 // for data coherence reasons, it's better to remove deleted tags
136 // before adding new data: ordering could be duplicated.
137 foreach($current_ids as $current_id) {
138 if (!in_array($current_id, $tags_ids)) {
139 tag_delete_instance($record_type, $record_id, $current_id);
140 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
141 // if we are removing a tag-on-a-tag (manually related tag),
142 // we need to remove the opposite relationship as well.
143 tag_delete_instance('tag', $current_id, $record_id);
148 if (empty($tags)) {
149 return true;
152 foreach($tags as $ordering => $tag) {
153 $tag = trim($tag);
154 if (!$tag) {
155 continue;
158 $clean_tag = $cleaned_tags[$tag];
159 $tag_current_id = $tags_ids[$clean_tag];
161 if ( is_null($tag_current_id) ) {
162 // create new tags
163 //echo "call to add tag $tag\n";
164 $new_tag = tag_add($tag);
165 $tag_current_id = $new_tag[$clean_tag];
168 tag_assign($record_type, $record_id, $tag_current_id, $ordering, 0, $component, $contextid);
170 // if we are tagging a tag (adding a manually-assigned related tag), we
171 // need to create the opposite relationship as well.
172 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
173 $in_recursion_semaphore = true;
174 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name, $component, $contextid);
175 $in_recursion_semaphore = false;
181 * Adds a tag to a record, without overwriting the current tags.
183 * @package core_tag
184 * @category tag
185 * @access public
186 * @param string $record_type the type of record to tag ('post' for blogs, 'user' for users, etc.)
187 * @param int $record_id the id of the record to tag
188 * @param string $tag the tag to add
189 * @param string|null $component the component that was tagged
190 * @param int|null $contextid the context id of where this tag was assigned
191 * @return bool|null
193 function tag_set_add($record_type, $record_id, $tag, $component = null, $contextid = null) {
195 $new_tags = array();
196 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
197 $new_tags[] = $current_tag->rawname;
199 $new_tags[] = $tag;
201 return tag_set($record_type, $record_id, $new_tags, $component, $contextid);
205 * Removes a tag from a record, without overwriting other current tags.
207 * @package core_tag
208 * @category tag
209 * @access public
210 * @param string $record_type the type of record to tag ('post' for blogs, 'user' for users, etc.)
211 * @param int $record_id the id of the record to tag
212 * @param string $tag the tag to delete
213 * @param string|null $component the component that was tagged
214 * @param int|null $contextid the context id of where this tag was assigned
215 * @return bool|null
217 function tag_set_delete($record_type, $record_id, $tag, $component = null, $contextid = null) {
219 $new_tags = array();
220 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
221 if ($current_tag->name != $tag) { // Keep all tags but the one specified
222 $new_tags[] = $current_tag->name;
226 return tag_set($record_type, $record_id, $new_tags, $component, $contextid);
230 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
231 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
233 * @package core_tag
234 * @category tag
235 * @access public
236 * @param string $tagid tagid to modify
237 * @param string $type either 'default' or 'official'
238 * @return bool true on success, false otherwise
240 function tag_type_set($tagid, $type) {
241 global $DB;
243 if ($tag = $DB->get_record('tag', array('id' => $tagid), 'id, userid, name, rawname')) {
244 $tag->tagtype = $type;
245 $tag->timemodified = time();
246 $DB->update_record('tag', $tag);
248 $event = \core\event\tag_updated::create(array(
249 'objectid' => $tag->id,
250 'relateduserid' => $tag->userid,
251 'context' => context_system::instance(),
252 'other' => array(
253 'name' => $tag->name,
254 'rawname' => $tag->rawname
257 $event->trigger();
259 return true;
261 return false;
265 * Set the description of a tag
267 * @package core_tag
268 * @category tag
269 * @access public
270 * @param int $tagid the id of the tag
271 * @param string $description the tag's description string to be set
272 * @param int $descriptionformat the moodle text format of the description
273 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
274 * @return bool true on success, false otherwise
276 function tag_description_set($tagid, $description, $descriptionformat) {
277 global $DB;
279 if ($tag = $DB->get_record('tag', array('id' => $tagid), 'id, userid, name, rawname')) {
280 $tag->description = $description;
281 $tag->descriptionformat = $descriptionformat;
282 $tag->timemodified = time();
283 $DB->update_record('tag', $tag);
285 $event = \core\event\tag_updated::create(array(
286 'objectid' => $tag->id,
287 'relateduserid' => $tag->userid,
288 'context' => context_system::instance(),
289 'other' => array(
290 'name' => $tag->name,
291 'rawname' => $tag->rawname
294 $event->trigger();
296 return true;
299 return false;
307 /// Functions for getting information about tags //////
310 * Simple function to just return a single tag object when you know the name or something
312 * @package core_tag
313 * @category tag
314 * @access public
315 * @param string $field which field do we use to identify the tag: id, name or rawname
316 * @param string $value the required value of the aforementioned field
317 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
318 * 'id', 'name', 'rawname' or '*' to include all fields.
319 * @return mixed tag object
321 function tag_get($field, $value, $returnfields='id, name, rawname') {
322 global $DB;
324 if ($field == 'name') {
325 $value = core_text::strtolower($value); // To cope with input that might just be wrong case
327 return $DB->get_record('tag', array($field=>$value), $returnfields);
332 * 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
333 * data in a comma-separated string, for instances such as needing to simply display a list of tags to the end user. This should
334 * really be called tag_get_tag_instances().
336 * @package core_tag
337 * @category tag
338 * @access public
339 * @param string $record_type the record type for which we want to get the tags
340 * @param int $record_id the record id for which we want to get the tags
341 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
342 * @param int $userid (optional) only required for course tagging
343 * @return array the array of tags
345 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
346 global $CFG, $DB;
348 $params = array();
350 if ($type) {
351 $sql_type = "AND tg.tagtype = :type";
352 $params['type'] = $type;
353 } else {
354 $sql_type = '';
357 $u = null;
358 if ($userid) {
359 $u = "AND ti.tiuserid = :userid ";
360 $params['userid'] = $userid;
363 $sql = "SELECT ti.id AS taginstanceid, tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
364 FROM {tag_instance} ti
365 JOIN {tag} tg ON tg.id = ti.tagid
366 WHERE ti.itemtype = :recordtype AND ti.itemid = :recordid $u $sql_type
367 ORDER BY ti.ordering ASC";
368 $params['recordtype'] = $record_type;
369 $params['recordid'] = $record_id;
371 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
372 return $DB->get_records_sql($sql, $params);
373 // This version of the query, reversing the ON clause, "correctly" returns
374 // a row with NULL values for instances that are still in the DB even though
375 // the tag has been deleted. This shouldn't happen, but if it did, using
376 // this query could help "clean it up". This causes bugs at this time.
377 //$tags = $DB->get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
378 // "FROM {tag_instance} ti LEFT JOIN {tag} tg ON ti.tagid = tg.id ".
379 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
380 // "ORDER BY ti.ordering ASC");
384 * Get the array of tags display names, indexed by id.
386 * @package core_tag
387 * @category tag
388 * @access public
389 * @param string $record_type the record type for which we want to get the tags
390 * @param int $record_id the record id for which we want to get the tags
391 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
392 * @return array the array of tags (with the value returned by tag_display_name), indexed by id
394 function tag_get_tags_array($record_type, $record_id, $type=null) {
395 $tags = array();
396 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
397 $tags[$tag->id] = tag_display_name($tag);
399 return $tags;
403 * Get a comma-separated string of tags associated to a record. Use {@see tag_get_tags()} to get the same information in an array.
405 * @package core_tag
406 * @category tag
407 * @access public
408 * @param string $record_type the record type for which we want to get the tags
409 * @param int $record_id the record id for which we want to get the tags
410 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
411 * @param string $type either 'official' or 'default', if null, all tags are returned
412 * @return string the comma-separated list of tags.
414 function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML, $type=null) {
415 global $CFG;
417 $tags_names = array();
418 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
419 if ($html == TAG_RETURN_TEXT) {
420 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
421 } else { // TAG_RETURN_HTML
422 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
425 return implode(', ', $tags_names);
429 * Get an array of tag ids associated to a record.
431 * @package core_tag
432 * @category tag
433 * @access public
434 * @todo MDL-31150 Update ordering property
435 * @param string $record_type the record type for which we want to get the tags
436 * @param int $record_id the record id for which we want to get the tags
437 * @return array tag ids, indexed and sorted by 'ordering'
439 function tag_get_tags_ids($record_type, $record_id) {
440 $tag_ids = array();
441 foreach (tag_get_tags($record_type, $record_id) as $tag) {
442 if ( array_key_exists($tag->ordering, $tag_ids) ) {
443 // until we can add a unique constraint, in table tag_instance,
444 // on (itemtype, itemid, ordering), this is needed to prevent a bug
445 // TODO MDL-31150 modify database in 2.0
446 $tag->ordering++;
448 $tag_ids[$tag->ordering] = $tag->id;
450 ksort($tag_ids);
451 return $tag_ids;
455 * Returns the database ID of a set of tags.
457 * @package core_tag
458 * @category tag
459 * @access public
460 * @todo MDL-31152 Test the commented MDL-31152 todo in this function to see if it helps performance
461 * without breaking anything.
462 * @param mixed $tags one tag, or array of tags, to look for.
463 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
464 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
465 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
466 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
468 function tag_get_id($tags, $return_value=null) {
469 global $CFG, $DB;
471 static $tag_id_cache = array();
473 $return_an_int = false;
474 if (!is_array($tags)) {
475 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
476 $return_an_int = true;
478 $tags = array($tags);
481 $result = array();
483 //TODO MDL-31152 test this and see if it helps performance without breaking anything
484 //foreach($tags as $key => $tag) {
485 // $clean_tag = core_text::strtolower($tag);
486 // if ( array_key_exists($clean_tag), $tag_id_cache) ) {
487 // $result[$clean_tag] = $tag_id_cache[$clean_tag];
488 // $tags[$key] = ''; // prevent further processing for this one.
489 // }
492 $tags = array_values(tag_normalize($tags));
493 foreach($tags as $key => $tag) {
494 $tags[$key] = core_text::strtolower($tag);
495 $result[core_text::strtolower($tag)] = null; // key must exists : no value for a key means the tag wasn't found.
498 if (empty($tags)) {
499 return array();
502 list($tag_string, $params) = $DB->get_in_or_equal($tags);
504 $rs = $DB->get_recordset_sql("SELECT * FROM {tag} WHERE name $tag_string ORDER BY name", $params);
505 foreach ($rs as $record) {
506 if ($return_value == TAG_RETURN_OBJECT) {
507 $result[$record->name] = $record;
508 } else { // TAG_RETURN_ARRAY
509 $result[$record->name] = $record->id;
512 $rs->close();
514 if ($return_an_int) {
515 return array_pop($result);
518 return $result;
523 * Returns tags related to a tag
525 * Related tags of a tag come from two sources:
526 * - manually added related tags, which are tag_instance entries for that tag
527 * - correlated tags, which are calculated
529 * @package core_tag
530 * @category tag
531 * @access public
532 * @param string $tagid is a single **normalized** tag name or the id of a tag
533 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
534 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
535 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
536 * @return array an array of tag objects
538 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
540 $related_tags = array();
542 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_MANUAL) {
543 //gets the manually added related tags
544 $related_tags = tag_get_tags('tag', $tagid);
547 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_CORRELATED ) {
548 //gets the correlated tags
549 $automatic_related_tags = tag_get_correlated($tagid, $limitnum);
550 if (is_array($automatic_related_tags)) {
551 $related_tags = array_merge($related_tags, $automatic_related_tags);
555 // Remove duplicated tags (multiple instances of the same tag).
556 $seen = array();
557 foreach ($related_tags as $instance => $tag) {
558 if (isset($seen[$tag->id])) {
559 unset($related_tags[$instance]);
560 } else {
561 $seen[$tag->id] = 1;
565 return array_slice($related_tags, 0 , $limitnum);
569 * Get a comma-separated list of tags related to another tag.
571 * @package core_tag
572 * @category tag
573 * @access public
574 * @param array $related_tags the array returned by tag_get_related_tags
575 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
576 * @return string comma-separated list
578 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
579 global $CFG;
581 $tags_names = array();
582 foreach($related_tags as $tag) {
583 if ( $html == TAG_RETURN_TEXT) {
584 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
585 } else {
586 // TAG_RETURN_HTML
587 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
591 return implode(', ', $tags_names);
595 * Change the "value" of a tag, and update the associated 'name'.
597 * @package core_tag
598 * @category tag
599 * @access public
600 * @param int $tagid the id of the tag to modify
601 * @param string $newrawname the new rawname
602 * @return bool true on success, false otherwise
604 function tag_rename($tagid, $newrawname) {
605 global $COURSE, $DB;
607 $norm = tag_normalize($newrawname, TAG_CASE_ORIGINAL);
608 if (! $newrawname_clean = array_shift($norm) ) {
609 return false;
612 if (! $newname_clean = core_text::strtolower($newrawname_clean)) {
613 return false;
616 // Prevent the rename if a tag with that name already exists
617 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
618 if ($existing->id != $tagid) { // Another tag already exists with this name
619 return false;
623 if ($tag = tag_get('id', $tagid, 'id, userid, name, rawname')) {
624 // Store the name before we change it.
625 $oldname = $tag->name;
627 $tag->rawname = $newrawname_clean;
628 $tag->name = $newname_clean;
629 $tag->timemodified = time();
630 $DB->update_record('tag', $tag);
632 $event = \core\event\tag_updated::create(array(
633 'objectid' => $tag->id,
634 'relateduserid' => $tag->userid,
635 'context' => context_system::instance(),
636 'other' => array(
637 'name' => $newname_clean,
638 'rawname' => $newrawname_clean
641 $event->set_legacy_logdata(array($COURSE->id, 'tag', 'update', 'index.php?id='. $tag->id, $oldname . '->'. $tag->name));
642 $event->trigger();
644 return true;
646 return false;
651 * Delete one or more tag, and all their instances if there are any left.
653 * @package core_tag
654 * @category tag
655 * @access public
656 * @param mixed $tagids one tagid (int), or one array of tagids to delete
657 * @return bool true on success, false otherwise
659 function tag_delete($tagids) {
660 global $DB;
662 if (!is_array($tagids)) {
663 $tagids = array($tagids);
666 // Use the tagids to create a select statement to be used later.
667 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids);
669 // Store the tags and tag instances we are going to delete.
670 $tags = $DB->get_records_select('tag', 'id ' . $tagsql, $tagparams);
671 $taginstances = $DB->get_records_select('tag_instance', 'tagid ' . $tagsql, $tagparams);
673 // Delete all the tag instances.
674 $select = 'WHERE tagid ' . $tagsql;
675 $sql = "DELETE FROM {tag_instance} $select";
676 $DB->execute($sql, $tagparams);
678 // Delete all the tag correlations.
679 $sql = "DELETE FROM {tag_correlation} $select";
680 $DB->execute($sql, $tagparams);
682 // Delete all the tags.
683 $select = 'WHERE id ' . $tagsql;
684 $sql = "DELETE FROM {tag} $select";
685 $DB->execute($sql, $tagparams);
687 // Fire an event that these items were untagged.
688 if ($taginstances) {
689 // Save the system context in case the 'contextid' column in the 'tag_instance' table is null.
690 $syscontextid = context_system::instance()->id;
691 // Loop through the tag instances and fire a 'tag_removed'' event.
692 foreach ($taginstances as $taginstance) {
693 // We can not fire an event with 'null' as the contextid.
694 if (is_null($taginstance->contextid)) {
695 $taginstance->contextid = $syscontextid;
698 // Trigger tag removed event.
699 $event = \core\event\tag_removed::create(array(
700 'objectid' => $taginstance->id,
701 'contextid' => $taginstance->contextid,
702 'other' => array(
703 'tagid' => $taginstance->tagid,
704 'tagname' => $tags[$taginstance->tagid]->name,
705 'tagrawname' => $tags[$taginstance->tagid]->rawname,
706 'itemid' => $taginstance->itemid,
707 'itemtype' => $taginstance->itemtype
710 $event->add_record_snapshot('tag_instance', $taginstance);
711 $event->trigger();
715 // Fire an event that these tags were deleted.
716 if ($tags) {
717 $context = context_system::instance();
718 foreach ($tags as $tag) {
719 // Delete all files associated with this tag
720 $fs = get_file_storage();
721 $files = $fs->get_area_files($context->id, 'tag', 'description', $tag->id);
722 foreach ($files as $file) {
723 $file->delete();
726 // Trigger an event for deleting this tag.
727 $event = \core\event\tag_deleted::create(array(
728 'objectid' => $tag->id,
729 'relateduserid' => $tag->userid,
730 'context' => $context,
731 'other' => array(
732 'name' => $tag->name,
733 'rawname' => $tag->rawname
736 $event->add_record_snapshot('tag', $tag);
737 $event->trigger();
741 return true;
745 * Deletes all the tag instances given a component and an optional contextid.
747 * @param string $component
748 * @param int $contextid if null, then we delete all tag instances for the $component
750 function tag_delete_instances($component, $contextid = null) {
751 global $DB;
753 $sql = "SELECT ti.*, t.name, t.rawname
754 FROM {tag_instance} ti
755 JOIN {tag} t
756 ON ti.tagid = t.id ";
757 if (is_null($contextid)) {
758 $params = array('component' => $component);
759 $sql .= "WHERE ti.component = :component";
760 } else {
761 $params = array('component' => $component, 'contextid' => $contextid);
762 $sql .= "WHERE ti.component = :component
763 AND ti.contextid = :contextid";
765 if ($taginstances = $DB->get_records_sql($sql, $params)) {
766 // Now remove all the tag instances.
767 $DB->delete_records('tag_instance',$params);
768 // Save the system context in case the 'contextid' column in the 'tag_instance' table is null.
769 $syscontextid = context_system::instance()->id;
770 // Loop through the tag instances and fire an 'tag_removed' event.
771 foreach ($taginstances as $taginstance) {
772 // We can not fire an event with 'null' as the contextid.
773 if (is_null($taginstance->contextid)) {
774 $taginstance->contextid = $syscontextid;
777 // Trigger tag removed event.
778 $event = \core\event\tag_removed::create(array(
779 'objectid' => $taginstance->id,
780 'contextid' => $taginstance->contextid,
781 'other' => array(
782 'tagid' => $taginstance->tagid,
783 'tagname' => $taginstance->name,
784 'tagrawname' => $taginstance->rawname,
785 'itemid' => $taginstance->itemid,
786 'itemtype' => $taginstance->itemtype
789 $event->add_record_snapshot('tag_instance', $taginstance);
790 $event->trigger();
796 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
798 * @package core_tag
799 * @category tag
800 * @access public
801 * @param string $record_type the type of the record for which to remove the instance
802 * @param int $record_id the id of the record for which to remove the instance
803 * @param int $tagid the tagid that needs to be removed
804 * @param int $userid (optional) the userid
805 * @return bool true on success, false otherwise
807 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
808 global $DB;
810 if (is_null($userid)) {
811 $taginstance = $DB->get_record('tag_instance', array('tagid' => $tagid, 'itemtype' => $record_type, 'itemid' => $record_id));
812 } else {
813 $taginstance = $DB->get_record('tag_instance', array('tagid' => $tagid, 'itemtype' => $record_type, 'itemid' => $record_id,
814 'tiuserid' => $userid));
816 if ($taginstance) {
817 // Get the tag.
818 $tag = $DB->get_record('tag', array('id' => $tagid));
820 $DB->delete_records('tag_instance', array('id' => $taginstance->id));
822 // We can not fire an event with 'null' as the contextid.
823 if (is_null($taginstance->contextid)) {
824 $taginstance->contextid = context_system::instance()->id;
827 // Trigger tag removed event.
828 $event = \core\event\tag_removed::create(array(
829 'objectid' => $taginstance->id,
830 'contextid' => $taginstance->contextid,
831 'other' => array(
832 'tagid' => $tag->id,
833 'tagname' => $tag->name,
834 'tagrawname' => $tag->rawname,
835 'itemid' => $taginstance->itemid,
836 'itemtype' => $taginstance->itemtype
839 $event->add_record_snapshot('tag_instance', $taginstance);
840 $event->trigger();
842 // If there are no other instances of the tag then consider deleting the tag as well.
843 if (!$DB->record_exists('tag_instance', array('tagid' => $tagid))) {
844 // If the tag is a personal tag then delete it - don't delete official tags.
845 if ($tag->tagtype == 'default') {
846 tag_delete($tagid);
849 } else {
850 return false;
853 return true;
858 * Function that returns the name that should be displayed for a specific tag
860 * @package core_tag
861 * @category tag
862 * @access public
863 * @param object $tagobject a line out of tag table, as returned by the adobd functions
864 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
865 * @return string
867 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
868 global $CFG;
870 if (!isset($tagobject->name)) {
871 return '';
874 if (empty($CFG->keeptagnamecase)) {
875 //this is the normalized tag name
876 $tagname = core_text::strtotitle($tagobject->name);
877 } else {
878 //original casing of the tag name
879 $tagname = $tagobject->rawname;
882 // clean up a bit just in case the rules change again
883 $tagname = clean_param($tagname, PARAM_TAG);
885 if ($html == TAG_RETURN_TEXT) {
886 return $tagname;
887 } else { // TAG_RETURN_HTML
888 return htmlspecialchars($tagname);
893 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
895 * @package core_tag
896 * @category tag
897 * @access public
898 * @param string $tag tag to look for
899 * @param string $type type to restrict search to. If null, every matching record will be returned
900 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
901 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
902 * @return array of matching objects, indexed by record id, from the table containing the type requested
904 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
905 global $CFG, $DB;
907 if (!$tag || !$type) {
908 return array();
911 $tagid = tag_get_id($tag);
913 $query = "SELECT it.*
914 FROM {".$type."} it INNER JOIN {tag_instance} tt ON it.id = tt.itemid
915 WHERE tt.itemtype = ? AND tt.tagid = ?";
916 $params = array($type, $tagid);
918 return $DB->get_records_sql($query, $params, $limitfrom, $limitnum);
924 ///////////////////////////////////////////////////////
925 /////////////////// PRIVATE TAG API ///////////////////
928 * Adds one or more tag in the database. This function should not be called directly : you should
929 * use tag_set.
931 * @package core_tag
932 * @access private
933 * @param mixed $tags one tag, or an array of tags, to be created
934 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
935 * value at this time). An official tag is kept even if there are no records tagged with it.
936 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
937 * adding the tag.
939 function tag_add($tags, $type="default") {
940 global $USER, $DB;
942 if (!is_array($tags)) {
943 $tags = array($tags);
946 $tag_object = new StdClass;
947 $tag_object->tagtype = $type;
948 $tag_object->userid = $USER->id;
949 $tag_object->timemodified = time();
951 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL);
953 $tags_ids = array();
954 foreach($clean_tags as $tag) {
955 $tag = trim($tag);
956 if (!$tag) {
957 $tags_ids[$tag] = false;
958 } else {
959 // note that the difference between rawname and name is only
960 // capitalization : the rawname is NOT the same at the rawtag.
961 $tag_object->rawname = $tag;
962 $tag_name_lc = core_text::strtolower($tag);
963 $tag_object->name = $tag_name_lc;
964 //var_dump($tag_object);
965 $tags_ids[$tag_name_lc] = $DB->insert_record('tag', $tag_object);
967 $event = \core\event\tag_created::create(array(
968 'objectid' => $tags_ids[$tag_name_lc],
969 'relateduserid' => $tag_object->userid,
970 'context' => context_system::instance(),
971 'other' => array(
972 'name' => $tag_object->name,
973 'rawname' => $tag_object->rawname
976 $event->trigger();
980 return $tags_ids;
984 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
986 * @package core_tag
987 * @access private
988 * @param string $record_type the type of the record that will be tagged
989 * @param int $record_id the id of the record that will be tagged
990 * @param string $tagid the tag id to set on the record.
991 * @param int $ordering the order of the instance for this record
992 * @param int $userid (optional) only required for course tagging
993 * @param string|null $component the component that was tagged
994 * @param int|null $contextid the context id of where this tag was assigned
995 * @return bool true on success, false otherwise
997 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
998 global $DB;
1000 if ($component === null || $contextid === null) {
1001 debugging('You should specify the component and contextid of the item being tagged in your call to tag_assign.',
1002 DEBUG_DEVELOPER);
1005 // Get the tag.
1006 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
1008 if ( $tag_instance_object = $DB->get_record('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id, 'tiuserid'=>$userid), 'id')) {
1009 $tag_instance_object->ordering = $ordering;
1010 $tag_instance_object->timemodified = time();
1012 $DB->update_record('tag_instance', $tag_instance_object);
1013 } else {
1014 $tag_instance_object = new StdClass;
1015 $tag_instance_object->tagid = $tagid;
1016 $tag_instance_object->component = $component;
1017 $tag_instance_object->itemid = $record_id;
1018 $tag_instance_object->itemtype = $record_type;
1019 $tag_instance_object->contextid = $contextid;
1020 $tag_instance_object->ordering = $ordering;
1021 $tag_instance_object->timecreated = time();
1022 $tag_instance_object->timemodified = $tag_instance_object->timecreated;
1023 $tag_instance_object->tiuserid = $userid;
1025 $tag_instance_object->id = $DB->insert_record('tag_instance', $tag_instance_object);
1028 // We can not fire an event with 'null' as the contextid.
1029 if (is_null($contextid)) {
1030 $contextid = context_system::instance()->id;
1033 // Trigger tag added event.
1034 $event = \core\event\tag_added::create(array(
1035 'objectid' => $tag_instance_object->id,
1036 'contextid' => $contextid,
1037 'other' => array(
1038 'tagid' => $tagid,
1039 'tagname' => $tag->name,
1040 'tagrawname' => $tag->rawname,
1041 'itemid' => $record_id,
1042 'itemtype' => $record_type
1045 $event->trigger();
1047 return true;
1051 * Function that returns tags that start with some text, for use by the autocomplete feature
1053 * @package core_tag
1054 * @access private
1055 * @param string $text string that the tag names will be matched against
1056 * @return mixed an array of objects, or false if no records were found or an error occured.
1058 function tag_autocomplete($text) {
1059 global $DB;
1060 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
1061 FROM {tag} tg
1062 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
1066 * Clean up the tag tables, making sure all tagged object still exists.
1068 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
1069 * 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
1070 * call: don't run at peak time.
1072 * @package core_tag
1073 * @access private
1074 * @todo MDL-31212 Update tag cleanup sql so that it supports multiple types of tags
1076 function tag_cleanup() {
1077 global $DB;
1079 // Get ids to delete from instances where the tag has been deleted. This should never happen apparently.
1080 $sql = "SELECT ti.id
1081 FROM {tag_instance} ti
1082 LEFT JOIN {tag} t ON t.id = ti.tagid
1083 WHERE t.id IS null";
1084 $tagids = $DB->get_records_sql($sql);
1085 $tagarray = array();
1086 foreach ($tagids as $tagid) {
1087 $tagarray[] = $tagid->id;
1090 // Next get ids from instances that have an owner that has been deleted.
1091 $sql = "SELECT ti.id
1092 FROM {tag_instance} ti, {user} u
1093 WHERE ti.itemid = u.id
1094 AND ti.itemtype = 'user'
1095 AND u.deleted = 1";
1096 $tagids = $DB->get_records_sql($sql);
1097 foreach ($tagids as $tagid) {
1098 $tagarray[] = $tagid->id;
1101 // Get the other itemtypes.
1102 $sql = "SELECT itemtype
1103 FROM {tag_instance}
1104 WHERE itemtype <> 'user'
1105 GROUP BY itemtype";
1106 $tagitemtypes = $DB->get_records_sql($sql);
1107 foreach ($tagitemtypes as $key => $notused) {
1108 $sql = 'SELECT ti.id
1109 FROM {tag_instance} ti
1110 LEFT JOIN {' . $key . '} it ON it.id = ti.itemid
1111 WHERE it.id IS null
1112 AND ti.itemtype = \'' . $key . '\'';
1113 $tagids = $DB->get_records_sql($sql);
1114 foreach ($tagids as $tagid) {
1115 $tagarray[] = $tagid->id;
1119 // Get instances for each of the ids to be deleted.
1120 if (count($tagarray) > 0) {
1121 list($sqlin, $params) = $DB->get_in_or_equal($tagarray);
1122 $sql = "SELECT ti.*, COALESCE(t.name, 'deleted') AS name, COALESCE(t.rawname, 'deleted') AS rawname
1123 FROM {tag_instance} ti
1124 LEFT JOIN {tag} t ON t.id = ti.tagid
1125 WHERE ti.id $sqlin";
1126 $instances = $DB->get_records_sql($sql, $params);
1127 tag_bulk_delete_instances($instances);
1130 // TODO MDL-31212 this will only clean tags of type 'default'. This is good as
1131 // it won't delete 'official' tags, but the day we get more than two
1132 // types, we need to fix this.
1133 $unused_tags = $DB->get_recordset_sql("SELECT tg.id
1134 FROM {tag} tg
1135 WHERE tg.tagtype = 'default'
1136 AND NOT EXISTS (
1137 SELECT 'x'
1138 FROM {tag_instance} ti
1139 WHERE ti.tagid = tg.id
1140 )");
1142 // cleanup tags
1143 foreach ($unused_tags as $unused_tag) {
1144 tag_delete($unused_tag->id);
1145 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
1147 $unused_tags->close();
1151 * This function will delete numerous tag instances efficiently.
1152 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
1154 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
1155 * (used for recording a delete event).
1157 function tag_bulk_delete_instances($instances) {
1158 global $DB;
1160 $instanceids = array();
1161 foreach ($instances as $instance) {
1162 $instanceids[] = $instance->id;
1165 // This is a multi db compatible method of creating the correct sql when using the 'IN' value.
1166 // $insql is the sql statement, $params are the id numbers.
1167 list($insql, $params) = $DB->get_in_or_equal($instanceids);
1168 $sql = 'id ' . $insql;
1169 $DB->delete_records_select('tag_instance', $sql, $params);
1171 // Now go through and record each tag individually with the event system.
1172 foreach ($instances as $instance) {
1173 // Trigger tag removed event (i.e. The tag instance has been removed).
1174 $event = \core\event\tag_removed::create(array(
1175 'objectid' => $instance->id,
1176 'contextid' => $instance->contextid,
1177 'other' => array(
1178 'tagid' => $instance->tagid,
1179 'tagname' => $instance->name,
1180 'tagrawname' => $instance->rawname,
1181 'itemid' => $instance->itemid,
1182 'itemtype' => $instance->itemtype
1185 unset($instance->name);
1186 unset($instance->rawname);
1187 $event->add_record_snapshot('tag_instance', $instance);
1188 $event->trigger();
1193 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
1195 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
1197 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
1198 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
1200 * @package core_tag
1201 * @access private
1202 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
1204 function tag_compute_correlations($mincorrelation = 2) {
1205 global $DB;
1207 // This mighty one line query fetches a row from the database for every
1208 // individual tag correlation. We then need to process the rows collecting
1209 // the correlations for each tag id.
1210 // The fields used by this query are as follows:
1211 // tagid : This is the tag id, there should be at least $mincorrelation
1212 // rows for each tag id.
1213 // correlation : This is the tag id that correlates to the above tagid field.
1214 // correlationid : This is the id of the row in the tag_correlation table that
1215 // relates to the tagid field and will be NULL if there are no
1216 // existing correlations
1217 $sql = 'SELECT pairs.tagid, pairs.correlation, pairs.ocurrences, co.id AS correlationid
1218 FROM (
1219 SELECT ta.tagid, tb.tagid AS correlation, COUNT(*) AS ocurrences
1220 FROM {tag_instance} ta
1221 JOIN {tag_instance} tb ON (ta.itemtype = tb.itemtype AND ta.itemid = tb.itemid AND ta.tagid <> tb.tagid)
1222 GROUP BY ta.tagid, tb.tagid
1223 HAVING COUNT(*) > :mincorrelation
1224 ) pairs
1225 LEFT JOIN {tag_correlation} co ON co.tagid = pairs.tagid
1226 ORDER BY pairs.tagid ASC, pairs.ocurrences DESC, pairs.correlation ASC';
1227 $rs = $DB->get_recordset_sql($sql, array('mincorrelation' => $mincorrelation));
1229 // Set up an empty tag correlation object
1230 $tagcorrelation = new stdClass;
1231 $tagcorrelation->id = null;
1232 $tagcorrelation->tagid = null;
1233 $tagcorrelation->correlatedtags = array();
1235 // We store each correlation id in this array so we can remove any correlations
1236 // that no longer exist.
1237 $correlations = array();
1239 // Iterate each row of the result set and build them into tag correlations.
1240 // We add all of a tag's correlations to $tagcorrelation->correlatedtags[]
1241 // then save the $tagcorrelation object
1242 foreach ($rs as $row) {
1243 if ($row->tagid != $tagcorrelation->tagid) {
1244 // The tag id has changed so we have all of the correlations for this tag
1245 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
1246 if ($tagcorrelationid) {
1247 $correlations[] = $tagcorrelationid;
1249 // Now we reset the tag correlation object so we can reuse it and set it
1250 // up for the current record.
1251 $tagcorrelation = new stdClass;
1252 $tagcorrelation->id = $row->correlationid;
1253 $tagcorrelation->tagid = $row->tagid;
1254 $tagcorrelation->correlatedtags = array();
1256 //Save the correlation on the tag correlation object
1257 $tagcorrelation->correlatedtags[] = $row->correlation;
1259 // Update the current correlation after the last record.
1260 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
1261 if ($tagcorrelationid) {
1262 $correlations[] = $tagcorrelationid;
1266 // Close the recordset
1267 $rs->close();
1269 // Remove any correlations that weren't just identified
1270 if (empty($correlations)) {
1271 //there are no tag correlations
1272 $DB->delete_records('tag_correlation');
1273 } else {
1274 list($sql, $params) = $DB->get_in_or_equal($correlations, SQL_PARAMS_NAMED, 'param0000', false);
1275 $DB->delete_records_select('tag_correlation', 'id '.$sql, $params);
1280 * This function processes a tag correlation and makes changes in the database as required.
1282 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
1284 * @package core_tag
1285 * @access private
1286 * @param stdClass $tagcorrelation
1287 * @return int/bool The id of the tag correlation that was just processed or false.
1289 function tag_process_computed_correlation(stdClass $tagcorrelation) {
1290 global $DB;
1292 // You must provide a tagid and correlatedtags must be set and be an array
1293 if (empty($tagcorrelation->tagid) || !isset($tagcorrelation->correlatedtags) || !is_array($tagcorrelation->correlatedtags)) {
1294 return false;
1297 $tagcorrelation->correlatedtags = join(',', $tagcorrelation->correlatedtags);
1298 if (!empty($tagcorrelation->id)) {
1299 // The tag correlation already exists so update it
1300 $DB->update_record('tag_correlation', $tagcorrelation);
1301 } else {
1302 // This is a new correlation to insert
1303 $tagcorrelation->id = $DB->insert_record('tag_correlation', $tagcorrelation);
1305 return $tagcorrelation->id;
1309 * Tasks that should be performed at cron time
1311 * @package core_tag
1312 * @access private
1314 function tag_cron() {
1315 tag_compute_correlations();
1316 tag_cleanup();
1320 * Search for tags with names that match some text
1322 * @package core_tag
1323 * @access private
1324 * @param string $text escaped string that the tag names will be matched against
1325 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
1326 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
1327 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
1328 * @return array/boolean an array of objects, or false if no records were found or an error occured.
1330 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
1331 global $DB;
1333 $norm = tag_normalize($text, TAG_CASE_LOWER);
1334 $text = array_shift($norm);
1336 if ($ordered) {
1337 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
1338 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
1339 WHERE tg.name LIKE ?
1340 GROUP BY tg.id, tg.name, tg.rawname
1341 ORDER BY count DESC";
1342 } else {
1343 $query = "SELECT tg.id, tg.name, tg.rawname
1344 FROM {tag} tg
1345 WHERE tg.name LIKE ?";
1347 $params = array("%{$text}%");
1348 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
1352 * Get the name of a tag
1354 * @package core_tag
1355 * @access private
1356 * @param mixed $tagids the id of the tag, or an array of ids
1357 * @return mixed string name of one tag, or id-indexed array of strings
1359 function tag_get_name($tagids) {
1360 global $DB;
1362 if (!is_array($tagids)) {
1363 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
1364 return $tag->name;
1366 return false;
1369 $tag_names = array();
1370 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
1371 $tag_names[$tag->id] = $tag->name;
1374 return $tag_names;
1378 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
1379 * empty and this function won't return anything.
1381 * @package core_tag
1382 * @access private
1383 * @param int $tag_id is a single tag id
1384 * @param int $limitnum this parameter does not appear to have any function???
1385 * @return array an array of tag objects or an empty if no correlated tags are found
1387 function tag_get_correlated($tag_id, $limitnum=null) {
1388 global $DB;
1390 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
1392 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
1393 return array();
1396 // this is (and has to) return the same fields as the query in tag_get_tags
1397 $sql = "SELECT ti.id AS taginstanceid, tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
1398 FROM {tag} tg
1399 INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
1400 WHERE tg.id IN ({$tag_correlation->correlatedtags})
1401 ORDER BY ti.ordering ASC";
1402 $result = $DB->get_records_sql($sql);
1403 if (!$result) {
1404 return array();
1407 return $result;
1411 * Function that normalizes a list of tag names.
1413 * @package core_tag
1414 * @access private
1415 * @param array/string $rawtags array of tags, or a single tag.
1416 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
1417 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
1418 * (Eg: 'Banana' => 'banana').
1420 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
1422 // cache normalized tags, to prevent costly repeated calls to clean_param
1423 static $cleaned_tags_lc = array(); // lower case - use for comparison
1424 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
1426 if ( !is_array($rawtags) ) {
1427 $rawtags = array($rawtags);
1430 $result = array();
1431 foreach($rawtags as $rawtag) {
1432 $rawtag = trim($rawtag);
1433 if (!$rawtag) {
1434 continue;
1436 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
1437 $cleaned_tags_lc[$rawtag] = core_text::strtolower( clean_param($rawtag, PARAM_TAG) );
1438 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
1440 if ( $case == TAG_CASE_LOWER ) {
1441 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
1442 } else { // TAG_CASE_ORIGINAL
1443 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
1447 return $result;
1451 * Count how many records are tagged with a specific tag.
1453 * @package core_tag
1454 * @access private
1455 * @param string $record_type record to look for ('post', 'user', etc.)
1456 * @param int $tagid is a single tag id
1457 * @return int number of mathing tags.
1459 function tag_record_count($record_type, $tagid) {
1460 global $DB;
1461 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
1465 * Determine if a record is tagged with a specific tag
1467 * @package core_tag
1468 * @access private
1469 * @param string $record_type the record type to look for
1470 * @param int $record_id the record id to look for
1471 * @param string $tag a tag name
1472 * @return bool/int true if it is tagged, 0 (false) otherwise
1474 function tag_record_tagged_with($record_type, $record_id, $tag) {
1475 global $DB;
1476 if ($tagid = tag_get_id($tag)) {
1477 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
1478 } else {
1479 return 0; // tag doesn't exist
1484 * Flag a tag as inappropriate.
1486 * @param int|array $tagids a single tagid, or an array of tagids
1488 function tag_set_flag($tagids) {
1489 global $DB;
1491 $tagids = (array) $tagids;
1493 // Use the tagids to create a select statement to be used later.
1494 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids, SQL_PARAMS_NAMED);
1496 // Update all the tags to flagged.
1497 $sql = "UPDATE {tag}
1498 SET flag = flag + 1, timemodified = :time
1499 WHERE id $tagsql";
1501 // Update all the tags.
1502 $DB->execute($sql, array_merge(array('time' => time()), $tagparams));
1504 // Get all the tags.
1505 if ($tags = $DB->get_records_select('tag', 'id '. $tagsql, $tagparams, 'id ASC')) {
1506 // Loop through and fire an event for each tag that it was flagged.
1507 foreach ($tags as $tag) {
1508 $event = \core\event\tag_flagged::create(array(
1509 'objectid' => $tag->id,
1510 'relateduserid' => $tag->userid,
1511 'context' => context_system::instance(),
1512 'other' => array(
1513 'name' => $tag->name,
1514 'rawname' => $tag->rawname
1518 $event->add_record_snapshot('tag', $tag);
1519 $event->trigger();
1525 * Remove the inappropriate flag on a tag.
1527 * @param int|array $tagids a single tagid, or an array of tagids
1529 function tag_unset_flag($tagids) {
1530 global $DB;
1532 $tagids = (array) $tagids;
1534 // Use the tagids to create a select statement to be used later.
1535 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids, SQL_PARAMS_NAMED);
1537 // Update all the tags to unflagged.
1538 $sql = "UPDATE {tag}
1539 SET flag = 0, timemodified = :time
1540 WHERE id $tagsql";
1542 // Update all the tags.
1543 $DB->execute($sql, array_merge(array('time' => time()), $tagparams));
1545 // Get all the tags.
1546 if ($tags = $DB->get_records_select('tag', 'id '. $tagsql, $tagparams, 'id ASC')) {
1547 // Loop through and fire an event for each tag that it was unflagged.
1548 foreach ($tags as $tag) {
1549 $event = \core\event\tag_unflagged::create(array(
1550 'objectid' => $tag->id,
1551 'relateduserid' => $tag->userid,
1552 'context' => context_system::instance(),
1553 'other' => array(
1554 'name' => $tag->name,
1555 'rawname' => $tag->rawname
1558 $event->add_record_snapshot('tag', $tag);
1559 $event->trigger();
1565 * Return a list of page types
1567 * @package core_tag
1568 * @access private
1569 * @param string $pagetype current page type
1570 * @param stdClass $parentcontext Block's parent context
1571 * @param stdClass $currentcontext Current context of block
1573 function tag_page_type_list($pagetype, $parentcontext, $currentcontext) {
1574 return array(
1575 'tag-*'=>get_string('page-tag-x', 'tag'),
1576 'tag-index'=>get_string('page-tag-index', 'tag'),
1577 'tag-search'=>get_string('page-tag-search', 'tag'),
1578 'tag-manage'=>get_string('page-tag-manage', 'tag')