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