6 * Tag strings : you can use any character in tags, except the comma (which is
7 * the separator) and the '\' (backslash). Note that many spaces (or other
8 * blank characters) will get "compressed" into one. A tag string is always a
9 * rawurlencode'd string. This is the same behavior as http://del.icio.us.
11 * A "record" is a php array (note that an object will work too) that contains
12 * the following variables :
13 * - type: the table containing the record that we are tagging (eg: for a
14 * blog, this is table 'post', and for a user it is 'user')
15 * - id: the id of the record
17 * TODO: turn this into a full-fledged categorization system. This could start
18 * by modifying (removing, probably) the 'tag type' to use another table
19 * describing the relationship between tags (parents, sibling, etc.), which
20 * could then be merged with the 'course categorization' system...
22 * BASIC INSTRUCTIONS :
23 * - to "tag a blog post" (for example):
24 * tag_set('post', $blog_post->id, $array_of_tags);
26 * - to "remove all the tags on a blog post":
27 * tag_set('post', $blog_post->id, array());
29 * Tag set will create tags that need to be created.
32 * @licence http://www.gnu.org/copyleft/gpl.html GNU Public License
35 * @see http://www.php.net/manual/en/function.urlencode.php
38 define('TAG_RETURN_ARRAY', 0);
39 define('TAG_RETURN_OBJECT', 1);
40 define('TAG_RETURN_TEXT', 2);
41 define('TAG_RETURN_HTML', 3);
43 define('TAG_CASE_LOWER', 0);
44 define('TAG_CASE_ORIGINAL', 1);
46 define('TAG_RELATED_ALL', 0);
47 define('TAG_RELATED_MANUAL', 1);
48 define('TAG_RELATED_CORRELATED', 2);
51 require_once($CFG->dirroot
.'/tag/locallib.php');
53 ///////////////////////////////////////////////////////
54 /////////////////// PUBLIC TAG API ////////////////////
56 /// Functions for settings tags //////////////////////
59 * Set the tags assigned to a record. This overwrites the current tags.
61 * This function is meant to be fed the string coming up from the user
62 * interface, which contains all tags assigned to a record.
64 * @param string $record_type the type of record to tag ('post' for blogs,
65 * 'user' for users, 'tag' for tags, etc.
66 * @param int $record_id the id of the record to tag
67 * @param array $tags the array of tags to set on the record. If
68 * given an empty array, all tags will be removed.
71 function tag_set($record_type, $record_id, $tags) {
73 static $in_recursion_semaphore = false; // this is to prevent loops when tagging a tag
74 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
75 $current_tagged_tag_name = tag_get_name($record_id);
78 $tags_ids = tag_get_id($tags, TAG_RETURN_ARRAY
); // force an array, even if we only have one tag.
79 $cleaned_tags = tag_normalize($tags);
80 //echo 'tags-in-tag_set'; var_dump($tags); var_dump($tags_ids); var_dump($cleaned_tags);
82 $current_ids = tag_get_tags_ids($record_type, $record_id);
83 //var_dump($current_ids);
85 // for data coherence reasons, it's better to remove deleted tags
86 // before adding new data: ordering could be duplicated.
87 foreach($current_ids as $current_id) {
88 if (!in_array($current_id, $tags_ids)) {
89 tag_delete_instance($record_type, $record_id, $current_id);
90 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
91 // if we are removing a tag-on-a-tag (manually related tag),
92 // we need to remove the opposite relationship as well.
93 tag_delete_instance('tag', $current_id, $record_id);
98 foreach($tags as $ordering => $tag) {
104 $clean_tag = $cleaned_tags[$tag];
105 $tag_current_id = $tags_ids[$clean_tag];
107 if ( is_null($tag_current_id) ) {
109 //echo "call to add tag $tag\n";
110 $new_tag = tag_add($tag);
111 $tag_current_id = $new_tag[$clean_tag];
114 tag_assign($record_type, $record_id, $tag_current_id, $ordering);
116 // if we are tagging a tag (adding a manually-assigned related tag), we
117 // need to create the opposite relationship as well.
118 if ( $record_type == 'tag' && !$in_recursion_semaphore) {
119 $in_recursion_semaphore = true;
120 tag_set_add('tag', $tag_current_id, $current_tagged_tag_name);
121 $in_recursion_semaphore = false;
127 * Adds a tag to a record, without overwriting the current tags.
129 * @param string $record_type the type of record to tag ('post' for blogs,
130 * 'user' for users, etc.
131 * @param int $record_id the id of the record to tag
132 * @param string $tag the tag to add
135 function tag_set_add($record_type, $record_id, $tag) {
138 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
139 $new_tags[] = $current_tag->rawname
;
143 return tag_set($record_type, $record_id, $new_tags);
147 * Removes a tag from a record, without overwriting other current tags.
149 * @param string $record_type the type of record to tag ('post' for blogs,
150 * 'user' for users, etc.
151 * @param int $record_id the id of the record to tag
152 * @param string $tag the tag to delete
155 function tag_set_delete($record_type, $record_id, $tag) {
158 foreach( tag_get_tags($record_type, $record_id) as $current_tag ) {
159 if ($current_tag->name
!= $tag) { // Keep all tags but the one specified
160 $new_tags[] = $current_tag->name
;
164 return tag_set($record_type, $record_id, $new_tags);
168 * Set the type of a tag. At this time (version 1.9) the possible values
169 * are 'default' or 'official'. Official tags will be displayed separately "at
170 * tagging time" (while selecting the tags to apply to a record).
172 * @param string $tagid tagid to modify
173 * @param string $type either 'default' or 'official'
174 * @return true on success, false otherwise
176 function tag_type_set($tagid, $type) {
177 if ($tag = get_record('tag', 'id', $tagid, '', '', '', '', 'id')) {
178 $tag->tagtype
= addslashes($type);
179 $tag->timemodified
= time();
180 return update_record('tag', $tag);
187 * Set the description of a tag
189 * @param int $tagid the id of the tag
190 * @param string $description the description
191 * @param int $descriptionformat the moodle text format of the description
192 * @return true on success, false otherwise
194 function tag_description_set($tagid, $description, $descriptionformat) {
195 if ($tag = get_record('tag', 'id', $tagid, '', '', '', '', 'id')) {
196 $tag->description
= addslashes($description);
197 $tag->descriptionformat
= addslashes($descriptionformat);
198 $tag->timemodified
= time();
199 return update_record('tag', $tag);
209 /// Functions for getting information about tags //////
212 * Simple function to just return a single tag object when you know the name or something
214 * @param string $field which field do we use to identify the tag: id, name or rawname
215 * @param string $value the required value of the aforementioned field
216 * @param string $returnfields which fields do we want returned?
220 function tag_get($field, $value, $returnfields='id, name, rawname') {
221 if ($field == 'name') {
222 $value = addslashes(moodle_strtolower($value)); // To cope with input that might just be wrong case
224 return get_record('tag', $field, $value, '', '', '', '', $returnfields);
229 * Get the array of db record of tags associated to a record (instances). Use
230 * tag_get_tags_csv to get the same information in a comma-separated string.
232 * @param string $record_type the record type for which we want to get the tags
233 * @param int $record_id the record id for which we want to get the tags
234 * @param string $type the tag type (either 'default' or 'official'). By default,
235 * all tags are returned.
236 * @return array the array of tags
238 function tag_get_tags($record_type, $record_id, $type=null) {
243 $type = "AND tg.tagtype = '$type'";
246 // if the fields in this query are changed, you need to do the same changes in tag_get_correlated_tags
247 $tags = get_records_sql("SELECT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
248 "FROM {$CFG->prefix}tag_instance ti INNER JOIN {$CFG->prefix}tag tg ON tg.id = ti.tagid ".
249 "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
250 "ORDER BY ti.ordering ASC");
251 // This version of the query, reversing the ON clause, "correctly" returns
252 // a row with NULL values for instances that are still in the DB even though
253 // the tag has been deleted. This shouldn't happen, but if it did, using
254 // this query could help "clean it up". This causes bugs at this time.
255 //$tags = get_records_sql("SELECT ti.tagid, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
256 // "FROM {$CFG->prefix}tag_instance ti LEFT JOIN {$CFG->prefix}tag tg ON ti.tagid = tg.id ".
257 // "WHERE ti.itemtype = '{$record_type}' AND ti.itemid = '{$record_id}' {$type} ".
258 // "ORDER BY ti.ordering ASC");
268 * Get the array of tags display names, indexed by id.
270 * @param string $record_type the record type for which we want to get the tags
271 * @param int $record_id the record id for which we want to get the tags
272 * @param string $type the tag type (either 'default' or 'official'). By default,
273 * all tags are returned.
274 * @return array the array of tags (with the value returned by tag_display_name), indexed by id
276 function tag_get_tags_array($record_type, $record_id, $type=null) {
278 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
279 $tags[$tag->id
] = tag_display_name($tag);
285 * Get a comma-separated string of tags associated to a record. Use tag_get_tags
286 * to get the same information in an array.
288 * @param string $record_type the record type for which we want to get the tags
289 * @param int $record_id the record id for which we want to get the tags
290 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending
291 * on the type of output desired
292 * @param string $type either 'official' or 'default', if null, all tags are
294 * @return string the comma-separated list of tags.
296 function tag_get_tags_csv($record_type, $record_id, $html=TAG_RETURN_HTML
, $type=null) {
299 $tags_names = array();
300 foreach(tag_get_tags($record_type, $record_id, $type) as $tag) {
301 if ($html == TAG_RETURN_TEXT
) {
302 $tags_names[] = tag_display_name($tag);
303 } else { // TAG_RETURN_HTML
304 $tags_names[] = '<a href="'. $CFG->wwwroot
.'/tag/index.php?tag='. rawurlencode($tag->name
) .'">'. tag_display_name($tag) .'</a>';
307 return implode(', ', $tags_names);
311 * Get an array of tag ids associated to a record.
313 * @param string $record_type the record type for which we want to get the tags
314 * @param int $record_id the record id for which we want to get the tags
315 * @return array of tag ids, indexed and sorted by 'ordering'
317 function tag_get_tags_ids($record_type, $record_id) {
320 foreach (tag_get_tags($record_type, $record_id) as $tag) {
321 if ( array_key_exists($tag->ordering
, $tag_ids) ) {
322 // until we can add a unique constraint, in table tag_instance,
323 // on (itemtype, itemid, ordering), this is needed to prevent a bug
324 // TODO : modify database in 2.0
327 $tag_ids[$tag->ordering
] = $tag->id
;
334 * Returns the database ID of a set of tags.
336 * @param mixed $tags one tag, or array of tags, to look for.
337 * @param bool $return_value specify the type of the returned value. Either
338 * TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default). If TAG_RETURN_ARRAY
339 * is specified, an array will be returned even if only one tag was
341 * @return mixed tag-indexed array of ids (or objects, if second parameter is
342 * TAG_RETURN_OBJECT), or only an int, if only one tag is given *and* the
343 * second parameter is null. No value for a key means the tag wasn't found.
345 function tag_get_id($tags, $return_value=null) {
347 static $tag_id_cache = array();
349 $return_an_int = false;
350 if (!is_array($tags)) {
351 if(is_null($return_value) ||
$return_value == TAG_RETURN_OBJECT
) {
352 $return_an_int = true;
354 $tags = array($tags);
359 //TODO: test this and see if it helps performance without breaking anything
360 //foreach($tags as $key => $tag) {
361 // $clean_tag = moodle_strtolower($tag);
362 // if ( array_key_exists($clean_tag), $tag_id_cache) ) {
363 // $result[$clean_tag] = $tag_id_cache[$clean_tag];
364 // $tags[$key] = ''; // prevent further processing for this one.
368 $tags = array_values(tag_normalize($tags));
369 foreach($tags as $key => $tag) {
370 $tags[$key] = addslashes(moodle_strtolower($tag));
371 $result[moodle_strtolower($tag)] = null; // key must exists : no value for a key means the tag wasn't found.
373 $tag_string = "'". implode("', '", $tags) ."'";
375 if ($rs = get_recordset_sql("SELECT * FROM {$CFG->prefix}tag WHERE name in ({$tag_string}) order by name")) {
376 while ($record = rs_fetch_next_record($rs)) {
377 if ($return_value == TAG_RETURN_OBJECT
) {
378 $result[$record->name
] = $record;
379 } else { // TAG_RETURN_ARRAY
380 $result[$record->name
] = $record->id
;
385 if ($return_an_int) {
386 return array_pop($result);
394 * Returns tags related to a tag
396 * Related tags of a tag come from two sources:
397 * - manually added related tags, which are tag_instance entries for that tag
398 * - correlated tags, which are a calculated
400 * @param string $tag_name_or_id is a single **normalized** tag name or the id
402 * @param int $type the function will return either manually
403 * (TAG_RELATED_MANUAL) related tags or correlated (TAG_RELATED_CORRELATED)
404 * tags. Default is TAG_RELATED_ALL, which returns everything.
405 * @param int $limitnum return a subset comprising this many records (optional,
407 * @return array an array of tag objects
409 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL
, $limitnum=10) {
411 $related_tags = array();
413 if ( $type == TAG_RELATED_ALL ||
$type == TAG_RELATED_MANUAL
) {
414 //gets the manually added related tags
415 $related_tags = tag_get_tags('tag', $tagid);
418 if ( $type == TAG_RELATED_ALL ||
$type == TAG_RELATED_CORRELATED
) {
419 //gets the correlated tags
420 $automatic_related_tags = tag_get_correlated($tagid, $limitnum);
421 if (is_array($automatic_related_tags)) {
422 $related_tags = array_merge($related_tags, $automatic_related_tags);
426 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
430 * Get a comma-separated list of tags related to another tag.
432 * @param array $related_tags the array returned by tag_get_related_tags
433 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
434 * @return string comma-separated list
436 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML
) {
439 $tags_names = array();
440 foreach($related_tags as $tag) {
441 if ( $html == TAG_RETURN_TEXT
) {
442 $tags_names[] = tag_display_name($tag);
445 $tags_names[] = '<a href="'. $CFG->wwwroot
.'/tag/index.php?tag='. rawurlencode($tag->name
) .'">'. tag_display_name($tag) .'</a>';
449 return implode(', ', $tags_names);
453 * Change the "value" of a tag, and update the associated 'name'.
455 * @param int $tagid the id of the tag to modify
456 * @param string $newtag the new rawname
457 * @return bool true on success, false otherwise
459 function tag_rename($tagid, $newrawname) {
461 if (! $newrawname_clean = array_shift(tag_normalize($newrawname, TAG_CASE_ORIGINAL
)) ) {
465 if (! $newname_clean = moodle_strtolower($newrawname_clean)) {
469 // Prevent the rename if a tag with that name already exists
470 if ($existing = tag_get('name', $newname_clean, 'id, name, rawname')) {
471 if ($existing->id
!= $tagid) { // Another tag already exists with this name
476 if ($tag = tag_get('id', $tagid, 'id, name, rawname')) {
477 $tag->rawname
= addslashes($newrawname_clean);
478 $tag->name
= addslashes($newname_clean);
479 $tag->timemodified
= time();
480 return update_record('tag', $tag);
487 * Delete one or more tag, and all their instances if there are any left.
489 * @param mixed $tagids one tagid (int), or one array of tagids to delete
490 * @return bool true on success, false otherwise
492 function tag_delete($tagids) {
494 if (!is_array($tagids)) {
495 $tagids = array($tagids);
499 foreach( $tagids as $tagid ) {
500 if (is_null($tagid)) { // can happen if tag doesn't exists
503 // only delete the main entry if there were no problems deleting all the
504 // instances - that (and the fact we won't often delete lots of tags)
505 // is the reason for not using delete_records_select()
506 if ( delete_records('tag_instance', 'tagid', $tagid) ) {
507 $success &= (bool) delete_records('tag', 'id', $tagid);
515 * Delete one instance of a tag. If the last instance was deleted, it will
516 * also delete the tag, unless it's type is 'official'.
518 * @param string $record_type the type of the record for which to remove the instance
519 * @param int $record_id the id of the record for which to remove the instance
520 * @param int $tagid the tagid that needs to be removed
521 * @return bool true on success, false otherwise
523 function tag_delete_instance($record_type, $record_id, $tagid) {
526 if ( delete_records('tag_instance', 'tagid', $tagid, 'itemtype', $record_type, 'itemid', $record_id) ) {
527 if ( !record_exists_sql("SELECT * FROM {$CFG->prefix}tag tg, {$CFG->prefix}tag_instance ti ".
528 "WHERE (tg.id = ti.tagid AND ti.tagid = {$tagid} ) OR ".
529 "(tg.id = {$tagid} AND tg.tagtype = 'official')") ) {
530 return tag_delete($tagid);
541 * Function that returns the name that should be displayed for a specific tag
543 * @param object $tag_object a line out of tag table, as returned by the adobd functions
546 function tag_display_name($tag_object) {
550 if(!isset($tag_object->name
)) {
554 if (empty($CFG->keeptagnamecase
)) {
555 //this is the normalized tag name
556 $textlib = textlib_get_instance();
557 return htmlspecialchars($textlib->strtotitle($tag_object->name
));
559 //original casing of the tag name
560 return htmlspecialchars($tag_object->rawname
);
565 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
567 * @param string $tag tag to look for
568 * @param string $type type to restrict search to. If null, every matching
569 * record will be returned
570 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
571 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
572 * @return array of matching objects, indexed by record id, from the table containing the type requested
574 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
578 if (!$tag ||
!$type) {
582 $tagid = tag_get_id($tag);
584 $query = "SELECT it.* ".
585 "FROM {$CFG->prefix}{$type} it INNER JOIN {$CFG->prefix}tag_instance tt ON it.id = tt.itemid ".
586 "WHERE tt.itemtype = '{$type}' AND tt.tagid = '{$tagid}'";
588 return get_records_sql($query, $limitfrom, $limitnum);
594 ///////////////////////////////////////////////////////
595 /////////////////// PRIVATE TAG API ///////////////////
598 * Adds one or more tag in the database. This function should not be called
599 * directly : you should use tag_set.
601 * @param mixed $tags one tag, or an array of tags, to be created
602 * @param string $type type of tag to be created ("default" is the default
603 * value and "official" is the only other supported value at this time). An
604 * official tag is kept even if there are no records tagged with it.
605 * @return an array of tags ids, indexed by their lowercase normalized names.
606 * Any boolean false in the array indicates an error while adding the tag.
608 function tag_add($tags, $type="default") {
611 require_capability('moodle/tag:create', get_context_instance(CONTEXT_SYSTEM
));
613 if (!is_array($tags)) {
614 $tags = array($tags);
617 $tag_object = new StdClass
;
618 $tag_object->tagtype
= $type;
619 $tag_object->userid
= $USER->id
;
620 $tag_object->timemodified
= time();
622 $clean_tags = tag_normalize($tags, TAG_CASE_ORIGINAL
);
625 foreach($clean_tags as $tag) {
628 $tags_ids[$tag] = false;
630 // note that the difference between rawname and name is only
631 // capitalization : the rawname is NOT the same at the rawtag.
632 $tag_object->rawname
= addslashes($tag);
633 $tag_name_lc = moodle_strtolower($tag);
634 $tag_object->name
= addslashes($tag_name_lc);
635 //var_dump($tag_object);
636 $tags_ids[$tag_name_lc] = insert_record('tag', $tag_object);
644 * Assigns a tag to a record: if the record already exists, the time and
645 * ordering will be updated.
647 * @param string $record_type the type of the record that will be tagged
648 * @param int $record_id the id of the record that will be tagged
649 * @param string $tagid the tag id to set on the record.
650 * @param int $ordering the order of the instance for this record
651 * @return bool true on success, false otherwise
653 function tag_assign($record_type, $record_id, $tagid, $ordering) {
655 require_capability('moodle/tag:create', get_context_instance(CONTEXT_SYSTEM
));
657 if ( $tag_instance_object = get_record('tag_instance', 'tagid', $tagid, 'itemtype', $record_type, 'itemid', $record_id, 'id') ) {
658 $tag_instance_object->ordering
= $ordering;
659 $tag_instance_object->timemodified
= time();
660 return update_record('tag_instance', $tag_instance_object);
662 $tag_instance_object = new StdClass
;
663 $tag_instance_object->tagid
= $tagid;
664 $tag_instance_object->itemid
= $record_id;
665 $tag_instance_object->itemtype
= $record_type;
666 $tag_instance_object->ordering
= $ordering;
667 $tag_instance_object->timemodified
= time();
668 return insert_record('tag_instance', $tag_instance_object);
673 * Function that returns tags that start with some text, for use by the autocomplete feature
675 * @param string $text string that the tag names will be matched against
676 * @return mixed an array of objects, or false if no records were found or an error occured.
678 function tag_autocomplete($text) {
680 return get_records_sql("SELECT tg.id, tg.name, tg.rawname FROM {$CFG->prefix}tag tg WHERE tg.name LIKE '". moodle_strtolower($text) ."%'");
684 * Clean up the tag tables, making sure all tagged object still exists.
686 * This should normally not be necessary, but in case related tags are not deleted
687 * when the tagged record is removed, this should be done once in a while, perhaps on
688 * an occasional cron run. On a site with lots of tags, this could become an expensive
689 * function to call: don't run at peak time.
691 function tag_cleanup() {
694 $instances = get_recordset('tag_instance');
696 // cleanup tag instances
697 while ($instance = rs_fetch_next_record($instances)) {
700 if (!record_exists('tag', 'id', $instance->tagid
)) {
701 // if the tag has been removed, instance should be deleted.
704 switch ($instance->itemtype
) {
705 case 'user': // users are marked as deleted, but not actually deleted
706 if (record_exists('user', 'id', $instance->itemid
, 'deleted', 1)) {
710 default: // anything else, if the instance is not there, delete.
711 if (!record_exists($instance->itemtype
, 'id', $instance->itemid
)) {
718 tag_delete_instance($instance->itemtype
, $instance->itemid
, $instance->tagid
);
719 //debugging('deleting tag_instance #'. $instance->id .', linked to tag id #'. $instance->tagid, DEBUG_DEVELOPER);
722 rs_close($instances);
724 // TODO: this will only clean tags of type 'default'. This is good as
725 // it won't delete 'official' tags, but the day we get more than two
726 // types, we need to fix this.
727 $unused_tags = get_recordset_sql("SELECT tg.id FROM {$CFG->prefix}tag tg WHERE tg.tagtype = 'default' AND NOT EXISTS (".
728 "SELECT 'x' FROM {$CFG->prefix}tag_instance ti WHERE ti.tagid = tg.id)");
731 while ($unused_tag = rs_fetch_next_record($unused_tags)) {
732 tag_delete($unused_tag->id
);
733 //debugging('deleting unused tag #'. $unused_tag->id, DEBUG_DEVELOPER);
735 rs_close($unused_tags);
739 * Calculates and stores the correlated tags of all tags.
740 * The correlations are stored in the 'tag_correlation' table.
742 * Two tags are correlated if they appear together a lot.
743 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
745 * The rationale for the 'tag_correlation' table is performance.
746 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
747 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
749 * @param number $min_correlation cutoff percentage (optional, default is 2)
751 function tag_compute_correlations($min_correlation=2) {
755 if (!$all_tags = get_records_list('tag')) {
759 $tag_correlation_obj = new object();
760 foreach($all_tags as $tag) {
762 // query that counts how many times any tag appears together in items
763 // with the tag passed as argument ($tag_id)
764 $query = "SELECT tb.tagid , COUNT(*) AS nr ".
765 "FROM {$CFG->prefix}tag_instance ta INNER JOIN {$CFG->prefix}tag_instance tb ON ta.itemid = tb.itemid ".
766 "WHERE ta.tagid = {$tag->id} AND tb.tagid != {$tag->id} ".
767 "GROUP BY tb.tagid ".
768 "HAVING nr > $min_correlation ".
771 $correlated = array();
773 // Correlated tags happen when they appear together in more occasions
774 // than $min_correlation.
775 if ($tag_correlations = get_records_sql($query)) {
776 foreach($tag_correlations as $correlation) {
777 // commented out - now done in query. kept here in case it breaks on some db
778 // if($correlation->nr >= $min_correlation){
779 $correlated[] = $correlation->tagid
;
784 if (empty($correlated)) {
788 $correlated = implode(',', $correlated);
789 //var_dump($correlated);
791 //saves correlation info in the caching table
792 if ($tag_correlation_obj = get_record('tag_correlation', 'tagid', $tag->id
, '', '', '', '', 'tagid')) {
793 $tag_correlation_obj->correlatedtags
= $correlated;
794 update_record('tag_correlation', $tag_correlation_obj);
796 $tag_correlation_obj->tagid
= $tag->id
;
797 $tag_correlation_obj->correlatedtags
= $correlated;
798 insert_record('tag_correlation', $tag_correlation_obj);
804 * Tasks that should be performed at cron time
806 function tag_cron() {
807 tag_compute_correlations();
812 * Search for tags with names that match some text
814 * @param string $text escaped string that the tag names will be matched against
815 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
816 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
817 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
818 * @return mixed an array of objects, or false if no records were found or an error occured.
820 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='') {
824 $text = array_shift(tag_normalize($text, TAG_CASE_LOWER
));
827 $query = "SELECT tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count ".
828 "FROM {$CFG->prefix}tag tg LEFT JOIN {$CFG->prefix}tag_instance ti ON tg.id = ti.tagid ".
829 "WHERE tg.name LIKE '%{$text}%' ".
830 "GROUP BY tg.id, tg.name, tg.rawname ".
831 "ORDER BY count DESC";
833 $query = "SELECT tg.id, tg.name, tg.rawname ".
834 "FROM {$CFG->prefix}tag tg ".
835 "WHERE tg.name LIKE '%{$text}%'";
837 return get_records_sql($query, $limitfrom , $limitnum);
841 * Get the name of a tag
843 * @param mixed $tagids the id of the tag, or an array of ids
844 * @return mixed string name of one tag, or id-indexed array of strings
846 function tag_get_name($tagids) {
848 $return_a_string = false;
849 if ( !is_array($tagids) ) {
850 $return_a_string = true;
851 $tagids = array($tagids);
854 $tag_names = array();
855 foreach(get_records_list('tag', 'id', implode(',', $tagids)) as $tag) {
856 $tag_names[$tag->id
] = $tag->name
;
859 if ($return_a_string) {
860 return array_pop($tag_names);
867 * Returns the correlated tags of a tag, retrieved from the tag_correlation
868 * table. Make sure cron runs, otherwise the table will be empty and this
869 * function won't return anything.
871 * @param int $tag_id is a single tag id
872 * @return array an array of tag objects, empty if no correlated tags are found
874 function tag_get_correlated($tag_id, $limitnum=null) {
877 $tag_correlation = get_record('tag_correlation', 'tagid', $tag_id);
879 if (!$tag_correlation ||
empty($tag_correlation->correlatedtags
)) {
883 // this is (and has to) return the same fields as the query in tag_get_tags
884 if ( !$result = get_records_sql("SELECT tg.id, tg.tagtype, tg.name, tg.rawname, tg.flag, ti.ordering ".
885 "FROM {$CFG->prefix}tag tg INNER JOIN {$CFG->prefix}tag_instance ti ON tg.id = ti.tagid ".
886 "WHERE tg.id IN ({$tag_correlation->correlatedtags})") ) {
894 * Function that normalizes a list of tag names.
896 * @param mixed $tags array of tags, or a single tag.
897 * @param int $case case to use for returned value (default: lower case).
898 * Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
899 * @return array of lowercased normalized tags, indexed by the normalized tag,
900 * in the same order as the original array. (Eg: 'Banana' => 'banana').
902 function tag_normalize($rawtags, $case = TAG_CASE_LOWER
) {
904 // cache normalized tags, to prevent costly repeated calls to clean_param
905 static $cleaned_tags_lc = array(); // lower case - use for comparison
906 static $cleaned_tags_mc = array(); // mixed case - use for saving to database
908 if ( !is_array($rawtags) ) {
909 $rawtags = array($rawtags);
913 foreach($rawtags as $rawtag) {
914 $rawtag = trim($rawtag);
918 if ( !array_key_exists($rawtag, $cleaned_tags_lc) ) {
919 $cleaned_tags_lc[$rawtag] = moodle_strtolower( clean_param($rawtag, PARAM_TAG
) );
920 $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG
);
922 if ( $case == TAG_CASE_LOWER
) {
923 $result[$rawtag] = $cleaned_tags_lc[$rawtag];
924 } else { // TAG_CASE_ORIGINAL
925 $result[$rawtag] = $cleaned_tags_mc[$rawtag];
933 * Count how many records are tagged with a specific tag,
935 * @param string $record record to look for ('post', 'user', etc.)
936 * @param int $tag is a single tag id
937 * @return int number of mathing tags.
939 function tag_record_count($record_type, $tagid) {
940 return count_records('tag_instance', 'itemtype', $record_type, 'tagid', $tagid);
944 * Determine if a record is tagged with a specific tag
946 * @param string $record_type the record type to look for
947 * @param int $record_id the record id to look for
948 * @param string $tag a tag name
949 * @return bool true if it is tagged, false otherwise
951 function tag_record_tagged_with($record_type, $record_id, $tag) {
952 if ($tagid = tag_get_id($tag)) {
953 return count_records('tag_instance', 'itemtype', $record_type, 'itemid', $record_id, 'tagid', $tagid);
955 return 0; // tag doesn't exist
960 * Flag a tag as inapropriate
962 * @param mixed $tagids one (int) tagid, or an array of tagids
965 function tag_set_flag($tagids) {
966 if ( !is_array($tagids) ) {
967 $tagids = array($tagids);
969 foreach ($tagids as $tagid) {
970 $tag = get_record('tag', 'id', $tagid, '', '', '', '', 'id, flag');
972 $tag->timemodified
= time();
973 update_record('tag', $tag);
978 * Remove the inapropriate flag on a tag
980 * @param mixed $tagids one (int) tagid, or an array of tagids
981 * @return bool true if function succeeds, false otherwise
983 function tag_unset_flag($tagids) {
986 require_capability('moodle/tag:manage', get_context_instance(CONTEXT_SYSTEM
));
988 if ( is_array($tagids) ) {
989 $tagids = implode(',', $tagids);
991 $timemodified = time();
992 return execute_sql("UPDATE {$CFG->prefix}tag tg SET tg.flag = 0, tg.timemodified = $timemodified WHERE tg.id IN ($tagids)", false);