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