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