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