MDL-25998 fix default manual enrol role
[moodle.git] / tag / lib.php
bloba28f1bd4bfc17a73536a23ce82b9636ac43c8357
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Moodle tag library
21 * Tag strings : you can use any character in tags, except the comma (which is
22 * the separator) and the '\' (backslash). Note that many spaces (or other
23 * blank characters) will get "compressed" into one. A tag string is always a
24 * rawurlencode'd string. This is the same behavior as http://del.icio.us.
26 * A "record" is a php array (note that an object will work too) that contains
27 * the following variables :
28 * - type: the table containing the record that we are tagging (eg: for a
29 * blog, this is table 'post', and for a user it is 'user')
30 * - id: the id of the record
32 * TODO: turn this into a full-fledged categorization system. This could start
33 * by modifying (removing, probably) the 'tag type' to use another table
34 * describing the relationship between tags (parents, sibling, etc.), which
35 * could then be merged with the 'course categorization' system...
37 * BASIC INSTRUCTIONS :
38 * - to "tag a blog post" (for example):
39 * tag_set('post', $blog_post->id, $array_of_tags);
41 * - to "remove all the tags on a blog post":
42 * tag_set('post', $blog_post->id, array());
44 * Tag set will create tags that need to be created.
46 * @package core
47 * @subpackage tag
48 * @see http://www.php.net/manual/en/function.urlencode.php
49 * @copyright 2007 Luiz Cruz <luiz.laydner@gmail.com>
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 define('TAG_RETURN_ARRAY', 0);
54 define('TAG_RETURN_OBJECT', 1);
55 define('TAG_RETURN_TEXT', 2);
56 define('TAG_RETURN_HTML', 3);
58 define('TAG_CASE_LOWER', 0);
59 define('TAG_CASE_ORIGINAL', 1);
61 define('TAG_RELATED_ALL', 0);
62 define('TAG_RELATED_MANUAL', 1);
63 define('TAG_RELATED_CORRELATED', 2);
65 ///////////////////////////////////////////////////////
66 /////////////////// PUBLIC TAG API ////////////////////
68 /// Functions for settings tags //////////////////////
70 /**
71 * Set the tags assigned to a record. This overwrites the current tags.
73 * This function is meant to be fed the string coming up from the user
74 * interface, which contains all tags assigned to a record.
76 * @param string $record_type the type of record to tag ('post' for blogs,
77 * 'user' for users, 'tag' for tags, etc.
78 * @param int $record_id the id of the record to tag
79 * @param array $tags the array of tags to set on the record. If
80 * given an empty array, all tags will be removed.
81 * @return void
83 function tag_set($record_type, $record_id, $tags) {
85 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
86 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
87 $current_tagged_tag_name = tag_get_name($record_id);
90 $tags_ids = tag_get_id($tags, TAG_RETURN_ARRAY); // force an array, even if we only have one tag.
91 $cleaned_tags = tag_normalize($tags);
92 //echo 'tags-in-tag_set'; var_dump($tags); var_dump($tags_ids); var_dump($cleaned_tags);
94 $current_ids = tag_get_tags_ids($record_type, $record_id);
95 //var_dump($current_ids);
97 // for data coherence reasons, it's better to remove deleted tags
98 // before adding new data: ordering could be duplicated.
99 foreach($current_ids as $current_id) {
100 if (!in_array($current_id, $tags_ids)) {
101 tag_delete_instance($record_type, $record_id, $current_id);
102 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
103 // if we are removing a tag-on-a-tag (manually related tag),
104 // we need to remove the opposite relationship as well.
105 tag_delete_instance('tag', $current_id, $record_id);
110 if (empty($tags)) {
111 return true;
114 foreach($tags as $ordering => $tag) {
115 $tag = trim($tag);
116 if (!$tag) {
117 continue;
120 $clean_tag = $cleaned_tags[$tag];
121 $tag_current_id = $tags_ids[$clean_tag];
123 if ( is_null($tag_current_id) ) {
124 // create new tags
125 //echo "call to add tag $tag\n";
126 $new_tag = tag_add($tag);
127 $tag_current_id = $new_tag[$clean_tag];
130 tag_assign($record_type, $record_id, $tag_current_id, $ordering);
132 // if we are tagging a tag (adding a manually-assigned related tag), we
133 // need to create the opposite relationship as well.
134 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
135 $in_recursion_semaphore = true;
136 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name);
137 $in_recursion_semaphore = false;
143 * Adds a tag to a record, without overwriting the current tags.
145 * @param string $record_type the type of record to tag ('post' for blogs,
146 * 'user' for users, etc.
147 * @param int $record_id the id of the record to tag
148 * @param string $tag the tag to add
149 * @return void
151 function tag_set_add($record_type, $record_id, $tag) {
153 $new_tags = array();
154 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
155 $new_tags[] = $current_tag->rawname;
157 $new_tags[] = $tag;
159 return tag_set($record_type, $record_id, $new_tags);
163 * Removes a tag from a record, without overwriting other current tags.
165 * @param string $record_type the type of record to tag ('post' for blogs,
166 * 'user' for users, etc.
167 * @param int $record_id the id of the record to tag
168 * @param string $tag the tag to delete
169 * @return void
171 function tag_set_delete($record_type, $record_id, $tag) {
173 $new_tags = array();
174 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
175 if ($current_tag->name != $tag) { // Keep all tags but the one specified
176 $new_tags[] = $current_tag->name;
180 return tag_set($record_type, $record_id, $new_tags);
184 * Set the type of a tag. At this time (version 1.9) the possible values
185 * are 'default' or 'official'. Official tags will be displayed separately "at
186 * tagging time" (while selecting the tags to apply to a record).
188 * @param string $tagid tagid to modify
189 * @param string $type either 'default' or 'official'
190 * @return true on success, false otherwise
192 function tag_type_set($tagid, $type) {
193 global $DB;
195 if ($tag = $DB->get_record('tag', array('id'=>$tagid), 'id')) {
196 $tag->tagtype = $type;
197 $tag->timemodified = time();
198 return $DB->update_record('tag', $tag);
200 return false;
205 * Set the description of a tag
207 * @param int $tagid the id of the tag
208 * @param string $description the description
209 * @param int $descriptionformat the moodle text format of the description
210 * @return true on success, false otherwise
212 function tag_description_set($tagid, $description, $descriptionformat) {
213 global $DB;
215 if ($tag = $DB->get_record('tag', array('id'=>$tagid),'id')) {
216 $tag->description = $description;
217 $tag->descriptionformat = $descriptionformat;
218 $tag->timemodified = time();
219 return $DB->update_record('tag', $tag);
221 return false;
229 /// Functions for getting information about tags //////
232 * Simple function to just return a single tag object when you know the name or something
234 * @param string $field which field do we use to identify the tag: id, name or rawname
235 * @param string $value the required value of the aforementioned field
236 * @param string $returnfields which fields do we want returned?
237 * @return tag object
240 function tag_get($field, $value, $returnfields='id, name, rawname') {
241 global $DB;
243 if ($field == 'name') {
244 $value = moodle_strtolower($value); // To cope with input that might just be wrong case
246 return $DB->get_record('tag', array($field=>$value), $returnfields);
251 * Get the array of db record of tags associated to a record (instances). Use
252 * tag_get_tags_csv to get the same information in a comma-separated string.
254 * @param string $record_type the record type for which we want to get the tags
255 * @param int $record_id the record id for which we want to get the tags
256 * @param string $type the tag type (either 'default' or 'official'). By default,
257 * all tags are returned.
258 * @param int $userid optional only required for course tagging
259 * @return array the array of tags
261 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
262 global $CFG, $DB;
264 $params = array();
266 if ($type) {
267 $sql_type = "AND tg.tagtype = :type";
268 $params['type'] = $type;
269 } else {
270 $sql_type = '';
273 $u = null;
274 if ($userid) {
275 $u = "AND ti.tiuserid = :userid ";
276 $params['userid'] = $userid;
279 $sql = "SELECT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
280 FROM {tag_instance} ti JOIN {tag} tg ON tg.id = ti.tagid
281 WHERE ti.itemtype = :recordtype AND ti.itemid = :recordid $u $sql_type
282 ORDER BY ti.ordering ASC";
283 $params['recordtype'] = $record_type;
284 $params['recordid'] = $record_id;
286 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
287 return $DB->get_records_sql($sql, $params);
288 // This version of the query, reversing the ON clause, "correctly" returns
289 // a row with NULL values for instances that are still in the DB even though
290 // the tag has been deleted. This shouldn't happen, but if it did, using
291 // this query could help "clean it up". This causes bugs at this time.
292 //$tags = $DB->get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
293 // "FROM {tag_instance} ti LEFT JOIN {tag} tg ON ti.tagid = tg.id ".
294 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
295 // "ORDER BY ti.ordering ASC");
299 * Get the array of tags display names, indexed by id.
301 * @param string $record_type the record type for which we want to get the tags
302 * @param int $record_id the record id for which we want to get the tags
303 * @param string $type the tag type (either 'default' or 'official'). By default,
304 * all tags are returned.
305 * @return array the array of tags (with the value returned by tag_display_name), indexed by id
307 function tag_get_tags_array($record_type, $record_id, $type=null) {
308 $tags = array();
309 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
310 $tags[$tag->id] = tag_display_name($tag);
312 return $tags;
316 * Get a comma-separated string of tags associated to a record. Use tag_get_tags
317 * to get the same information in an array.
319 * @param string $record_type the record type for which we want to get the tags
320 * @param int $record_id the record id for which we want to get the tags
321 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending
322 * on the type of output desired
323 * @param string $type either 'official' or 'default', if null, all tags are
324 * returned
325 * @return string the comma-separated list of tags.
327 function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML, $type=null) {
328 global $CFG;
330 $tags_names = array();
331 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
332 if ($html == TAG_RETURN_TEXT) {
333 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
334 } else { // TAG_RETURN_HTML
335 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
338 return implode(', ', $tags_names);
342 * Get an array of tag ids associated to a record.
344 * @param string $record_type the record type for which we want to get the tags
345 * @param int $record_id the record id for which we want to get the tags
346 * @return array of tag ids, indexed and sorted by 'ordering'
348 function tag_get_tags_ids($record_type, $record_id) {
350 $tag_ids = array();
351 foreach (tag_get_tags($record_type, $record_id) as $tag) {
352 if ( array_key_exists($tag->ordering, $tag_ids) ) {
353 // until we can add a unique constraint, in table tag_instance,
354 // on (itemtype, itemid, ordering), this is needed to prevent a bug
355 // TODO : modify database in 2.0
356 $tag->ordering++;
358 $tag_ids[$tag->ordering] = $tag->id;
360 ksort($tag_ids);
361 return $tag_ids;
365 * Returns the database ID of a set of tags.
367 * @param mixed $tags one tag, or array of tags, to look for.
368 * @param bool $return_value specify the type of the returned value. Either
369 * TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default). If TAG_RETURN_ARRAY
370 * is specified, an array will be returned even if only one tag was
371 * passed in $tags.
372 * @return mixed tag-indexed array of ids (or objects, if second parameter is
373 * TAG_RETURN_OBJECT), or only an int, if only one tag is given *and* the
374 * second parameter is null. No value for a key means the tag wasn't found.
376 function tag_get_id($tags, $return_value=null) {
377 global $CFG, $DB;
379 static $tag_id_cache = array();
381 $return_an_int = false;
382 if (!is_array($tags)) {
383 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
384 $return_an_int = true;
386 $tags = array($tags);
389 $result = array();
391 //TODO: test this and see if it helps performance without breaking anything
392 //foreach($tags as $key => $tag) {
393 // $clean_tag = moodle_strtolower($tag);
394 // if ( array_key_exists($clean_tag), $tag_id_cache) ) {
395 // $result[$clean_tag] = $tag_id_cache[$clean_tag];
396 // $tags[$key] = ''; // prevent further processing for this one.
397 // }
400 $tags = array_values(tag_normalize($tags));
401 foreach($tags as $key => $tag) {
402 $tags[$key] = moodle_strtolower($tag);
403 $result[moodle_strtolower($tag)] = null; // key must exists : no value for a key means the tag wasn't found.
406 if (empty($tags)) {
407 return array();
410 list($tag_string, $params) = $DB->get_in_or_equal($tags);
412 $rs = $DB->get_recordset_sql("SELECT * FROM {tag} WHERE name $tag_string ORDER BY name", $params);
413 foreach ($rs as $record) {
414 if ($return_value == TAG_RETURN_OBJECT) {
415 $result[$record->name] = $record;
416 } else { // TAG_RETURN_ARRAY
417 $result[$record->name] = $record->id;
420 $rs->close();
422 if ($return_an_int) {
423 return array_pop($result);
426 return $result;
431 * Returns tags related to a tag
433 * Related tags of a tag come from two sources:
434 * - manually added related tags, which are tag_instance entries for that tag
435 * - correlated tags, which are a calculated
437 * @param string $tag_name_or_id is a single **normalized** tag name or the id
438 * of a tag
439 * @param int $type the function will return either manually
440 * (TAG_RELATED_MANUAL) related tags or correlated (TAG_RELATED_CORRELATED)
441 * tags. Default is TAG_RELATED_ALL, which returns everything.
442 * @param int $limitnum return a subset comprising this many records (optional,
443 * default is 10)
444 * @return array an array of tag objects
446 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
448 $related_tags = array();
450 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_MANUAL) {
451 //gets the manually added related tags
452 $related_tags = tag_get_tags('tag', $tagid);
455 if ( $type == TAG_RELATED_ALL || $type == TAG_RELATED_CORRELATED ) {
456 //gets the correlated tags
457 $automatic_related_tags = tag_get_correlated($tagid, $limitnum);
458 if (is_array($automatic_related_tags)) {
459 $related_tags = array_merge($related_tags, $automatic_related_tags);
463 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
467 * Get a comma-separated list of tags related to another tag.
469 * @param array $related_tags the array returned by tag_get_related_tags
470 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
471 * @return string comma-separated list
473 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
474 global $CFG;
476 $tags_names = array();
477 foreach($related_tags as $tag) {
478 if ( $html == TAG_RETURN_TEXT) {
479 $tags_names[] = tag_display_name($tag, TAG_RETURN_TEXT);
480 } else {
481 // TAG_RETURN_HTML
482 $tags_names[] = '<a href="'. $CFG->wwwroot .'/tag/index.php?tag='. rawurlencode($tag->name) .'">'. tag_display_name($tag) .'</a>';
486 return implode(', ', $tags_names);
490 * Change the "value" of a tag, and update the associated 'name'.
492 * @param int $tagid the id of the tag to modify
493 * @param string $newtag the new rawname
494 * @return bool true on success, false otherwise
496 function tag_rename($tagid, $newrawname) {
497 global $DB;
499 if (! $newrawname_clean = array_shift(tag_normalize($newrawname, TAG_CASE_ORIGINAL)) ) {
500 return false;
503 if (! $newname_clean = moodle_strtolower($newrawname_clean)) {
504 return false;
507 // Prevent the rename if a tag with that name already exists
508 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
509 if ($existing->id != $tagid) { // Another tag already exists with this name
510 return false;
514 if ($tag = tag_get('id', $tagid, 'id, name, rawname')) {
515 $tag->rawname = $newrawname_clean;
516 $tag->name = $newname_clean;
517 $tag->timemodified = time();
518 return $DB->update_record('tag', $tag);
520 return false;
525 * Delete one or more tag, and all their instances if there are any left.
527 * @param mixed $tagids one tagid (int), or one array of tagids to delete
528 * @return bool true on success, false otherwise
530 function tag_delete($tagids) {
531 global $DB;
533 if (!is_array($tagids)) {
534 $tagids = array($tagids);
537 $success = true;
538 $context = get_context_instance(CONTEXT_SYSTEM);
539 foreach( $tagids as $tagid ) {
540 if (is_null($tagid)) { // can happen if tag doesn't exists
541 continue;
543 // only delete the main entry if there were no problems deleting all the
544 // instances - that (and the fact we won't often delete lots of tags)
545 // is the reason for not using $DB->delete_records_select()
546 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid)) ) {
547 $success &= (bool) $DB->delete_records('tag', array('id'=>$tagid));
548 // Delete all files associated with this tag
549 $fs = get_file_storage();
550 $files = $fs->get_area_files($context->id, 'tag', 'description', $tagid);
551 foreach ($files as $file) {
552 $file->delete();
557 return $success;
561 * Delete one instance of a tag. If the last instance was deleted, it will
562 * also delete the tag, unless its type is 'official'.
564 * @param string $record_type the type of the record for which to remove the instance
565 * @param int $record_id the id of the record for which to remove the instance
566 * @param int $tagid the tagid that needs to be removed
567 * @return bool true on success, false otherwise
569 function tag_delete_instance($record_type, $record_id, $tagid) {
570 global $CFG, $DB;
572 if ($DB->delete_records('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id))) {
573 if (!$DB->record_exists_sql("SELECT * ".
574 "FROM {tag} tg ".
575 "WHERE tg.id = ? AND ( tg.tagtype = 'official' OR ".
576 "EXISTS (SELECT 1
577 FROM {tag_instance} ti
578 WHERE ti.tagid = ?) )",
579 array($tagid, $tagid))) {
580 return tag_delete($tagid);
582 } else {
583 return false;
586 return true;
591 * Function that returns the name that should be displayed for a specific tag
593 * @param object $tag_object a line out of tag table, as returned by the adobd functions
594 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
595 * @return string
597 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
599 global $CFG;
601 if (!isset($tagobject->name)) {
602 return '';
605 if (empty($CFG->keeptagnamecase)) {
606 //this is the normalized tag name
607 $textlib = textlib_get_instance();
608 $tagname = $textlib->strtotitle($tagobject->name);
609 } else {
610 //original casing of the tag name
611 $tagname = $tagobject->rawname;
614 // clean up a bit just in case the rules change again
615 $tagname = clean_param($tagname, PARAM_TAG);
617 if ($html == TAG_RETURN_TEXT) {
618 return $tagname;
619 } else { // TAG_RETURN_HTML
620 return htmlspecialchars($tagname);
625 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
627 * @param string $tag tag to look for
628 * @param string $type type to restrict search to. If null, every matching
629 * record will be returned
630 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
631 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
632 * @return array of matching objects, indexed by record id, from the table containing the type requested
634 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
635 global $CFG, $DB;
637 if (!$tag || !$type) {
638 return array();
641 $tagid = tag_get_id($tag);
643 $query = "SELECT it.*
644 FROM {".$type."} it INNER JOIN {tag_instance} tt ON it.id = tt.itemid
645 WHERE tt.itemtype = ? AND tt.tagid = ?";
646 $params = array($type, $tagid);
648 return $DB->get_records_sql($query, $params, $limitfrom, $limitnum);
654 ///////////////////////////////////////////////////////
655 /////////////////// PRIVATE TAG API ///////////////////
658 * Adds one or more tag in the database. This function should not be called
659 * directly : you should use tag_set.
661 * @param mixed $tags one tag, or an array of tags, to be created
662 * @param string $type type of tag to be created ("default" is the default
663 * value and "official" is the only other supported value at this time). An
664 * official tag is kept even if there are no records tagged with it.
665 * @return an array of tags ids, indexed by their lowercase normalized names.
666 * Any boolean false in the array indicates an error while adding the tag.
668 function tag_add($tags, $type="default") {
669 global $USER, $DB;
671 if (!is_array($tags)) {
672 $tags = array($tags);
675 $tag_object = new StdClass;
676 $tag_object->tagtype = $type;
677 $tag_object->userid = $USER->id;
678 $tag_object->timemodified = time();
680 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL);
682 $tags_ids = array();
683 foreach($clean_tags as $tag) {
684 $tag = trim($tag);
685 if (!$tag) {
686 $tags_ids[$tag] = false;
687 } else {
688 // note that the difference between rawname and name is only
689 // capitalization : the rawname is NOT the same at the rawtag.
690 $tag_object->rawname = $tag;
691 $tag_name_lc = moodle_strtolower($tag);
692 $tag_object->name = $tag_name_lc;
693 //var_dump($tag_object);
694 $tags_ids[$tag_name_lc] = $DB->insert_record('tag', $tag_object);
698 return $tags_ids;
702 * Assigns a tag to a record: if the record already exists, the time and
703 * ordering will be updated.
705 * @param string $record_type the type of the record that will be tagged
706 * @param int $record_id the id of the record that will be tagged
707 * @param string $tagid the tag id to set on the record.
708 * @param int $ordering the order of the instance for this record
709 * @param int $userid optional only required for course tagging
710 * @return bool true on success, false otherwise
712 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0) {
713 global $DB;
715 if ( $tag_instance_object = $DB->get_record('tag_instance', array('tagid'=>$tagid, 'itemtype'=>$record_type, 'itemid'=>$record_id, 'tiuserid'=>$userid), 'id')) {
716 $tag_instance_object->ordering = $ordering;
717 $tag_instance_object->timemodified = time();
718 return $DB->update_record('tag_instance', $tag_instance_object);
719 } else {
720 $tag_instance_object = new StdClass;
721 $tag_instance_object->tagid = $tagid;
722 $tag_instance_object->itemid = $record_id;
723 $tag_instance_object->itemtype = $record_type;
724 $tag_instance_object->ordering = $ordering;
725 $tag_instance_object->timemodified = time();
726 $tag_instance_object->tiuserid = $userid;
727 return $DB->insert_record('tag_instance', $tag_instance_object);
732 * Function that returns tags that start with some text, for use by the autocomplete feature
734 * @param string $text string that the tag names will be matched against
735 * @return mixed an array of objects, or false if no records were found or an error occured.
737 function tag_autocomplete($text) {
738 global $DB;
739 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
740 FROM {tag} tg
741 WHERE tg.name LIKE ?", array(moodle_strtolower($text)."%"));
745 * Clean up the tag tables, making sure all tagged object still exists.
747 * This should normally not be necessary, but in case related tags are not deleted
748 * when the tagged record is removed, this should be done once in a while, perhaps on
749 * an occasional cron run. On a site with lots of tags, this could become an expensive
750 * function to call: don't run at peak time.
752 function tag_cleanup() {
753 global $DB;
755 $instances = $DB->get_recordset('tag_instance');
757 // cleanup tag instances
758 foreach ($instances as $instance) {
759 $delete = false;
761 if (!$DB->record_exists('tag', array('id'=>$instance->tagid))) {
762 // if the tag has been removed, instance should be deleted.
763 $delete = true;
764 } else {
765 switch ($instance->itemtype) {
766 case 'user': // users are marked as deleted, but not actually deleted
767 if ($DB->record_exists('user', array('id'=>$instance->itemid, 'deleted'=>1))) {
768 $delete = true;
770 break;
771 default: // anything else, if the instance is not there, delete.
772 if (!$DB->record_exists($instance->itemtype, array('id'=>$instance->itemid))) {
773 $delete = true;
775 break;
778 if ($delete) {
779 tag_delete_instance($instance->itemtype, $instance->itemid, $instance->tagid);
780 //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER);
783 $instances->close();
785 // TODO: this will only clean tags of type 'default'. This is good as
786 // it won't delete 'official' tags, but the day we get more than two
787 // types, we need to fix this.
788 $unused_tags = $DB->get_recordset_sql("SELECT tg.id
789 FROM {tag} tg
790 WHERE tg.tagtype = 'default'
791 AND NOT EXISTS (
792 SELECT 'x'
793 FROM {tag_instance} ti
794 WHERE ti.tagid = tg.id
795 )");
797 // cleanup tags
798 foreach ($unused_tags as $unused_tag) {
799 tag_delete($unused_tag->id);
800 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
802 $unused_tags->close();
806 * Calculates and stores the correlated tags of all tags.
807 * The correlations are stored in the 'tag_correlation' table.
809 * Two tags are correlated if they appear together a lot.
810 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
812 * The rationale for the 'tag_correlation' table is performance.
813 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
814 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
816 * @global moodle_database $DB
817 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will
818 * be identified.
819 * @return void
821 function tag_compute_correlations($mincorrelation = 2) {
822 global $DB;
824 // This mighty one line query fetches a row from the database for every
825 // individual tag correlation. We then need to process the rows collecting
826 // the correlations for each tag id.
827 // The fields used by this query are as follows:
828 // tagid : This is the tag id, there should be at least $mincorrelation
829 // rows for each tag id.
830 // correlation : This is the tag id that correlates to the above tagid field.
831 // correlationid : This is the id of the row in the tag_correlation table that
832 // relates to the tagid field and will be NULL if there are no
833 // existing correlations
834 $sql = 'SELECT ta.tagid, tb.tagid AS correlation, co.id AS correlationid, co.correlatedtags
835 FROM {tag_instance} ta
836 LEFT JOIN {tag_instance} tb
837 ON (ta.itemtype = tb.itemtype AND ta.itemid = tb.itemid AND ta.tagid <> tb.tagid)
838 LEFT JOIN {tag_correlation} co
839 ON co.tagid = ta.tagid
840 WHERE tb.tagid IS NOT NULL
841 GROUP BY ta.tagid, tb.tagid
842 HAVING COUNT(*) > :mincorrelation
843 ORDER BY ta.tagid ASC, COUNT(*) DESC, tb.tagid ASC';
844 $rs = $DB->get_recordset_sql($sql, array('mincorrelation' => $mincorrelation));
846 // Set up an empty tag correlation object
847 $tagcorrelation = new stdClass;
848 $tagcorrelation->id = null;
849 $tagcorrelation->tagid = null;
850 $tagcorrelation->correlatedtags = array();
852 // Iterate each row of the result set and build them into tag correlations.
853 foreach ($rs as $row) {
854 if ($row->tagid != $tagcorrelation->tagid) {
855 // The tag id has changed so its now time to process the tag
856 // correlation information we have.
857 tag_process_computed_correlation($tagcorrelation);
858 // Now we reset the tag correlation object so we can reuse it and set it
859 // up for the current record.
860 $tagcorrelation = new stdClass;
861 $tagcorrelation->id = $row->correlationid;
862 $tagcorrelation->tagid = $row->tagid;
863 $tagcorrelation->correlatedtags = array();
865 $tagcorrelation->correlatedtags[] = $row->correlation;
867 // Update the current correlation after the last record.
868 tag_process_computed_correlation($tagcorrelation);
870 // Close the recordset
871 $rs->close();
875 * This function processes a tag correlation and makes changes in the database
876 * as required.
878 * The tag correlation object needs have both a tagid property and a correlatedtags
879 * property that is an array.
881 * @param stdClass $tagcorrelation
882 * @return bool True if the function completed, false if something was wrong.
884 function tag_process_computed_correlation(stdClass $tagcorrelation) {
885 global $DB;
887 // You must provide a tagid and correlatedtags must be set and be an array
888 if (empty($tagcorrelation->tagid) || !isset($tagcorrelation->correlatedtags) || !is_array($tagcorrelation->correlatedtags)) {
889 return false;
892 // The row tagid doesn't match the current tag id which means we are onto
893 // the next tag. Before we switch over we need to either insert or update
894 // the correlation.
895 $tagcorrelation->correlatedtags = join(',', $tagcorrelation->correlatedtags);
896 if (!empty($tagcorrelation->id)) {
897 // The tag correlation already exists so update it
898 $DB->update_record('tag_correlation', $tagcorrelation);
899 } else {
900 // This is a new correlation to insert
901 $DB->insert_record('tag_correlation', $tagcorrelation);
903 return true;
907 * Tasks that should be performed at cron time
909 function tag_cron() {
910 tag_compute_correlations();
911 tag_cleanup();
915 * Search for tags with names that match some text
917 * @param string $text escaped string that the tag names will be matched against
918 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
919 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
920 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
921 * @return mixed an array of objects, or false if no records were found or an error occured.
923 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
924 global $DB;
926 $text = array_shift(tag_normalize($text, TAG_CASE_LOWER));
928 if ($ordered) {
929 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
930 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
931 WHERE tg.name LIKE ?
932 GROUP BY tg.id, tg.name, tg.rawname
933 ORDER BY count DESC";
934 } else {
935 $query = "SELECT tg.id, tg.name, tg.rawname
936 FROM {tag} tg
937 WHERE tg.name LIKE ?";
939 $params = array("%{$text}%");
940 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
944 * Get the name of a tag
946 * @param mixed $tagids the id of the tag, or an array of ids
947 * @return mixed string name of one tag, or id-indexed array of strings
949 function tag_get_name($tagids) {
950 global $DB;
952 if (!is_array($tagids)) {
953 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
954 return $tag->name;
956 return false;
959 $tag_names = array();
960 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
961 $tag_names[$tag->id] = $tag->name;
964 return $tag_names;
968 * Returns the correlated tags of a tag, retrieved from the tag_correlation
969 * table. Make sure cron runs, otherwise the table will be empty and this
970 * function won't return anything.
972 * @param int $tag_id is a single tag id
973 * @return array an array of tag objects, empty if no correlated tags are found
975 function tag_get_correlated($tag_id, $limitnum=null) {
976 global $DB;
978 $tag_correlation = $DB->get_record('tag_correlation', array('tagid'=>$tag_id));
980 if (!$tag_correlation || empty($tag_correlation->correlatedtags)) {
981 return array();
984 // this is (and has to) return the same fields as the query in tag_get_tags
985 if ( !$result = $DB->get_records_sql("SELECT DISTINCT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering
986 FROM {tag} tg INNER JOIN {tag_instance} ti ON tg.id = ti.tagid
987 WHERE tg.id IN ({$tag_correlation->correlatedtags})") ) {
988 return array();
991 return $result;
995 * Function that normalizes a list of tag names.
997 * @param mixed $tags array of tags, or a single tag.
998 * @param int $case case to use for returned value (default: lower case).
999 * Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
1000 * @return array of lowercased normalized tags, indexed by the normalized tag,
1001 * in the same order as the original array. (Eg: 'Banana' => 'banana').
1003 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
1005 // cache normalized tags, to prevent costly repeated calls to clean_param
1006 static $cleaned_tags_lc = array(); // lower case - use for comparison
1007 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
1009 if ( !is_array($rawtags) ) {
1010 $rawtags = array($rawtags);
1013 $result = array();
1014 foreach($rawtags as $rawtag) {
1015 $rawtag = trim($rawtag);
1016 if (!$rawtag) {
1017 continue;
1019 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
1020 $cleaned_tags_lc[$rawtag] = moodle_strtolower( clean_param($rawtag, PARAM_TAG) );
1021 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
1023 if ( $case == TAG_CASE_LOWER ) {
1024 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
1025 } else { // TAG_CASE_ORIGINAL
1026 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
1030 return $result;
1034 * Count how many records are tagged with a specific tag,
1036 * @param string $record record to look for ('post', 'user', etc.)
1037 * @param int $tag is a single tag id
1038 * @return int number of mathing tags.
1040 function tag_record_count($record_type, $tagid) {
1041 global $DB;
1042 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'tagid'=>$tagid));
1046 * Determine if a record is tagged with a specific tag
1048 * @param string $record_type the record type to look for
1049 * @param int $record_id the record id to look for
1050 * @param string $tag a tag name
1051 * @return bool true if it is tagged, false otherwise
1053 function tag_record_tagged_with($record_type, $record_id, $tag) {
1054 global $DB;
1055 if ($tagid = tag_get_id($tag)) {
1056 return $DB->count_records('tag_instance', array('itemtype'=>$record_type, 'itemid'=>$record_id, 'tagid'=>$tagid));
1057 } else {
1058 return 0; // tag doesn't exist
1063 * Flag a tag as inapropriate
1065 * @param mixed $tagids one (int) tagid, or an array of tagids
1066 * @return void
1068 function tag_set_flag($tagids) {
1069 global $DB;
1071 $tagids = (array)$tagids;
1072 foreach ($tagids as $tagid) {
1073 $tag = $DB->get_record('tag', array('id'=>$tagid), 'id, flag');
1074 $tag->flag++;
1075 $tag->timemodified = time();
1076 $DB->update_record('tag', $tag);
1081 * Remove the inapropriate flag on a tag
1083 * @param mixed $tagids one (int) tagid, or an array of tagids
1084 * @return bool true if function succeeds, false otherwise
1086 function tag_unset_flag($tagids) {
1087 global $DB;
1089 if ( is_array($tagids) ) {
1090 $tagids = implode(',', $tagids);
1092 $timemodified = time();
1093 return $DB->execute("UPDATE {tag} SET flag = 0, timemodified = ? WHERE id IN ($tagids)", array($timemodified));