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