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