MDL-25754 improved tag sanitisation and fixed tag autocomplete
[moodle.git] / tag / lib.php
CommitLineData
6bfe7aac 1<?php
4d4dac81 2
000ebd5c
DM
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
c933a060 18/**
4a0daed7 19 * Moodle tag library
db32b054 20 *
986dca60 21 * Tag strings : you can use any character in tags, except the comma (which is
22 * the separator) and the '\' (backslash). Note that many spaces (or other
23 * blank characters) will get "compressed" into one. A tag string is always a
4a0daed7 24 * rawurlencode'd string. This is the same behavior as http://del.icio.us.
db32b054 25 *
986dca60 26 * A "record" is a php array (note that an object will work too) that contains
27 * the following variables :
db32b054 28 * - type: the table containing the record that we are tagging (eg: for a
29 * blog, this is table 'post', and for a user it is 'user')
986dca60 30 * - id: the id of the record
d4be9d6d 31 *
986dca60 32 * TODO: turn this into a full-fledged categorization system. This could start
33 * by modifying (removing, probably) the 'tag type' to use another table
34 * describing the relationship between tags (parents, sibling, etc.), which
db32b054 35 * could then be merged with the 'course categorization' system...
c933a060 36 *
986dca60 37 * BASIC INSTRUCTIONS :
38 * - to "tag a blog post" (for example):
4a0daed7 39 * tag_set('post', $blog_post->id, $array_of_tags);
d4be9d6d 40 *
db32b054 41 * - to "remove all the tags on a blog post":
4a0daed7 42 * tag_set('post', $blog_post->id, array());
43 *
44 * Tag set will create tags that need to be created.
d4be9d6d 45 *
000ebd5c 46 * @package core
4a0daed7 47 * @subpackage tag
48 * @see http://www.php.net/manual/en/function.urlencode.php
000ebd5c
DM
49 * @copyright 2007 Luiz Cruz <luiz.laydner@gmail.com>
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
c933a060 51 */
52
db32b054 53define('TAG_RETURN_ARRAY', 0);
54define('TAG_RETURN_OBJECT', 1);
55define('TAG_RETURN_TEXT', 2);
56define('TAG_RETURN_HTML', 3);
c933a060 57
db32b054 58define('TAG_CASE_LOWER', 0);
59define('TAG_CASE_ORIGINAL', 1);
d4be9d6d 60
537aa65c 61define('TAG_RELATED_ALL', 0);
62define('TAG_RELATED_MANUAL', 1);
63define('TAG_RELATED_CORRELATED', 2);
64
db32b054 65///////////////////////////////////////////////////////
66/////////////////// PUBLIC TAG API ////////////////////
c933a060 67
8479c2e0 68/// Functions for settings tags //////////////////////
69
c933a060 70/**
8479c2e0 71 * Set the tags assigned to a record. This overwrites the current tags.
986dca60 72 *
73 * This function is meant to be fed the string coming up from the user
8479c2e0 74 * interface, which contains all tags assigned to a record.
75 *
986dca60 76 * @param string $record_type the type of record to tag ('post' for blogs,
8479c2e0 77 * 'user' for users, 'tag' for tags, etc.
78 * @param int $record_id the id of the record to tag
986dca60 79 * @param array $tags the array of tags to set on the record. If
8479c2e0 80 * given an empty array, all tags will be removed.
986dca60 81 * @return void
c933a060 82 */
b91de8a5 83function tag_set($record_type, $record_id, $tags) {
3d436d8a 84
28f64040 85 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
86 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
87 $current_tagged_tag_name = tag_get_name($record_id);
88 }
8479c2e0 89
90 $tags_ids = tag_get_id($tags, TAG_RETURN_ARRAY); // force an array, even if we only have one tag.
91 $cleaned_tags = tag_normalize($tags);
92 //echo 'tags-in-tag_set'; var_dump($tags); var_dump($tags_ids); var_dump($cleaned_tags);
93
28f64040 94 $current_ids = tag_get_tags_ids($record_type, $record_id);
986dca60 95 //var_dump($current_ids);
8479c2e0 96
97 // for data coherence reasons, it's better to remove deleted tags
98 // before adding new data: ordering could be duplicated.
99 foreach($current_ids as $current_id) {
100 if (!in_array($current_id, $tags_ids)) {
28f64040 101 tag_delete_instance($record_type, $record_id, $current_id);
102 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
986dca60 103 // if we are removing a tag-on-a-tag (manually related tag),
28f64040 104 // we need to remove the opposite relationship as well.
105 tag_delete_instance('tag', $current_id, $record_id);
106 }
8479c2e0 107 }
c933a060 108 }
3d436d8a 109
0f097239 110 if (empty($tags)) {
111 return true;
112 }
113
8479c2e0 114 foreach($tags as $ordering => $tag) {
115 $tag = trim($tag);
116 if (!$tag) {
db32b054 117 continue;
118 }
8479c2e0 119
120 $clean_tag = $cleaned_tags[$tag];
121 $tag_current_id = $tags_ids[$clean_tag];
986dca60 122
8479c2e0 123 if ( is_null($tag_current_id) ) {
124 // create new tags
125 //echo "call to add tag $tag\n";
126 $new_tag = tag_add($tag);
28f64040 127 $tag_current_id = $new_tag[$clean_tag];
128 }
129
b91de8a5 130 tag_assign($record_type, $record_id, $tag_current_id, $ordering);
28f64040 131
132 // if we are tagging a tag (adding a manually-assigned related tag), we
133 // need to create the opposite relationship as well.
134 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
135 $in_recursion_semaphore = true;
136 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name);
137 $in_recursion_semaphore = false;
db32b054 138 }
139 }
8479c2e0 140}
3d436d8a 141
8479c2e0 142/**
143 * Adds a tag to a record, without overwriting the current tags.
986dca60 144 *
145 * @param string $record_type the type of record to tag ('post' for blogs,
8479c2e0 146 * 'user' for users, etc.
147 * @param int $record_id the id of the record to tag
148 * @param string $tag the tag to add
149 * @return void
150 */
b91de8a5 151function tag_set_add($record_type, $record_id, $tag) {
8479c2e0 152
153 $new_tags = array();
b91de8a5 154 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
8479c2e0 155 $new_tags[] = $current_tag->rawname;
156 }
157 $new_tags[] = $tag;
986dca60 158
b91de8a5 159 return tag_set($record_type, $record_id, $new_tags);
c933a060 160}
161
162/**
8479c2e0 163 * Removes a tag from a record, without overwriting other current tags.
986dca60 164 *
165 * @param string $record_type the type of record to tag ('post' for blogs,
8479c2e0 166 * 'user' for users, etc.
167 * @param int $record_id the id of the record to tag
168 * @param string $tag the tag to delete
169 * @return void
c933a060 170 */
8479c2e0 171function tag_set_delete($record_type, $record_id, $tag) {
70e9b59d 172
8479c2e0 173 $new_tags = array();
174 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
175 if ($current_tag->name != $tag) { // Keep all tags but the one specified
176 $new_tags[] = $current_tag->name;
db32b054 177 }
c933a060 178 }
28f64040 179
8479c2e0 180 return tag_set($record_type, $record_id, $new_tags);
181}
182
183/**
184 * Set the type of a tag. At this time (version 1.9) the possible values
185 * are 'default' or 'official'. Official tags will be displayed separately "at
186 * tagging time" (while selecting the tags to apply to a record).
187 *
188 * @param string $tagid tagid to modify
189 * @param string $type either 'default' or 'official'
190 * @return true on success, false otherwise
191 */
192function tag_type_set($tagid, $type) {
f7ed2687 193 global $DB;
194
195 if ($tag = $DB->get_record('tag', array('id'=>$tagid), 'id')) {
196 $tag->tagtype = $type;
8479c2e0 197 $tag->timemodified = time();
f7ed2687 198 return $DB->update_record('tag', $tag);
8479c2e0 199 }
200 return false;
c933a060 201}
202
8479c2e0 203
986dca60 204/**
b50d2245 205 * Set the description of a tag
986dca60 206 *
b50d2245 207 * @param int $tagid the id of the tag
208 * @param string $description the description
209 * @param int $descriptionformat the moodle text format of the description
986dca60 210 * @return true on success, false otherwise
b50d2245 211 */
212function tag_description_set($tagid, $description, $descriptionformat) {
f7ed2687 213 global $DB;
214
215 if ($tag = $DB->get_record('tag', array('id'=>$tagid),'id')) {
216 $tag->description = $description;
217 $tag->descriptionformat = $descriptionformat;
b50d2245 218 $tag->timemodified = time();
f7ed2687 219 return $DB->update_record('tag', $tag);
b50d2245 220 }
221 return false;
222}
223
3d436d8a 224
6361e02a 225
db32b054 226
c933a060 227
c933a060 228
8479c2e0 229/// Functions for getting information about tags //////
2f4b82f4 230
231/**
8479c2e0 232 * Simple function to just return a single tag object when you know the name or something
2f4b82f4 233 *
234 * @param string $field which field do we use to identify the tag: id, name or rawname
235 * @param string $value the required value of the aforementioned field
236 * @param string $returnfields which fields do we want returned?
237 * @return tag object
238 *
239 **/
240function tag_get($field, $value, $returnfields='id, name, rawname') {
f7ed2687 241 global $DB;
242
8479c2e0 243 if ($field == 'name') {
f7ed2687 244 $value = moodle_strtolower($value); // To cope with input that might just be wrong case
8479c2e0 245 }
f7ed2687 246 return $DB->get_record('tag', array($field=>$value), $returnfields);
2f4b82f4 247}
248
249
c933a060 250/**
986dca60 251 * Get the array of db record of tags associated to a record (instances). Use
db32b054 252 * tag_get_tags_csv to get the same information in a comma-separated string.
c933a060 253 *
986dca60 254 * @param string $record_type the record type for which we want to get the tags
255 * @param int $record_id the record id for which we want to get the tags
db32b054 256 * @param string $type the tag type (either 'default' or 'official'). By default,
257 * all tags are returned.
38fb8190 258 * @param int $userid optional only required for course tagging
db32b054 259 * @return array the array of tags
c933a060 260 */
38fb8190 261function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
f7ed2687 262 global $CFG, $DB;
263
264 $params = array();
3d436d8a 265
db32b054 266 if ($type) {
cda19b7a 267 $sql_type = "AND tg.tagtype = :type";
f7ed2687 268 $params['type'] = $type;
269 } else {
cda19b7a 270 $sql_type = '';
db32b054 271 }
537aa65c 272
38fb8190 273 $u = null;
274 if ($userid) {
275 $u = "AND ti.tiuserid = :userid ";
276 $params['userid'] = $userid;
277 }
278
f7ed2687 279 $sql = "SELECT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
280 FROM {tag_instance} ti JOIN {tag} tg ON tg.id = ti.tagid
38fb8190 281 WHERE ti.itemtype = :recordtype AND ti.itemid = :recordid $u $sql_type
f7ed2687 282 ORDER BY ti.ordering ASC";
283 $params['recordtype'] = $record_type;
284 $params['recordid'] = $record_id;
285
73c32e86 286 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
f7ed2687 287 return $DB->get_records_sql($sql, $params);
986dca60 288 // This version of the query, reversing the ON clause, "correctly" returns
289 // a row with NULL values for instances that are still in the DB even though
290 // the tag has been deleted. This shouldn't happen, but if it did, using
db32b054 291 // this query could help "clean it up". This causes bugs at this time.
f7ed2687 292 //$tags = $DB->get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
5183f0cc 293 // "FROM {tag_instance} ti LEFT JOIN {tag} tg ON ti.tagid = tg.id ".
537aa65c 294 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
2f9ba531 295 // "ORDER BY ti.ordering ASC");
db32b054 296}
297
298/**
299 * Get the array of tags display names, indexed by id.
986dca60 300 *
537aa65c 301 * @param string $record_type the record type for which we want to get the tags
302 * @param int $record_id the record id for which we want to get the tags
db32b054 303 * @param string $type the tag type (either 'default' or 'official'). By default,
304 * all tags are returned.
305 * @return array the array of tags (with the value returned by tag_display_name), indexed by id
306 */
537aa65c 307function tag_get_tags_array($record_type, $record_id, $type=null) {
db32b054 308 $tags = array();
537aa65c 309 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
db32b054 310 $tags[$tag->id] = tag_display_name($tag);
4f81c51d 311 }
db32b054 312 return $tags;
c933a060 313}
314
315/**
db32b054 316 * Get a comma-separated string of tags associated to a record. Use tag_get_tags
317 * to get the same information in an array.
c933a060 318 *
537aa65c 319 * @param string $record_type the record type for which we want to get the tags
320 * @param int $record_id the record id for which we want to get the tags
db32b054 321 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending
322 * on the type of output desired
323 * @param string $type either 'official' or 'default', if null, all tags are
324 * returned
325 * @return string the comma-separated list of tags.
c933a060 326 */
537aa65c 327function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML, $type=null) {
db32b054 328 global $CFG;
c933a060 329
330 $tags_names = array();
8479c2e0 331 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
db32b054 332 if ($html == TAG_RETURN_TEXT) {
e7134583 333 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
db32b054 334 } else { // TAG_RETURN_HTML
335 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
336 }
c933a060 337 }
db32b054 338 return implode(', ', $tags_names);
c933a060 339}
340
4f81c51d 341/**
db32b054 342 * Get an array of tag ids associated to a record.
d4be9d6d 343 *
28f64040 344 * @param string $record_type the record type for which we want to get the tags
537aa65c 345 * @param int $record_id the record id for which we want to get the tags
db32b054 346 * @return array of tag ids, indexed and sorted by 'ordering'
4f81c51d 347 */
537aa65c 348function tag_get_tags_ids($record_type, $record_id) {
986dca60 349
db32b054 350 $tag_ids = array();
8479c2e0 351 foreach (tag_get_tags($record_type, $record_id) as $tag) {
28f64040 352 if ( array_key_exists($tag->ordering, $tag_ids) ) {
353 // until we can add a unique constraint, in table tag_instance,
354 // on (itemtype, itemid, ordering), this is needed to prevent a bug
355 // TODO : modify database in 2.0
356 $tag->ordering++;
357 }
db32b054 358 $tag_ids[$tag->ordering] = $tag->id;
359 }
360 ksort($tag_ids);
361 return $tag_ids;
362}
3d436d8a 363
986dca60 364/**
db32b054 365 * Returns the database ID of a set of tags.
986dca60 366 *
db32b054 367 * @param mixed $tags one tag, or array of tags, to look for.
986dca60 368 * @param bool $return_value specify the type of the returned value. Either
369 * TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default). If TAG_RETURN_ARRAY
370 * is specified, an array will be returned even if only one tag was
dee71a16 371 * passed in $tags.
986dca60 372 * @return mixed tag-indexed array of ids (or objects, if second parameter is
373 * TAG_RETURN_OBJECT), or only an int, if only one tag is given *and* the
dee71a16 374 * second parameter is null. No value for a key means the tag wasn't found.
db32b054 375 */
376function tag_get_id($tags, $return_value=null) {
f7ed2687 377 global $CFG, $DB;
378
db32b054 379 static $tag_id_cache = array();
3d436d8a 380
db32b054 381 $return_an_int = false;
382 if (!is_array($tags)) {
383 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
986dca60 384 $return_an_int = true;
db32b054 385 }
386 $tags = array($tags);
387 }
986dca60 388
db32b054 389 $result = array();
986dca60 390
db32b054 391 //TODO: test this and see if it helps performance without breaking anything
392 //foreach($tags as $key => $tag) {
393 // $clean_tag = moodle_strtolower($tag);
394 // if ( array_key_exists($clean_tag), $tag_id_cache) ) {
395 // $result[$clean_tag] = $tag_id_cache[$clean_tag];
396 // $tags[$key] = ''; // prevent further processing for this one.
397 // }
398 //}
399
400 $tags = array_values(tag_normalize($tags));
401 foreach($tags as $key => $tag) {
986dca60 402 $tags[$key] = moodle_strtolower($tag);
db32b054 403 $result[moodle_strtolower($tag)] = null; // key must exists : no value for a key means the tag wasn't found.
404 }
db32b054 405
f7ed2687 406 if (empty($tags)) {
407 return array();
408 }
409
410 list($tag_string, $params) = $DB->get_in_or_equal($tags);
411
412 if ($rs = $DB->get_recordset_sql("SELECT * FROM {tag} WHERE name $tag_string ORDER BY name", $params)) {
413 foreach ($rs as $record) {
db32b054 414 if ($return_value == TAG_RETURN_OBJECT) {
415 $result[$record->name] = $record;
416 } else { // TAG_RETURN_ARRAY
417 $result[$record->name] = $record->id;
418 }
419 }
f7ed2687 420 $rs->close();
4f81c51d 421 }
3d436d8a 422
db32b054 423 if ($return_an_int) {
424 return array_pop($result);
425 }
3d436d8a 426
db32b054 427 return $result;
c933a060 428}
429
c933a060 430
431/**
db32b054 432 * Returns tags related to a tag
d4be9d6d 433 *
db32b054 434 * Related tags of a tag come from two sources:
435 * - manually added related tags, which are tag_instance entries for that tag
436 * - correlated tags, which are a calculated
d4be9d6d 437 *
986dca60 438 * @param string $tag_name_or_id is a single **normalized** tag name or the id
537aa65c 439 * of a tag
986dca60 440 * @param int $type the function will return either manually
441 * (TAG_RELATED_MANUAL) related tags or correlated (TAG_RELATED_CORRELATED)
537aa65c 442 * tags. Default is TAG_RELATED_ALL, which returns everything.
986dca60 443 * @param int $limitnum return a subset comprising this many records (optional,
537aa65c 444 * default is 10)
db32b054 445 * @return array an array of tag objects
c933a060 446 */
537aa65c 447function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
c933a060 448
537aa65c 449 $related_tags = array();
450
451 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_MANUAL) {
452 //gets the manually added related tags
453 $related_tags = tag_get_tags('tag', $tagid);
c933a060 454 }
455
537aa65c 456 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_CORRELATED ) {
457 //gets the correlated tags
458 $automatic_related_tags = tag_get_correlated($tagid, $limitnum);
459 if (is_array($automatic_related_tags)) {
460 $related_tags = array_merge($related_tags, $automatic_related_tags);
461 }
db32b054 462 }
3d436d8a 463
db32b054 464 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
c933a060 465}
466
986dca60 467/**
db32b054 468 * Get a comma-separated list of tags related to another tag.
d4be9d6d 469 *
db32b054 470 * @param array $related_tags the array returned by tag_get_related_tags
471 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
472 * @return string comma-separated list
c933a060 473 */
db32b054 474function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
475 global $CFG;
c933a060 476
db32b054 477 $tags_names = array();
478 foreach($related_tags as $tag) {
479 if ( $html == TAG_RETURN_TEXT) {
e7134583 480 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
db32b054 481 } else {
482 // TAG_RETURN_HTML
9fccb889 483 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
c933a060 484 }
c933a060 485 }
b50d2245 486
db32b054 487 return implode(', ', $tags_names);
c933a060 488}
489
3a597ace 490/**
db32b054 491 * Change the "value" of a tag, and update the associated 'name'.
3a597ace 492 *
db32b054 493 * @param int $tagid the id of the tag to modify
73c32e86 494 * @param string $newtag the new rawname
db32b054 495 * @return bool true on success, false otherwise
3a597ace 496 */
73c32e86 497function tag_rename($tagid, $newrawname) {
f7ed2687 498 global $DB;
3a597ace 499
73c32e86 500 if (! $newrawname_clean = array_shift(tag_normalize($newrawname, TAG_CASE_ORIGINAL)) ) {
db32b054 501 return false;
502 }
3a597ace 503
2f4b82f4 504 if (! $newname_clean = moodle_strtolower($newrawname_clean)) {
505 return false;
506 }
507
508 // Prevent the rename if a tag with that name already exists
509 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
510 if ($existing->id != $tagid) { // Another tag already exists with this name
986dca60 511 return false;
2f4b82f4 512 }
db32b054 513 }
3a597ace 514
2f4b82f4 515 if ($tag = tag_get('id', $tagid, 'id, name, rawname')) {
986dca60 516 $tag->rawname = $newrawname_clean;
517 $tag->name = $newname_clean;
db32b054 518 $tag->timemodified = time();
f7ed2687 519 return $DB->update_record('tag', $tag);
db32b054 520 }
521 return false;
3a597ace 522}
523
8479c2e0 524
c933a060 525/**
8479c2e0 526 * Delete one or more tag, and all their instances if there are any left.
986dca60 527 *
8479c2e0 528 * @param mixed $tagids one tagid (int), or one array of tagids to delete
986dca60 529 * @return bool true on success, false otherwise
c933a060 530 */
8479c2e0 531function tag_delete($tagids) {
f7ed2687 532 global $DB;
3d436d8a 533
8479c2e0 534 if (!is_array($tagids)) {
535 $tagids = array($tagids);
db32b054 536 }
3d436d8a 537
8479c2e0 538 $success = true;
8bdc9cac 539 $context = get_context_instance(CONTEXT_SYSTEM);
8479c2e0 540 foreach( $tagids as $tagid ) {
541 if (is_null($tagid)) { // can happen if tag doesn't exists
db32b054 542 continue;
26d8649f 543 }
986dca60 544 // only delete the main entry if there were no problems deleting all the
545 // instances - that (and the fact we won't often delete lots of tags)
8618fd2a 546 // is the reason for not using $DB->delete_records_select()
f7ed2687 547 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid)) ) {
548 $success &= (bool) $DB->delete_records('tag', array('id'=>$tagid));
8bdc9cac
SH
549 // Delete all files associated with this tag
550 $fs = get_file_storage();
64f93798 551 $files = $fs->get_area_files($context->id, 'tag', 'description', $tagid);
8bdc9cac
SH
552 foreach ($files as $file) {
553 $file->delete();
554 }
1acd661d 555 }
c933a060 556 }
8479c2e0 557
558 return $success;
db32b054 559}
c933a060 560
db32b054 561/**
8479c2e0 562 * Delete one instance of a tag. If the last instance was deleted, it will
a72529c7 563 * also delete the tag, unless its type is 'official'.
8479c2e0 564 *
28f64040 565 * @param string $record_type the type of the record for which to remove the instance
566 * @param int $record_id the id of the record for which to remove the instance
8479c2e0 567 * @param int $tagid the tagid that needs to be removed
568 * @return bool true on success, false otherwise
db32b054 569 */
28f64040 570function tag_delete_instance($record_type, $record_id, $tagid) {
f7ed2687 571 global $CFG, $DB;
572
573 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id))) {
a72529c7 574 if (!$DB->record_exists_sql("SELECT * ".
575 "FROM {tag} tg ".
576 "WHERE tg.id = ? AND ( tg.tagtype = 'official' OR ".
b91de8a5 577 "EXISTS (SELECT 1
578 FROM {tag_instance} ti
579 WHERE ti.tagid = ?) )",
580 array($tagid, $tagid))) {
8479c2e0 581 return tag_delete($tagid);
582 }
583 } else {
584 return false;
db32b054 585 }
4a0daed7 586
587 return true;
db32b054 588}
c933a060 589
8479c2e0 590
3627b0e3 591/**
8479c2e0 592 * Function that returns the name that should be displayed for a specific tag
593 *
594 * @param object $tag_object a line out of tag table, as returned by the adobd functions
e7134583 595 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
8479c2e0 596 * @return string
3627b0e3 597 */
e7134583 598function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
3627b0e3 599
8479c2e0 600 global $CFG;
601
34b93e39 602 if (!isset($tagobject->name)) {
8479c2e0 603 return '';
604 }
605
606 if (empty($CFG->keeptagnamecase)) {
607 //this is the normalized tag name
608 $textlib = textlib_get_instance();
e7134583 609 $tagname = $textlib->strtotitle($tagobject->name);
8479c2e0 610 } else {
611 //original casing of the tag name
e7134583 612 $tagname = $tagobject->rawname;
3627b0e3 613 }
e7134583 614
34b93e39
PS
615 // clean up a bit just in case the rules change again
616 $tagname = clean_param($tagname, PARAM_TAG);
617
e7134583 618 if ($html == TAG_RETURN_TEXT) {
619 return $tagname;
620 } else { // TAG_RETURN_HTML
621 return htmlspecialchars($tagname);
b91de8a5 622 }
3627b0e3 623}
624
db32b054 625/**
8479c2e0 626 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
db32b054 627 *
8479c2e0 628 * @param string $tag tag to look for
629 * @param string $type type to restrict search to. If null, every matching
630 * record will be returned
631 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
632 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
633 * @return array of matching objects, indexed by record id, from the table containing the type requested
db32b054 634 */
8479c2e0 635function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
f7ed2687 636 global $CFG, $DB;
8479c2e0 637
638 if (!$tag || !$type) {
639 return array();
db32b054 640 }
8479c2e0 641
642 $tagid = tag_get_id($tag);
643
f7ed2687 644 $query = "SELECT it.*
645 FROM {".$type."} it INNER JOIN {tag_instance} tt ON it.id = tt.itemid
646 WHERE tt.itemtype = ? AND tt.tagid = ?";
647 $params = array($type, $tagid);
986dca60 648
649 return $DB->get_records_sql($query, $params, $limitfrom, $limitnum);
c933a060 650}
651
8479c2e0 652
653
654
db32b054 655///////////////////////////////////////////////////////
656/////////////////// PRIVATE TAG API ///////////////////
c933a060 657
658/**
986dca60 659 * Adds one or more tag in the database. This function should not be called
db32b054 660 * directly : you should use tag_set.
d4be9d6d 661 *
db32b054 662 * @param mixed $tags one tag, or an array of tags, to be created
986dca60 663 * @param string $type type of tag to be created ("default" is the default
db32b054 664 * value and "official" is the only other supported value at this time). An
665 * official tag is kept even if there are no records tagged with it.
986dca60 666 * @return an array of tags ids, indexed by their lowercase normalized names.
db32b054 667 * Any boolean false in the array indicates an error while adding the tag.
c933a060 668 */
db32b054 669function tag_add($tags, $type="default") {
f7ed2687 670 global $USER, $DB;
c933a060 671
db32b054 672 if (!is_array($tags)) {
673 $tags = array($tags);
c933a060 674 }
3d436d8a 675
db32b054 676 $tag_object = new StdClass;
f7ed2687 677 $tag_object->tagtype = $type;
678 $tag_object->userid = $USER->id;
679 $tag_object->timemodified = time();
c933a060 680
db32b054 681 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL);
c933a060 682
db32b054 683 $tags_ids = array();
684 foreach($clean_tags as $tag) {
685 $tag = trim($tag);
686 if (!$tag) {
687 $tags_ids[$tag] = false;
688 } else {
986dca60 689 // note that the difference between rawname and name is only
690 // capitalization : the rawname is NOT the same at the rawtag.
691 $tag_object->rawname = $tag;
f7ed2687 692 $tag_name_lc = moodle_strtolower($tag);
693 $tag_object->name = $tag_name_lc;
db32b054 694 //var_dump($tag_object);
f7ed2687 695 $tags_ids[$tag_name_lc] = $DB->insert_record('tag', $tag_object);
db32b054 696 }
697 }
c933a060 698
db32b054 699 return $tags_ids;
c933a060 700}
701
702/**
db32b054 703 * Assigns a tag to a record: if the record already exists, the time and
704 * ordering will be updated.
986dca60 705 *
28f64040 706 * @param string $record_type the type of the record that will be tagged
707 * @param int $record_id the id of the record that will be tagged
986dca60 708 * @param string $tagid the tag id to set on the record.
db32b054 709 * @param int $ordering the order of the instance for this record
38fb8190 710 * @param int $userid optional only required for course tagging
db32b054 711 * @return bool true on success, false otherwise
c933a060 712 */
38fb8190 713function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0) {
f7ed2687 714 global $DB;
c933a060 715
38fb8190 716 if ( $tag_instance_object = $DB->get_record('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id, 'tiuserid'=>$userid), 'id')) {
f7ed2687 717 $tag_instance_object->ordering = $ordering;
db32b054 718 $tag_instance_object->timemodified = time();
f7ed2687 719 return $DB->update_record('tag_instance', $tag_instance_object);
986dca60 720 } else {
db32b054 721 $tag_instance_object = new StdClass;
f7ed2687 722 $tag_instance_object->tagid = $tagid;
723 $tag_instance_object->itemid = $record_id;
724 $tag_instance_object->itemtype = $record_type;
725 $tag_instance_object->ordering = $ordering;
db32b054 726 $tag_instance_object->timemodified = time();
38fb8190 727 $tag_instance_object->tiuserid = $userid;
f7ed2687 728 return $DB->insert_record('tag_instance', $tag_instance_object);
c933a060 729 }
c933a060 730}
731
732/**
db32b054 733 * Function that returns tags that start with some text, for use by the autocomplete feature
d4be9d6d 734 *
db32b054 735 * @param string $text string that the tag names will be matched against
c933a060 736 * @return mixed an array of objects, or false if no records were found or an error occured.
737 */
db32b054 738function tag_autocomplete($text) {
f7ed2687 739 global $DB;
740 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
741 FROM {tag} tg
742 WHERE tg.name LIKE ?", array(moodle_strtolower($text)."%"));
c933a060 743}
744
986dca60 745/**
9545cdba 746 * Clean up the tag tables, making sure all tagged object still exists.
747 *
748 * This should normally not be necessary, but in case related tags are not deleted
749 * when the tagged record is removed, this should be done once in a while, perhaps on
986dca60 750 * an occasional cron run. On a site with lots of tags, this could become an expensive
9545cdba 751 * function to call: don't run at peak time.
752 */
753function tag_cleanup() {
f7ed2687 754 global $DB;
9545cdba 755
f7ed2687 756 $instances = $DB->get_recordset('tag_instance');
9545cdba 757
084426c5 758 // cleanup tag instances
f7ed2687 759 foreach ($instances as $instance) {
9545cdba 760 $delete = false;
986dca60 761
f7ed2687 762 if (!$DB->record_exists('tag', array('id'=>$instance->tagid))) {
9545cdba 763 // if the tag has been removed, instance should be deleted.
764 $delete = true;
765 } else {
766 switch ($instance->itemtype) {
767 case 'user': // users are marked as deleted, but not actually deleted
f7ed2687 768 if ($DB->record_exists('user', array('id'=>$instance->itemid, 'deleted'=>1))) {
9545cdba 769 $delete = true;
770 }
771 break;
772 default: // anything else, if the instance is not there, delete.
f7ed2687 773 if (!$DB->record_exists($instance->itemtype, array('id'=>$instance->itemid))) {
9545cdba 774 $delete = true;
775 }
776 break;
777 }
778 }
779 if ($delete) {
780 tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid);
781 //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER);
782 }
783 }
f7ed2687 784 $instances->close();
9545cdba 785
786 // TODO: this will only clean tags of type 'default'. This is good as
787 // it won't delete 'official' tags, but the day we get more than two
788 // types, we need to fix this.
f7ed2687 789 $unused_tags = $DB->get_recordset_sql("SELECT tg.id
790 FROM {tag} tg
791 WHERE tg.tagtype = 'default'
792 AND NOT EXISTS (
793 SELECT 'x'
794 FROM {tag_instance} ti
795 WHERE ti.tagid = tg.id
796 )");
9545cdba 797
084426c5 798 // cleanup tags
f7ed2687 799 foreach ($unused_tags as $unused_tag) {
084426c5 800 tag_delete($unused_tag->id);
801 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
9545cdba 802 }
f7ed2687 803 $unused_tags->close();
9545cdba 804}
805
c933a060 806/**
db32b054 807 * Calculates and stores the correlated tags of all tags.
808 * The correlations are stored in the 'tag_correlation' table.
809 *
810 * Two tags are correlated if they appear together a lot.
811 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
d4be9d6d 812 *
db32b054 813 * The rationale for the 'tag_correlation' table is performance.
814 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
815 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
d4be9d6d 816 *
db32b054 817 * @param number $min_correlation cutoff percentage (optional, default is 2)
c933a060 818 */
db32b054 819function tag_compute_correlations($min_correlation=2) {
f7ed2687 820 global $DB;
3d436d8a 821
986dca60 822 if (!$all_tags = $DB->get_records('tag')) {
423a71b6 823 return;
824 }
db32b054 825
c213773d 826 $tag_correlation_obj = new stdClass();
db32b054 827 foreach($all_tags as $tag) {
828
829 // query that counts how many times any tag appears together in items
830 // with the tag passed as argument ($tag_id)
b91de8a5 831 $query = "SELECT tb.tagid
f7ed2687 832 FROM {tag_instance} ta JOIN {tag_instance} tb ON ta.itemid = tb.itemid
833 WHERE ta.tagid = ? AND tb.tagid <> ?
834 GROUP BY tb.tagid
db3d1302 835 HAVING COUNT(*) > ?
eafa83ef 836 ORDER BY COUNT(*) DESC";
f7ed2687 837 $params = array($tag->id, $tag->id, $min_correlation);
db32b054 838
839 $correlated = array();
840
986dca60 841 // Correlated tags happen when they appear together in more occasions
db32b054 842 // than $min_correlation.
f7ed2687 843 if ($tag_correlations = $DB->get_records_sql($query, $params)) {
db32b054 844 foreach($tag_correlations as $correlation) {
844f9c15 845 // commented out - now done in query. kept here in case it breaks on some db
846 // if($correlation->nr >= $min_correlation){
db32b054 847 $correlated[] = $correlation->tagid;
844f9c15 848 // }
db32b054 849 }
850 }
c933a060 851
844f9c15 852 if (empty($correlated)) {
853 continue;
854 }
855
db32b054 856 $correlated = implode(',', $correlated);
857 //var_dump($correlated);
858
859 //saves correlation info in the caching table
aced917b 860 if ($tag_correlation_obj = $DB->get_record('tag_correlation', array('tagid'=>$tag->id), 'id')) {
db32b054 861 $tag_correlation_obj->correlatedtags = $correlated;
f7ed2687 862 $DB->update_record('tag_correlation', $tag_correlation_obj);
db32b054 863 } else {
aced917b 864 $tag_correlation_obj = new stdClass();
db32b054 865 $tag_correlation_obj->tagid = $tag->id;
866 $tag_correlation_obj->correlatedtags = $correlated;
f7ed2687 867 $DB->insert_record('tag_correlation', $tag_correlation_obj);
db32b054 868 }
3d436d8a 869 }
db32b054 870}
871
872/**
873 * Tasks that should be performed at cron time
874 */
875function tag_cron() {
876 tag_compute_correlations();
0f5e5f5c 877 tag_cleanup();
db32b054 878}
879
0f039283 880/**
881 * Search for tags with names that match some text
882 *
883 * @param string $text escaped string that the tag names will be matched against
884 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
885 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
886 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
887 * @return mixed an array of objects, or false if no records were found or an error occured.
888 */
889function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
f7ed2687 890 global $DB;
0f039283 891
892 $text = array_shift(tag_normalize($text, TAG_CASE_LOWER));
893
894 if ($ordered) {
f7ed2687 895 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
896 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
897 WHERE tg.name LIKE ?
898 GROUP BY tg.id, tg.name, tg.rawname
899 ORDER BY count DESC";
0f039283 900 } else {
f7ed2687 901 $query = "SELECT tg.id, tg.name, tg.rawname
902 FROM {tag} tg
903 WHERE tg.name LIKE ?";
0f039283 904 }
f7ed2687 905 $params = array("%{$text}%");
906 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
0f039283 907}
908
986dca60 909/**
db32b054 910 * Get the name of a tag
986dca60 911 *
db32b054 912 * @param mixed $tagids the id of the tag, or an array of ids
913 * @return mixed string name of one tag, or id-indexed array of strings
914 */
915function tag_get_name($tagids) {
f7ed2687 916 global $DB;
3d436d8a 917
f7ed2687 918 if (!is_array($tagids)) {
919 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
920 return $tag->name;
921 }
922 return false;
db32b054 923 }
c933a060 924
db32b054 925 $tag_names = array();
986dca60 926 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
db32b054 927 $tag_names[$tag->id] = $tag->name;
928 }
c933a060 929
db32b054 930 return $tag_names;
c933a060 931}
932
933/**
db32b054 934 * Returns the correlated tags of a tag, retrieved from the tag_correlation
986dca60 935 * table. Make sure cron runs, otherwise the table will be empty and this
db32b054 936 * function won't return anything.
c933a060 937 *
db32b054 938 * @param int $tag_id is a single tag id
939 * @return array an array of tag objects, empty if no correlated tags are found
c933a060 940 */
db32b054 941function tag_get_correlated($tag_id, $limitnum=null) {
f7ed2687 942 global $DB;
3d436d8a 943
f7ed2687 944 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
c933a060 945
db32b054 946 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
947 return array();
c933a060 948 }
986dca60 949
73c32e86 950 // this is (and has to) return the same fields as the query in tag_get_tags
725c9404 951 if ( !$result = $DB->get_records_sql("SELECT DISTINCT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
f7ed2687 952 FROM {tag} tg INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
953 WHERE tg.id IN ({$tag_correlation->correlatedtags})") ) {
db32b054 954 return array();
c933a060 955 }
986dca60 956
db32b054 957 return $result;
c933a060 958}
959
c933a060 960/**
db32b054 961 * Function that normalizes a list of tag names.
c933a060 962 *
db32b054 963 * @param mixed $tags array of tags, or a single tag.
986dca60 964 * @param int $case case to use for returned value (default: lower case).
0f039283 965 * Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
986dca60 966 * @return array of lowercased normalized tags, indexed by the normalized tag,
0f039283 967 * in the same order as the original array. (Eg: 'Banana' => 'banana').
c933a060 968 */
db32b054 969function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
970
0f039283 971 // cache normalized tags, to prevent costly repeated calls to clean_param
db32b054 972 static $cleaned_tags_lc = array(); // lower case - use for comparison
973 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
c933a060 974
db32b054 975 if ( !is_array($rawtags) ) {
976 $rawtags = array($rawtags);
977 }
c933a060 978
db32b054 979 $result = array();
980 foreach($rawtags as $rawtag) {
981 $rawtag = trim($rawtag);
982 if (!$rawtag) {
983 continue;
984 }
985 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
986 $cleaned_tags_lc[$rawtag] = moodle_strtolower( clean_param($rawtag, PARAM_TAG) );
987 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
988 }
986dca60 989 if ( $case == TAG_CASE_LOWER ) {
db32b054 990 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
991 } else { // TAG_CASE_ORIGINAL
992 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
993 }
994 }
986dca60 995
db32b054 996 return $result;
c933a060 997}
998
999/**
0f039283 1000 * Count how many records are tagged with a specific tag,
c933a060 1001 *
0f039283 1002 * @param string $record record to look for ('post', 'user', etc.)
1003 * @param int $tag is a single tag id
1004 * @return int number of mathing tags.
c933a060 1005 */
0f039283 1006function tag_record_count($record_type, $tagid) {
f7ed2687 1007 global $DB;
1008 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
0f039283 1009}
c933a060 1010
0f039283 1011/**
986dca60 1012 * Determine if a record is tagged with a specific tag
0f039283 1013 *
1014 * @param string $record_type the record type to look for
1015 * @param int $record_id the record id to look for
1016 * @param string $tag a tag name
1017 * @return bool true if it is tagged, false otherwise
1018 */
1019function tag_record_tagged_with($record_type, $record_id, $tag) {
f7ed2687 1020 global $DB;
0f039283 1021 if ($tagid = tag_get_id($tag)) {
f7ed2687 1022 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
c933a060 1023 } else {
0f039283 1024 return 0; // tag doesn't exist
c933a060 1025 }
c933a060 1026}
1027
1028/**
db32b054 1029 * Flag a tag as inapropriate
986dca60 1030 *
db32b054 1031 * @param mixed $tagids one (int) tagid, or an array of tagids
1032 * @return void
c933a060 1033 */
db32b054 1034function tag_set_flag($tagids) {
f7ed2687 1035 global $DB;
1036
1037 $tagids = (array)$tagids;
db32b054 1038 foreach ($tagids as $tagid) {
f7ed2687 1039 $tag = $DB->get_record('tag', array('id'=>$tagid), 'id, flag');
c933a060 1040 $tag->flag++;
1041 $tag->timemodified = time();
f7ed2687 1042 $DB->update_record('tag', $tag);
c933a060 1043 }
1044}
1045
986dca60 1046/**
db32b054 1047 * Remove the inapropriate flag on a tag
986dca60 1048 *
db32b054 1049 * @param mixed $tagids one (int) tagid, or an array of tagids
1050 * @return bool true if function succeeds, false otherwise
c933a060 1051 */
db32b054 1052function tag_unset_flag($tagids) {
f7ed2687 1053 global $DB;
d4be9d6d 1054
db32b054 1055 if ( is_array($tagids) ) {
1056 $tagids = implode(',', $tagids);
ab86d9c7 1057 }
db32b054 1058 $timemodified = time();
cef53045 1059 return $DB->execute("UPDATE {tag} SET flag = 0, timemodified = ? WHERE id IN ($tagids)", array($timemodified));
c933a060 1060}