MDL-40908 core_tag: created a 'tag_created' event
[moodle.git] / tag / lib.php
CommitLineData
6bfe7aac 1<?php
000ebd5c
DM
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.
13//
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/>.
16
bcdcee90 17
c933a060 18/**
4a0daed7 19 * Moodle tag library
db32b054 20 *
bcdcee90
GGC
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.
d4be9d6d 25 *
bcdcee90
GGC
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
c933a060 31 *
986dca60 32 * BASIC INSTRUCTIONS :
33 * - to "tag a blog post" (for example):
cc033d48 34 * tag_set('post', $blog_post->id, $array_of_tags, 'core', $thecontext);
d4be9d6d 35 *
db32b054 36 * - to "remove all the tags on a blog post":
cc033d48 37 * tag_set('post', $blog_post->id, array(), 'core', $thecontext);
4a0daed7 38 *
39 * Tag set will create tags that need to be created.
d4be9d6d 40 *
bcdcee90
GGC
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
000ebd5c
DM
48 * @copyright 2007 Luiz Cruz <luiz.laydner@gmail.com>
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
c933a060 50 */
51
bcdcee90
GGC
52/**
53 * Used to require that the return value from a function is an array.
54 * @see tag_set()
55 */
db32b054 56define('TAG_RETURN_ARRAY', 0);
bcdcee90
GGC
57/**
58 * Used to require that the return value from a function is an object.
59 * @see tag_set()
60 */
db32b054 61define('TAG_RETURN_OBJECT', 1);
bcdcee90
GGC
62/**
63 * Use to specify that HTML free text is expected to be returned from a function.
64 * @see tag_display_name()
65 */
db32b054 66define('TAG_RETURN_TEXT', 2);
bcdcee90
GGC
67/**
68 * Use to specify that encoded HTML is expected to be returned from a function.
69 * @see tag_display_name()
70 */
db32b054 71define('TAG_RETURN_HTML', 3);
c933a060 72
bcdcee90
GGC
73/**
74 * Used to specify that we wish a lowercased string to be returned
75 * @see tag_normal()
76 */
db32b054 77define('TAG_CASE_LOWER', 0);
bcdcee90
GGC
78/**
79 * Used to specify that we do not wish the case of the returned string to change
80 * @see tag_normal()
81 */
db32b054 82define('TAG_CASE_ORIGINAL', 1);
d4be9d6d 83
bcdcee90
GGC
84/**
85 * Used to specify that we want all related tags returned, no matter how they are related.
86 * @see tag_get_related_tags()
87 */
537aa65c 88define('TAG_RELATED_ALL', 0);
bcdcee90
GGC
89/**
90 * Used to specify that we only want back tags that were manually related.
91 * @see tag_get_related_tags()
92 */
537aa65c 93define('TAG_RELATED_MANUAL', 1);
bcdcee90
GGC
94/**
95 * Used to specify that we only want back tags where the relationship was automatically correlated.
96 * @see tag_get_related_tags()
97 */
537aa65c 98define('TAG_RELATED_CORRELATED', 2);
99
db32b054 100///////////////////////////////////////////////////////
101/////////////////// PUBLIC TAG API ////////////////////
c933a060 102
8479c2e0 103/// Functions for settings tags //////////////////////
104
c933a060 105/**
8479c2e0 106 * Set the tags assigned to a record. This overwrites the current tags.
986dca60 107 *
bcdcee90 108 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
8479c2e0 109 *
cc033d48 110 * @package core_tag
bcdcee90 111 * @category tag
cc033d48
MN
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
c933a060 119 */
cc033d48 120function tag_set($record_type, $record_id, $tags, $component = null, $contextid = null) {
3d436d8a 121
28f64040 122 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
cc033d48 123
28f64040 124 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
125 $current_tagged_tag_name = tag_get_name($record_id);
126 }
8479c2e0 127
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);
131
28f64040 132 $current_ids = tag_get_tags_ids($record_type, $record_id);
986dca60 133 //var_dump($current_ids);
8479c2e0 134
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)) {
28f64040 139 tag_delete_instance($record_type, $record_id, $current_id);
140 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
986dca60 141 // if we are removing a tag-on-a-tag (manually related tag),
28f64040 142 // we need to remove the opposite relationship as well.
143 tag_delete_instance('tag', $current_id, $record_id);
144 }
8479c2e0 145 }
c933a060 146 }
3d436d8a 147
0f097239 148 if (empty($tags)) {
149 return true;
150 }
151
8479c2e0 152 foreach($tags as $ordering => $tag) {
153 $tag = trim($tag);
154 if (!$tag) {
db32b054 155 continue;
156 }
8479c2e0 157
158 $clean_tag = $cleaned_tags[$tag];
159 $tag_current_id = $tags_ids[$clean_tag];
986dca60 160
8479c2e0 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);
28f64040 165 $tag_current_id = $new_tag[$clean_tag];
166 }
167
cc033d48 168 tag_assign($record_type, $record_id, $tag_current_id, $ordering, 0, $component, $contextid);
28f64040 169
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;
cc033d48 174 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name, $component, $contextid);
28f64040 175 $in_recursion_semaphore = false;
db32b054 176 }
177 }
8479c2e0 178}
3d436d8a 179
8479c2e0 180/**
181 * Adds a tag to a record, without overwriting the current tags.
986dca60 182 *
cc033d48 183 * @package core_tag
bcdcee90 184 * @category tag
cc033d48
MN
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
8479c2e0 192 */
cc033d48 193function tag_set_add($record_type, $record_id, $tag, $component = null, $contextid = null) {
8479c2e0 194
195 $new_tags = array();
b91de8a5 196 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
8479c2e0 197 $new_tags[] = $current_tag->rawname;
198 }
199 $new_tags[] = $tag;
986dca60 200
cc033d48 201 return tag_set($record_type, $record_id, $new_tags, $component, $contextid);
c933a060 202}
203
204/**
8479c2e0 205 * Removes a tag from a record, without overwriting other current tags.
986dca60 206 *
cc033d48 207 * @package core_tag
bcdcee90 208 * @category tag
cc033d48
MN
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
c933a060 216 */
cc033d48 217function tag_set_delete($record_type, $record_id, $tag, $component = null, $contextid = null) {
70e9b59d 218
8479c2e0 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;
db32b054 223 }
c933a060 224 }
28f64040 225
cc033d48 226 return tag_set($record_type, $record_id, $new_tags, $component, $contextid);
8479c2e0 227}
228
229/**
bcdcee90
GGC
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).
8479c2e0 232 *
bcdcee90
GGC
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
8479c2e0 239 */
240function tag_type_set($tagid, $type) {
f7ed2687 241 global $DB;
242
09fce434 243 if ($tag = $DB->get_record('tag', array('id' => $tagid), 'id, userid, name, rawname')) {
f7ed2687 244 $tag->tagtype = $type;
8479c2e0 245 $tag->timemodified = time();
09fce434
MN
246 $DB->update_record('tag', $tag);
247
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
255 )
256 ));
257 $event->trigger();
258
259 return true;
8479c2e0 260 }
261 return false;
c933a060 262}
263
986dca60 264/**
b50d2245 265 * Set the description of a tag
986dca60 266 *
bcdcee90
GGC
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
b50d2245 275 */
276function tag_description_set($tagid, $description, $descriptionformat) {
f7ed2687 277 global $DB;
278
09fce434 279 if ($tag = $DB->get_record('tag', array('id' => $tagid), 'id, userid, name, rawname')) {
f7ed2687 280 $tag->description = $description;
281 $tag->descriptionformat = $descriptionformat;
b50d2245 282 $tag->timemodified = time();
09fce434
MN
283 $DB->update_record('tag', $tag);
284
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
292 )
293 ));
294 $event->trigger();
295
296 return true;
b50d2245 297 }
09fce434 298
b50d2245 299 return false;
300}
301
3d436d8a 302
6361e02a 303
db32b054 304
c933a060 305
c933a060 306
8479c2e0 307/// Functions for getting information about tags //////
2f4b82f4 308
309/**
8479c2e0 310 * Simple function to just return a single tag object when you know the name or something
2f4b82f4 311 *
bcdcee90
GGC
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
320 */
2f4b82f4 321function tag_get($field, $value, $returnfields='id, name, rawname') {
f7ed2687 322 global $DB;
323
8479c2e0 324 if ($field == 'name') {
2f1e464a 325 $value = core_text::strtolower($value); // To cope with input that might just be wrong case
8479c2e0 326 }
f7ed2687 327 return $DB->get_record('tag', array($field=>$value), $returnfields);
2f4b82f4 328}
329
330
c933a060 331/**
bcdcee90
GGC
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().
c933a060 335 *
bcdcee90
GGC
336 * @package core_tag
337 * @category tag
338 * @access public
986dca60 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
bcdcee90
GGC
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
db32b054 343 * @return array the array of tags
c933a060 344 */
38fb8190 345function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
f7ed2687 346 global $CFG, $DB;
347
348 $params = array();
3d436d8a 349
db32b054 350 if ($type) {
cda19b7a 351 $sql_type = "AND tg.tagtype = :type";
f7ed2687 352 $params['type'] = $type;
353 } else {
cda19b7a 354 $sql_type = '';
db32b054 355 }
537aa65c 356
38fb8190 357 $u = null;
358 if ($userid) {
359 $u = "AND ti.tiuserid = :userid ";
360 $params['userid'] = $userid;
361 }
362
f45d62e7 363 $sql = "SELECT ti.id AS taginstanceid, tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
638cf615
AD
364 FROM {tag_instance} ti
365 JOIN {tag} tg ON tg.id = ti.tagid
38fb8190 366 WHERE ti.itemtype = :recordtype AND ti.itemid = :recordid $u $sql_type
f7ed2687 367 ORDER BY ti.ordering ASC";
368 $params['recordtype'] = $record_type;
369 $params['recordid'] = $record_id;
370
73c32e86 371 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
f7ed2687 372 return $DB->get_records_sql($sql, $params);
986dca60 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
db32b054 376 // this query could help "clean it up". This causes bugs at this time.
f7ed2687 377 //$tags = $DB->get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
5183f0cc 378 // "FROM {tag_instance} ti LEFT JOIN {tag} tg ON ti.tagid = tg.id ".
537aa65c 379 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
2f9ba531 380 // "ORDER BY ti.ordering ASC");
db32b054 381}
382
383/**
384 * Get the array of tags display names, indexed by id.
986dca60 385 *
bcdcee90
GGC
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
db32b054 393 */
537aa65c 394function tag_get_tags_array($record_type, $record_id, $type=null) {
db32b054 395 $tags = array();
537aa65c 396 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
db32b054 397 $tags[$tag->id] = tag_display_name($tag);
4f81c51d 398 }
db32b054 399 return $tags;
c933a060 400}
401
402/**
bcdcee90 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.
c933a060 404 *
bcdcee90
GGC
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.
c933a060 413 */
537aa65c 414function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML, $type=null) {
db32b054 415 global $CFG;
c933a060 416
417 $tags_names = array();
8479c2e0 418 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
db32b054 419 if ($html == TAG_RETURN_TEXT) {
e7134583 420 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
db32b054 421 } else { // TAG_RETURN_HTML
422 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
423 }
c933a060 424 }
db32b054 425 return implode(', ', $tags_names);
c933a060 426}
427
4f81c51d 428/**
db32b054 429 * Get an array of tag ids associated to a record.
d4be9d6d 430 *
bcdcee90
GGC
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'
4f81c51d 438 */
537aa65c 439function tag_get_tags_ids($record_type, $record_id) {
db32b054 440 $tag_ids = array();
8479c2e0 441 foreach (tag_get_tags($record_type, $record_id) as $tag) {
28f64040 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
bcdcee90 445 // TODO MDL-31150 modify database in 2.0
28f64040 446 $tag->ordering++;
447 }
db32b054 448 $tag_ids[$tag->ordering] = $tag->id;
449 }
450 ksort($tag_ids);
451 return $tag_ids;
452}
3d436d8a 453
986dca60 454/**
db32b054 455 * Returns the database ID of a set of tags.
986dca60 456 *
bcdcee90
GGC
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.
db32b054 467 */
468function tag_get_id($tags, $return_value=null) {
f7ed2687 469 global $CFG, $DB;
470
db32b054 471 static $tag_id_cache = array();
3d436d8a 472
db32b054 473 $return_an_int = false;
474 if (!is_array($tags)) {
475 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
986dca60 476 $return_an_int = true;
db32b054 477 }
478 $tags = array($tags);
479 }
986dca60 480
db32b054 481 $result = array();
986dca60 482
bcdcee90 483 //TODO MDL-31152 test this and see if it helps performance without breaking anything
db32b054 484 //foreach($tags as $key => $tag) {
2f1e464a 485 // $clean_tag = core_text::strtolower($tag);
db32b054 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 // }
490 //}
491
492 $tags = array_values(tag_normalize($tags));
493 foreach($tags as $key => $tag) {
2f1e464a
PS
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.
db32b054 496 }
db32b054 497
f7ed2687 498 if (empty($tags)) {
499 return array();
500 }
501
502 list($tag_string, $params) = $DB->get_in_or_equal($tags);
503
cd5fdfd8
EL
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;
db32b054 510 }
4f81c51d 511 }
cd5fdfd8 512 $rs->close();
3d436d8a 513
db32b054 514 if ($return_an_int) {
515 return array_pop($result);
516 }
3d436d8a 517
db32b054 518 return $result;
c933a060 519}
520
c933a060 521
522/**
db32b054 523 * Returns tags related to a tag
d4be9d6d 524 *
db32b054 525 * Related tags of a tag come from two sources:
526 * - manually added related tags, which are tag_instance entries for that tag
bcdcee90 527 * - correlated tags, which are calculated
d4be9d6d 528 *
bcdcee90
GGC
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
c933a060 537 */
537aa65c 538function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
c933a060 539
537aa65c 540 $related_tags = array();
541
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);
c933a060 545 }
546
537aa65c 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);
552 }
db32b054 553 }
3d436d8a 554
db32b054 555 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
c933a060 556}
557
986dca60 558/**
db32b054 559 * Get a comma-separated list of tags related to another tag.
d4be9d6d 560 *
bcdcee90
GGC
561 * @package core_tag
562 * @category tag
563 * @access public
564 * @param array $related_tags the array returned by tag_get_related_tags
565 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
566 * @return string comma-separated list
c933a060 567 */
db32b054 568function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
569 global $CFG;
c933a060 570
db32b054 571 $tags_names = array();
572 foreach($related_tags as $tag) {
573 if ( $html == TAG_RETURN_TEXT) {
e7134583 574 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
db32b054 575 } else {
576 // TAG_RETURN_HTML
9fccb889 577 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
c933a060 578 }
c933a060 579 }
b50d2245 580
db32b054 581 return implode(', ', $tags_names);
c933a060 582}
583
3a597ace 584/**
db32b054 585 * Change the "value" of a tag, and update the associated 'name'.
3a597ace 586 *
bcdcee90
GGC
587 * @package core_tag
588 * @category tag
589 * @access public
590 * @param int $tagid the id of the tag to modify
591 * @param string $newrawname the new rawname
592 * @return bool true on success, false otherwise
3a597ace 593 */
73c32e86 594function tag_rename($tagid, $newrawname) {
09fce434 595 global $COURSE, $DB;
3a597ace 596
7c2cc9c8
PS
597 $norm = tag_normalize($newrawname, TAG_CASE_ORIGINAL);
598 if (! $newrawname_clean = array_shift($norm) ) {
db32b054 599 return false;
600 }
3a597ace 601
2f1e464a 602 if (! $newname_clean = core_text::strtolower($newrawname_clean)) {
2f4b82f4 603 return false;
604 }
605
606 // Prevent the rename if a tag with that name already exists
607 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
608 if ($existing->id != $tagid) { // Another tag already exists with this name
986dca60 609 return false;
2f4b82f4 610 }
db32b054 611 }
3a597ace 612
09fce434
MN
613 if ($tag = tag_get('id', $tagid, 'id, userid, name, rawname')) {
614 // Store the name before we change it.
615 $oldname = $tag->name;
616
617 $tag->rawname = $newrawname_clean;
618 $tag->name = $newname_clean;
db32b054 619 $tag->timemodified = time();
09fce434
MN
620 $DB->update_record('tag', $tag);
621
622 $event = \core\event\tag_updated::create(array(
623 'objectid' => $tag->id,
624 'relateduserid' => $tag->userid,
625 'context' => context_system::instance(),
626 'other' => array(
627 'name' => $newname_clean,
628 'rawname' => $newrawname_clean
629 )
630 ));
631 $event->set_legacy_logdata(array($COURSE->id, 'tag', 'update', 'index.php?id='. $tag->id, $oldname . '->'. $tag->name));
632 $event->trigger();
633
634 return true;
db32b054 635 }
636 return false;
3a597ace 637}
638
8479c2e0 639
c933a060 640/**
8479c2e0 641 * Delete one or more tag, and all their instances if there are any left.
986dca60 642 *
bcdcee90
GGC
643 * @package core_tag
644 * @category tag
645 * @access public
646 * @param mixed $tagids one tagid (int), or one array of tagids to delete
647 * @return bool true on success, false otherwise
c933a060 648 */
8479c2e0 649function tag_delete($tagids) {
f7ed2687 650 global $DB;
3d436d8a 651
8479c2e0 652 if (!is_array($tagids)) {
653 $tagids = array($tagids);
db32b054 654 }
3d436d8a 655
db456ec1
MN
656 // Use the tagids to create a select statement to be used later.
657 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids);
658
659 // Store the tags we are going to delete.
660 $tags = $DB->get_records_select('tag', 'id ' . $tagsql, $tagparams);
661
662 // Delete all the tag instances.
663 $select = 'WHERE tagid ' . $tagsql;
664 $sql = "DELETE FROM {tag_instance} $select";
665 $DB->execute($sql, $tagparams);
666
667 // Delete all the tag correlations.
668 $sql = "DELETE FROM {tag_correlation} $select";
669 $DB->execute($sql, $tagparams);
670
671 // Delete all the tags.
672 $select = 'WHERE id ' . $tagsql;
673 $sql = "DELETE FROM {tag} $select";
674 $DB->execute($sql, $tagparams);
675
676 // Fire an event that these tags were deleted.
677 if ($tags) {
678 $context = context_system::instance();
679 foreach ($tags as $tag) {
8bdc9cac
SH
680 // Delete all files associated with this tag
681 $fs = get_file_storage();
db456ec1 682 $files = $fs->get_area_files($context->id, 'tag', 'description', $tag->id);
8bdc9cac
SH
683 foreach ($files as $file) {
684 $file->delete();
685 }
db456ec1
MN
686
687 // Trigger an event for deleting this tag.
688 $event = \core\event\tag_deleted::create(array(
689 'objectid' => $tag->id,
690 'relateduserid' => $tag->userid,
691 'context' => $context,
692 'other' => array(
693 'name' => $tag->name,
694 'rawname' => $tag->rawname
695 )
696 ));
697 $event->add_record_snapshot('tag', $tag);
698 $event->trigger();
1acd661d 699 }
c933a060 700 }
8479c2e0 701
db456ec1 702 return true;
db32b054 703}
c933a060 704
db32b054 705/**
bcdcee90 706 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
8479c2e0 707 *
bcdcee90
GGC
708 * @package core_tag
709 * @category tag
710 * @access public
711 * @param string $record_type the type of the record for which to remove the instance
712 * @param int $record_id the id of the record for which to remove the instance
713 * @param int $tagid the tagid that needs to be removed
714 * @return bool true on success, false otherwise
db32b054 715 */
28f64040 716function tag_delete_instance($record_type, $record_id, $tagid) {
f7ed2687 717 global $CFG, $DB;
718
719 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id))) {
a72529c7 720 if (!$DB->record_exists_sql("SELECT * ".
721 "FROM {tag} tg ".
722 "WHERE tg.id = ? AND ( tg.tagtype = 'official' OR ".
b91de8a5 723 "EXISTS (SELECT 1
724 FROM {tag_instance} ti
725 WHERE ti.tagid = ?) )",
726 array($tagid, $tagid))) {
8479c2e0 727 return tag_delete($tagid);
728 }
729 } else {
730 return false;
db32b054 731 }
4a0daed7 732
733 return true;
db32b054 734}
c933a060 735
8479c2e0 736
3627b0e3 737/**
8479c2e0 738 * Function that returns the name that should be displayed for a specific tag
739 *
bcdcee90
GGC
740 * @package core_tag
741 * @category tag
742 * @access public
743 * @param object $tagobject a line out of tag table, as returned by the adobd functions
744 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
745 * @return string
3627b0e3 746 */
e7134583 747function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
8479c2e0 748 global $CFG;
749
34b93e39 750 if (!isset($tagobject->name)) {
8479c2e0 751 return '';
752 }
753
754 if (empty($CFG->keeptagnamecase)) {
755 //this is the normalized tag name
2f1e464a 756 $tagname = core_text::strtotitle($tagobject->name);
8479c2e0 757 } else {
758 //original casing of the tag name
e7134583 759 $tagname = $tagobject->rawname;
3627b0e3 760 }
e7134583 761
34b93e39
PS
762 // clean up a bit just in case the rules change again
763 $tagname = clean_param($tagname, PARAM_TAG);
764
e7134583 765 if ($html == TAG_RETURN_TEXT) {
766 return $tagname;
767 } else { // TAG_RETURN_HTML
768 return htmlspecialchars($tagname);
b91de8a5 769 }
3627b0e3 770}
771
db32b054 772/**
8479c2e0 773 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
db32b054 774 *
bcdcee90
GGC
775 * @package core_tag
776 * @category tag
777 * @access public
778 * @param string $tag tag to look for
779 * @param string $type type to restrict search to. If null, every matching record will be returned
780 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
781 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
782 * @return array of matching objects, indexed by record id, from the table containing the type requested
db32b054 783 */
8479c2e0 784function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
f7ed2687 785 global $CFG, $DB;
8479c2e0 786
787 if (!$tag || !$type) {
788 return array();
db32b054 789 }
8479c2e0 790
791 $tagid = tag_get_id($tag);
792
f7ed2687 793 $query = "SELECT it.*
794 FROM {".$type."} it INNER JOIN {tag_instance} tt ON it.id = tt.itemid
795 WHERE tt.itemtype = ? AND tt.tagid = ?";
796 $params = array($type, $tagid);
986dca60 797
798 return $DB->get_records_sql($query, $params, $limitfrom, $limitnum);
c933a060 799}
800
8479c2e0 801
802
803
db32b054 804///////////////////////////////////////////////////////
805/////////////////// PRIVATE TAG API ///////////////////
c933a060 806
807/**
bcdcee90
GGC
808 * Adds one or more tag in the database. This function should not be called directly : you should
809 * use tag_set.
d4be9d6d 810 *
bcdcee90
GGC
811 * @package core_tag
812 * @access private
813 * @param mixed $tags one tag, or an array of tags, to be created
814 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
815 * value at this time). An official tag is kept even if there are no records tagged with it.
816 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
817 * adding the tag.
c933a060 818 */
db32b054 819function tag_add($tags, $type="default") {
f7ed2687 820 global $USER, $DB;
c933a060 821
db32b054 822 if (!is_array($tags)) {
823 $tags = array($tags);
c933a060 824 }
3d436d8a 825
db32b054 826 $tag_object = new StdClass;
f7ed2687 827 $tag_object->tagtype = $type;
828 $tag_object->userid = $USER->id;
829 $tag_object->timemodified = time();
c933a060 830
db32b054 831 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL);
c933a060 832
db32b054 833 $tags_ids = array();
834 foreach($clean_tags as $tag) {
835 $tag = trim($tag);
836 if (!$tag) {
837 $tags_ids[$tag] = false;
838 } else {
986dca60 839 // note that the difference between rawname and name is only
840 // capitalization : the rawname is NOT the same at the rawtag.
841 $tag_object->rawname = $tag;
2f1e464a 842 $tag_name_lc = core_text::strtolower($tag);
f7ed2687 843 $tag_object->name = $tag_name_lc;
db32b054 844 //var_dump($tag_object);
f7ed2687 845 $tags_ids[$tag_name_lc] = $DB->insert_record('tag', $tag_object);
bf2ae267
MN
846
847 $event = \core\event\tag_created::create(array(
848 'objectid' => $tags_ids[$tag_name_lc],
849 'relateduserid' => $tag_object->userid,
850 'context' => context_system::instance(),
851 'other' => array(
852 'name' => $tag_object->name,
853 'rawname' => $tag_object->rawname
854 )
855 ));
856 $event->trigger();
db32b054 857 }
858 }
c933a060 859
db32b054 860 return $tags_ids;
c933a060 861}
862
863/**
bcdcee90 864 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
986dca60 865 *
bcdcee90 866 * @package core_tag
cc033d48
MN
867 * @access private
868 * @param string $record_type the type of the record that will be tagged
869 * @param int $record_id the id of the record that will be tagged
870 * @param string $tagid the tag id to set on the record.
871 * @param int $ordering the order of the instance for this record
872 * @param int $userid (optional) only required for course tagging
873 * @param string|null $component the component that was tagged
874 * @param int|null $contextid the context id of where this tag was assigned
875 * @return bool true on success, false otherwise
c933a060 876 */
cc033d48 877function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
f7ed2687 878 global $DB;
c933a060 879
cc033d48
MN
880 if ($component === null || $contextid === null) {
881 debugging('You should specify the component and contextid of the item being tagged in your call to tag_assign.',
882 DEBUG_DEVELOPER);
883 }
884
cfa2c6e1
MN
885 // Get the tag.
886 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
887
38fb8190 888 if ( $tag_instance_object = $DB->get_record('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id, 'tiuserid'=>$userid), 'id')) {
f7ed2687 889 $tag_instance_object->ordering = $ordering;
db32b054 890 $tag_instance_object->timemodified = time();
cfa2c6e1
MN
891
892 $DB->update_record('tag_instance', $tag_instance_object);
986dca60 893 } else {
db32b054 894 $tag_instance_object = new StdClass;
f7ed2687 895 $tag_instance_object->tagid = $tagid;
cc033d48 896 $tag_instance_object->component = $component;
f7ed2687 897 $tag_instance_object->itemid = $record_id;
898 $tag_instance_object->itemtype = $record_type;
cc033d48 899 $tag_instance_object->contextid = $contextid;
f7ed2687 900 $tag_instance_object->ordering = $ordering;
cc033d48
MN
901 $tag_instance_object->timecreated = time();
902 $tag_instance_object->timemodified = $tag_instance_object->timecreated;
38fb8190 903 $tag_instance_object->tiuserid = $userid;
cc033d48 904
cfa2c6e1
MN
905 $tag_instance_object->id = $DB->insert_record('tag_instance', $tag_instance_object);
906 }
907
908 // We can not fire an event with 'null' as the contextid.
909 if (is_null($contextid)) {
910 $contextid = context_system::instance()->id;
c933a060 911 }
cfa2c6e1
MN
912
913 // Trigger item tagged event.
914 $event = \core\event\item_tagged::create(array(
915 'objectid' => $tag_instance_object->id,
916 'contextid' => $contextid,
917 'other' => array(
918 'tagid' => $tagid,
919 'tagname' => $tag->name,
920 'tagrawname' => $tag->rawname,
921 'itemid' => $record_id,
922 'itemtype' => $record_type
923 )
924 ));
925 $event->trigger();
926
927 return true;
c933a060 928}
929
930/**
db32b054 931 * Function that returns tags that start with some text, for use by the autocomplete feature
d4be9d6d 932 *
bcdcee90
GGC
933 * @package core_tag
934 * @access private
935 * @param string $text string that the tag names will be matched against
936 * @return mixed an array of objects, or false if no records were found or an error occured.
c933a060 937 */
db32b054 938function tag_autocomplete($text) {
f7ed2687 939 global $DB;
940 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
941 FROM {tag} tg
2f1e464a 942 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
c933a060 943}
944
986dca60 945/**
9545cdba 946 * Clean up the tag tables, making sure all tagged object still exists.
947 *
bcdcee90
GGC
948 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
949 * 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
950 * call: don't run at peak time.
951 *
952 * @package core_tag
953 * @access private
954 * @todo MDL-31212 Update tag cleanup sql so that it supports multiple types of tags
9545cdba 955 */
956function tag_cleanup() {
f7ed2687 957 global $DB;
9545cdba 958
f7ed2687 959 $instances = $DB->get_recordset('tag_instance');
9545cdba 960
084426c5 961 // cleanup tag instances
f7ed2687 962 foreach ($instances as $instance) {
9545cdba 963 $delete = false;
986dca60 964
f7ed2687 965 if (!$DB->record_exists('tag', array('id'=>$instance->tagid))) {
9545cdba 966 // if the tag has been removed, instance should be deleted.
967 $delete = true;
968 } else {
969 switch ($instance->itemtype) {
970 case 'user': // users are marked as deleted, but not actually deleted
f7ed2687 971 if ($DB->record_exists('user', array('id'=>$instance->itemid, 'deleted'=>1))) {
9545cdba 972 $delete = true;
973 }
974 break;
975 default: // anything else, if the instance is not there, delete.
f7ed2687 976 if (!$DB->record_exists($instance->itemtype, array('id'=>$instance->itemid))) {
9545cdba 977 $delete = true;
978 }
979 break;
980 }
981 }
982 if ($delete) {
983 tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid);
984 //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER);
985 }
986 }
f7ed2687 987 $instances->close();
9545cdba 988
bcdcee90 989 // TODO MDL-31212 this will only clean tags of type 'default'. This is good as
9545cdba 990 // it won't delete 'official' tags, but the day we get more than two
991 // types, we need to fix this.
f7ed2687 992 $unused_tags = $DB->get_recordset_sql("SELECT tg.id
993 FROM {tag} tg
994 WHERE tg.tagtype = 'default'
995 AND NOT EXISTS (
996 SELECT 'x'
997 FROM {tag_instance} ti
998 WHERE ti.tagid = tg.id
999 )");
9545cdba 1000
084426c5 1001 // cleanup tags
f7ed2687 1002 foreach ($unused_tags as $unused_tag) {
084426c5 1003 tag_delete($unused_tag->id);
1004 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
9545cdba 1005 }
f7ed2687 1006 $unused_tags->close();
9545cdba 1007}
1008
c933a060 1009/**
bcdcee90 1010 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
db32b054 1011 *
bcdcee90 1012 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
d4be9d6d 1013 *
bcdcee90
GGC
1014 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
1015 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
d4be9d6d 1016 *
bcdcee90
GGC
1017 * @package core_tag
1018 * @access private
1019 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
c933a060 1020 */
78defd5c 1021function tag_compute_correlations($mincorrelation = 2) {
f7ed2687 1022 global $DB;
3d436d8a 1023
78defd5c
SH
1024 // This mighty one line query fetches a row from the database for every
1025 // individual tag correlation. We then need to process the rows collecting
1026 // the correlations for each tag id.
1027 // The fields used by this query are as follows:
1028 // tagid : This is the tag id, there should be at least $mincorrelation
1029 // rows for each tag id.
1030 // correlation : This is the tag id that correlates to the above tagid field.
1031 // correlationid : This is the id of the row in the tag_correlation table that
1032 // relates to the tagid field and will be NULL if there are no
1033 // existing correlations
2650c547 1034 $sql = 'SELECT pairs.tagid, pairs.correlation, pairs.ocurrences, co.id AS correlationid
1c2cfff0
EL
1035 FROM (
1036 SELECT ta.tagid, tb.tagid AS correlation, COUNT(*) AS ocurrences
1037 FROM {tag_instance} ta
1038 JOIN {tag_instance} tb ON (ta.itemtype = tb.itemtype AND ta.itemid = tb.itemid AND ta.tagid <> tb.tagid)
1039 GROUP BY ta.tagid, tb.tagid
1040 HAVING COUNT(*) > :mincorrelation
1041 ) pairs
1042 LEFT JOIN {tag_correlation} co ON co.tagid = pairs.tagid
1043 ORDER BY pairs.tagid ASC, pairs.ocurrences DESC, pairs.correlation ASC';
78defd5c
SH
1044 $rs = $DB->get_recordset_sql($sql, array('mincorrelation' => $mincorrelation));
1045
1046 // Set up an empty tag correlation object
1047 $tagcorrelation = new stdClass;
1048 $tagcorrelation->id = null;
1049 $tagcorrelation->tagid = null;
1050 $tagcorrelation->correlatedtags = array();
1051
638cf615 1052 // We store each correlation id in this array so we can remove any correlations
2650c547
SH
1053 // that no longer exist.
1054 $correlations = array();
1055
78defd5c 1056 // Iterate each row of the result set and build them into tag correlations.
638cf615
AD
1057 // We add all of a tag's correlations to $tagcorrelation->correlatedtags[]
1058 // then save the $tagcorrelation object
78defd5c
SH
1059 foreach ($rs as $row) {
1060 if ($row->tagid != $tagcorrelation->tagid) {
638cf615 1061 // The tag id has changed so we have all of the correlations for this tag
2650c547
SH
1062 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
1063 if ($tagcorrelationid) {
1064 $correlations[] = $tagcorrelationid;
1065 }
78defd5c
SH
1066 // Now we reset the tag correlation object so we can reuse it and set it
1067 // up for the current record.
1068 $tagcorrelation = new stdClass;
1069 $tagcorrelation->id = $row->correlationid;
1070 $tagcorrelation->tagid = $row->tagid;
1071 $tagcorrelation->correlatedtags = array();
db32b054 1072 }
638cf615 1073 //Save the correlation on the tag correlation object
78defd5c
SH
1074 $tagcorrelation->correlatedtags[] = $row->correlation;
1075 }
1076 // Update the current correlation after the last record.
2650c547
SH
1077 $tagcorrelationid = tag_process_computed_correlation($tagcorrelation);
1078 if ($tagcorrelationid) {
1079 $correlations[] = $tagcorrelationid;
1080 }
1081
c933a060 1082
78defd5c
SH
1083 // Close the recordset
1084 $rs->close();
2650c547
SH
1085
1086 // Remove any correlations that weren't just identified
638cf615
AD
1087 if (empty($correlations)) {
1088 //there are no tag correlations
1089 $DB->delete_records('tag_correlation');
1090 } else {
1091 list($sql, $params) = $DB->get_in_or_equal($correlations, SQL_PARAMS_NAMED, 'param0000', false);
1092 $DB->delete_records_select('tag_correlation', 'id '.$sql, $params);
1093 }
78defd5c 1094}
844f9c15 1095
78defd5c 1096/**
bcdcee90 1097 * This function processes a tag correlation and makes changes in the database as required.
78defd5c 1098 *
bcdcee90 1099 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
78defd5c 1100 *
bcdcee90
GGC
1101 * @package core_tag
1102 * @access private
1103 * @param stdClass $tagcorrelation
1104 * @return int/bool The id of the tag correlation that was just processed or false.
78defd5c
SH
1105 */
1106function tag_process_computed_correlation(stdClass $tagcorrelation) {
1107 global $DB;
db32b054 1108
78defd5c
SH
1109 // You must provide a tagid and correlatedtags must be set and be an array
1110 if (empty($tagcorrelation->tagid) || !isset($tagcorrelation->correlatedtags) || !is_array($tagcorrelation->correlatedtags)) {
1111 return false;
3d436d8a 1112 }
78defd5c 1113
78defd5c
SH
1114 $tagcorrelation->correlatedtags = join(',', $tagcorrelation->correlatedtags);
1115 if (!empty($tagcorrelation->id)) {
1116 // The tag correlation already exists so update it
1117 $DB->update_record('tag_correlation', $tagcorrelation);
1118 } else {
1119 // This is a new correlation to insert
2650c547 1120 $tagcorrelation->id = $DB->insert_record('tag_correlation', $tagcorrelation);
78defd5c 1121 }
2650c547 1122 return $tagcorrelation->id;
db32b054 1123}
1124
1125/**
1126 * Tasks that should be performed at cron time
bcdcee90
GGC
1127 *
1128 * @package core_tag
1129 * @access private
db32b054 1130 */
1131function tag_cron() {
1132 tag_compute_correlations();
0f5e5f5c 1133 tag_cleanup();
db32b054 1134}
1135
0f039283 1136/**
1137 * Search for tags with names that match some text
1138 *
bcdcee90
GGC
1139 * @package core_tag
1140 * @access private
1141 * @param string $text escaped string that the tag names will be matched against
1142 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
1143 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
1144 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
1145 * @return array/boolean an array of objects, or false if no records were found or an error occured.
0f039283 1146 */
1147function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
f7ed2687 1148 global $DB;
0f039283 1149
7c2cc9c8
PS
1150 $norm = tag_normalize($text, TAG_CASE_LOWER);
1151 $text = array_shift($norm);
0f039283 1152
1153 if ($ordered) {
f7ed2687 1154 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
1155 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
1156 WHERE tg.name LIKE ?
1157 GROUP BY tg.id, tg.name, tg.rawname
1158 ORDER BY count DESC";
0f039283 1159 } else {
f7ed2687 1160 $query = "SELECT tg.id, tg.name, tg.rawname
1161 FROM {tag} tg
1162 WHERE tg.name LIKE ?";
0f039283 1163 }
f7ed2687 1164 $params = array("%{$text}%");
1165 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
0f039283 1166}
1167
986dca60 1168/**
db32b054 1169 * Get the name of a tag
986dca60 1170 *
bcdcee90
GGC
1171 * @package core_tag
1172 * @access private
1173 * @param mixed $tagids the id of the tag, or an array of ids
1174 * @return mixed string name of one tag, or id-indexed array of strings
db32b054 1175 */
1176function tag_get_name($tagids) {
f7ed2687 1177 global $DB;
3d436d8a 1178
f7ed2687 1179 if (!is_array($tagids)) {
1180 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
1181 return $tag->name;
1182 }
1183 return false;
db32b054 1184 }
c933a060 1185
db32b054 1186 $tag_names = array();
986dca60 1187 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
db32b054 1188 $tag_names[$tag->id] = $tag->name;
1189 }
c933a060 1190
db32b054 1191 return $tag_names;
c933a060 1192}
1193
1194/**
bcdcee90
GGC
1195 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
1196 * empty and this function won't return anything.
c933a060 1197 *
bcdcee90
GGC
1198 * @package core_tag
1199 * @access private
1200 * @param int $tag_id is a single tag id
1201 * @param int $limitnum this parameter does not appear to have any function???
1202 * @return array an array of tag objects or an empty if no correlated tags are found
c933a060 1203 */
db32b054 1204function tag_get_correlated($tag_id, $limitnum=null) {
f7ed2687 1205 global $DB;
3d436d8a 1206
f7ed2687 1207 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
c933a060 1208
db32b054 1209 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
1210 return array();
c933a060 1211 }
986dca60 1212
73c32e86 1213 // this is (and has to) return the same fields as the query in tag_get_tags
638cf615 1214 $sql = "SELECT DISTINCT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
e2a64d83 1215 FROM {tag} tg
638cf615 1216 INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
e2a64d83
SH
1217 WHERE tg.id IN ({$tag_correlation->correlatedtags})";
1218 $result = $DB->get_records_sql($sql);
1219 if (!$result) {
db32b054 1220 return array();
c933a060 1221 }
986dca60 1222
db32b054 1223 return $result;
c933a060 1224}
1225
c933a060 1226/**
db32b054 1227 * Function that normalizes a list of tag names.
c933a060 1228 *
bcdcee90
GGC
1229 * @package core_tag
1230 * @access private
1231 * @param array/string $rawtags array of tags, or a single tag.
1232 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
1233 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
1234 * (Eg: 'Banana' => 'banana').
c933a060 1235 */
db32b054 1236function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
1237
0f039283 1238 // cache normalized tags, to prevent costly repeated calls to clean_param
db32b054 1239 static $cleaned_tags_lc = array(); // lower case - use for comparison
1240 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
c933a060 1241
db32b054 1242 if ( !is_array($rawtags) ) {
1243 $rawtags = array($rawtags);
1244 }
c933a060 1245
db32b054 1246 $result = array();
1247 foreach($rawtags as $rawtag) {
1248 $rawtag = trim($rawtag);
1249 if (!$rawtag) {
1250 continue;
1251 }
1252 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
2f1e464a 1253 $cleaned_tags_lc[$rawtag] = core_text::strtolower( clean_param($rawtag, PARAM_TAG) );
db32b054 1254 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
1255 }
986dca60 1256 if ( $case == TAG_CASE_LOWER ) {
db32b054 1257 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
1258 } else { // TAG_CASE_ORIGINAL
1259 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
1260 }
1261 }
986dca60 1262
db32b054 1263 return $result;
c933a060 1264}
1265
1266/**
bcdcee90 1267 * Count how many records are tagged with a specific tag.
c933a060 1268 *
bcdcee90
GGC
1269 * @package core_tag
1270 * @access private
1271 * @param string $record_type record to look for ('post', 'user', etc.)
1272 * @param int $tagid is a single tag id
1273 * @return int number of mathing tags.
c933a060 1274 */
0f039283 1275function tag_record_count($record_type, $tagid) {
f7ed2687 1276 global $DB;
1277 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
0f039283 1278}
c933a060 1279
0f039283 1280/**
986dca60 1281 * Determine if a record is tagged with a specific tag
0f039283 1282 *
bcdcee90
GGC
1283 * @package core_tag
1284 * @access private
1285 * @param string $record_type the record type to look for
1286 * @param int $record_id the record id to look for
1287 * @param string $tag a tag name
1288 * @return bool/int true if it is tagged, 0 (false) otherwise
0f039283 1289 */
1290function tag_record_tagged_with($record_type, $record_id, $tag) {
f7ed2687 1291 global $DB;
0f039283 1292 if ($tagid = tag_get_id($tag)) {
f7ed2687 1293 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
c933a060 1294 } else {
0f039283 1295 return 0; // tag doesn't exist
c933a060 1296 }
c933a060 1297}
1298
1299/**
6298494d 1300 * Flag a tag as inappropriate.
986dca60 1301 *
6298494d 1302 * @param int|array $tagids a single tagid, or an array of tagids
c933a060 1303 */
db32b054 1304function tag_set_flag($tagids) {
f7ed2687 1305 global $DB;
1306
6298494d
MN
1307 $tagids = (array) $tagids;
1308
1309 // Use the tagids to create a select statement to be used later.
1310 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids, SQL_PARAMS_NAMED);
1311
1312 // Update all the tags to flagged.
1313 $sql = "UPDATE {tag}
1314 SET flag = flag + 1, timemodified = :time
1315 WHERE id $tagsql";
1316
1317 // Update all the tags.
1318 $DB->execute($sql, array_merge(array('time' => time()), $tagparams));
1319
1320 // Get all the tags.
1321 if ($tags = $DB->get_records_select('tag', 'id '. $tagsql, $tagparams, 'id ASC')) {
1322 // Loop through and fire an event for each tag that it was flagged.
1323 foreach ($tags as $tag) {
1324 $event = \core\event\tag_flagged::create(array(
1325 'objectid' => $tag->id,
1326 'relateduserid' => $tag->userid,
1327 'context' => context_system::instance(),
1328 'other' => array(
1329 'name' => $tag->name,
1330 'rawname' => $tag->rawname
1331 )
1332
1333 ));
1334 $event->add_record_snapshot('tag', $tag);
1335 $event->trigger();
1336 }
c933a060 1337 }
1338}
1339
986dca60 1340/**
097bd4cd 1341 * Remove the inappropriate flag on a tag.
986dca60 1342 *
097bd4cd 1343 * @param int|array $tagids a single tagid, or an array of tagids
c933a060 1344 */
db32b054 1345function tag_unset_flag($tagids) {
f7ed2687 1346 global $DB;
d4be9d6d 1347
097bd4cd
MN
1348 $tagids = (array) $tagids;
1349
1350 // Use the tagids to create a select statement to be used later.
1351 list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids, SQL_PARAMS_NAMED);
1352
1353 // Update all the tags to unflagged.
1354 $sql = "UPDATE {tag}
1355 SET flag = 0, timemodified = :time
1356 WHERE id $tagsql";
1357
1358 // Update all the tags.
1359 $DB->execute($sql, array_merge(array('time' => time()), $tagparams));
1360
1361 // Get all the tags.
1362 if ($tags = $DB->get_records_select('tag', 'id '. $tagsql, $tagparams, 'id ASC')) {
1363 // Loop through and fire an event for each tag that it was unflagged.
1364 foreach ($tags as $tag) {
1365 $event = \core\event\tag_unflagged::create(array(
1366 'objectid' => $tag->id,
1367 'relateduserid' => $tag->userid,
1368 'context' => context_system::instance(),
1369 'other' => array(
1370 'name' => $tag->name,
1371 'rawname' => $tag->rawname
1372 )
1373 ));
1374 $event->add_record_snapshot('tag', $tag);
1375 $event->trigger();
1376 }
ab86d9c7 1377 }
c933a060 1378}
b1627a92 1379
b1627a92
DC
1380/**
1381 * Return a list of page types
bcdcee90
GGC
1382 *
1383 * @package core_tag
1384 * @access private
1385 * @param string $pagetype current page type
1386 * @param stdClass $parentcontext Block's parent context
1387 * @param stdClass $currentcontext Current context of block
b1627a92 1388 */
b38e2e28 1389function tag_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
1390 return array(
1391 'tag-*'=>get_string('page-tag-x', 'tag'),
1392 'tag-index'=>get_string('page-tag-index', 'tag'),
1393 'tag-search'=>get_string('page-tag-search', 'tag'),
1394 'tag-manage'=>get_string('page-tag-manage', 'tag')
1395 );
1396}