3 define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
8 * Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
9 * will create the following normalized {@link tag_normalize()} entries in tags table:
13 * @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
14 * @param string $tag_type type of tag to be created ("default" is the default value).
15 * @return an array of tags ids, indexed by their normalized names
17 function tag_create($tag_names_csv, $tag_type="default") {
19 $textlib = textlib_get_instance();
21 $tags = explode(",", $tag_names_csv );
23 $tag_object = new StdClass
;
24 $tag_object->tagtype
= $tag_type;
25 $tag_object->userid
= $USER->id
;
27 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
28 $can_create_tags = has_capability('moodle/tag:create',$systemcontext);
30 $norm_tag_names_csv = '';
31 foreach ($tags as $tag) {
33 // rawname keeps the original casing of the string
34 $tag_object->rawname
= tag_normalize($tag, false);
36 // name lowercases the string
37 $tag_object->name
= tag_normalize($tag);
38 $norm_tag_names_csv .= $tag_object->name
. ',';
40 $tag_object->timemodified
= time();
42 $exists = record_exists('tag', 'name', $tag_object->name
);
44 if ( !$exists && is_tag_name_valid($tag_object->name
) ) {
45 if ($can_create_tags) {
46 insert_record('tag', $tag_object);
49 require_capability('moodle/tag:create',$systemcontext);
54 $norm_tag_names_csv = $textlib->substr($norm_tag_names_csv,0,-1);
56 return tags_id( $norm_tag_names_csv );
63 * Ex 1: tag_delete('a very cool tag, another nice tag')
64 * Will delete the tags with names 'a very cool tag' and 'another nice tag' from the 'tags' table, if they exist!
66 * Ex 2: tag_delete('computers, 123, 143, algorithms')
67 * Will delete tags with names 'computers' and 'algorithms' and tags with ids 123 and 143.
70 * @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
73 function tag_delete($tag_names_or_ids_csv) {
75 //covert all names to ids
76 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
79 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
81 // tag instances needs to be deleted as well
82 // delete_records_select('tag_instance',"tagid IN ($tag_ids_csv_with_apos)");
83 // Luiz: (in near future) tag instances should be cascade deleted by RDMS referential integrity constraints, when moodle implements it
84 // For now, tag_instance orphans should be removed using tag_instance_table_cleanup()
86 $return1 = delete_records_select('tag',"name IN ($tag_ids_csv_with_apos)");
87 $return2 = delete_records_select('tag',"id IN ($tag_ids_csv_with_apos)");
89 return $return1 && $return2;
94 * Get all tags from the records
96 * @param string $tag_types_csv (optional, default value is "default". If '*' is passed, tags of any type will be returned).
97 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
98 * @param string $fields a comma separated list of fields to return
99 * (optional, by default 'id, tagtype, name, rawname, flag'). The first field will be used as key for the
100 * array so must be a unique field such as 'id'.
102 function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields=DEFAULT_TAG_TABLE_FIELDS
) {
104 if ($tag_types_csv == '*'){
105 return get_records('tag', '', '', $sort, $fields);
108 $tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
110 return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
114 * Determines if a tag exists
116 * @param string $tag_name_or_id **normalized** tag name, or an id.
117 * @return true if exists or false otherwise
120 function tag_exists($tag_name_or_id) {
122 if (is_numeric($tag_name_or_id)) {
123 return record_exists('tag', 'id', $tag_name_or_id);
126 // normalised tag names are always lowercase only
127 return record_exists('tag', 'name', moodle_strtolower($tag_name_or_id));
132 * Function that returns the id of a tag
134 * @param String $tag_name **normalized** name of the tag
135 * @return int id of the matching tag
137 function tag_id($tag_name) {
138 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
149 * Function that returns the ids of tags
151 * Ex: tags_id('computers, algorithms')
153 * @param String $tag_names_csv comma separated **normalized** tag names.
154 * @return Array array with the tags ids, indexed by their **normalized** names
156 function tags_id($tag_names_csv) {
158 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
159 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
163 if ($tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" )) {
164 foreach ($tag_objects as $tag) {
165 $tags_ids[$tag->name
] = $tag->id
;
173 * Function that returns the name of a tag
175 * @param int $tag_id id of the tag
176 * @return String name of the tag with the id passed
178 function tag_name($tag_id) {
179 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
190 * Function that retrieves the names of tags given their ids
192 * @param String $tag_ids_csv comma separated tag ids
193 * @return Array an array with the tags names, indexed by their ids
196 function tags_name($tag_ids_csv) {
198 //remove any white spaces
199 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
201 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
203 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
205 $tags_names = array();
206 foreach ($tag_objects as $tag) {
207 $tags_names[$tag->id
] = $tag->name
;
214 * Function that returns the name of a tag for display.
216 * @param mixed $tag_object
219 function tag_display_name($tag_object){
223 if( empty($CFG->keeptagnamecase
) ) {
224 //this is the normalized tag name
225 $textlib = textlib_get_instance();
226 return $textlib->strtotitle($tag_object->name
);
229 //original casing of the tag name
230 return $tag_object->rawname
;
236 * Function that retrieves a tag object by its id
238 * @param String $tag_id
239 * @return mixed a fieldset object containing the first matching record, or false if none found
241 function tag_by_id($tag_id) {
243 return get_record('tag','id',$tag_id);
247 * Function that retrieves a tag object by its name
249 * @param String $tag_name
250 * @return mixed a fieldset object containing the first matching record, or false if none found
252 function tag_by_name($tag_name) {
253 $tag = get_record('tag','name',$tag_name);
258 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
261 * Suppose the DB contains only the following entries in the tags table:
267 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
268 * will return '10,12,22,,33,11'
270 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
272 * @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
273 * @return int comma separated ids of the tags
275 function tag_id_from_string($tag_names_or_ids_csv) {
277 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
280 foreach ($tag_names_or_ids as $name_or_id) {
282 if (is_numeric($name_or_id)){
283 $tag_ids[] = trim($name_or_id);
285 elseif (is_string($name_or_id)) {
286 $tag_ids[] = tag_id( $name_or_id );
291 $tag_ids_csv = implode(',',$tag_ids);
292 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
298 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
301 * Suppose the DB contains only the following entries in the tags table:
307 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
308 * will return the string 'mOOdle,moodle,HiStOrY,,education'
310 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
312 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
313 * @return int comma separated names of the tags
315 function tag_name_from_string($tag_names_or_ids_csv) {
317 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
319 $tag_names = array();
320 foreach ($tag_names_or_ids as $name_or_id) {
322 if (is_numeric($name_or_id)){
323 $tag_names[] = tag_name($name_or_id);
325 elseif (is_string($name_or_id)) {
326 $tag_names[] = trim($name_or_id);
331 $tag_names_csv = implode(',',$tag_names);
333 return $tag_names_csv;
339 * Determines if a tag name is valid
341 * @param string $name
344 function is_tag_name_valid($name){
346 $normalized = tag_normalize($name);
348 return !strcmp($normalized, $name) && !empty($name) && !is_numeric($name);
354 * Associates a tag with an item
356 * Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
357 * This will tag an user whose id is 1 with "history", "religions", "roman"
358 * If the tag names passed do not exist, they will get created.
360 * Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
361 * This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
363 * @param string $item_type name of the table where the item is stored. Ex: 'user'
364 * @param string $item_id id of the item to be tagged
365 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
366 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
369 function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
372 //convert any tag ids passed to their corresponding tag names
373 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
376 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
378 //tag instances of an item are ordered, get the last one
381 MAX(ordering) max_order
383 {$CFG->prefix}tag_instance ti
385 ti.itemtype = '{$item_type}'
387 ti.itemid = '{$item_id}'
390 $max_order = get_field_sql($query);
392 $tag_names = explode(',', tag_normalize($tag_names_csv));
395 foreach($tag_names as $tag_name){
396 $ordering[$tag_name] = ++
$max_order;
399 //setup tag_instance object
400 $tag_instance = new StdClass
;
401 $tag_instance->itemtype
= $item_type;
402 $tag_instance->itemid
= $item_id;
405 //create tag instances
406 foreach ($tags_created_ids as $tag_normalized_name => $tag_id) {
408 $tag_instance->tagid
= $tag_id;
409 $tag_instance->ordering
= $ordering[$tag_normalized_name];
410 $tag_instance->timemodified
= time();
411 $tag_instance_exists = get_record('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
413 if (!$tag_instance_exists) {
414 insert_record('tag_instance',$tag_instance);
417 $tag_instance_exists->timemodified
= time();
418 $tag_instance_exists->ordering
= $ordering[$tag_normalized_name];
419 update_record('tag_instance',$tag_instance_exists);
424 // update_tag_correlations($item_type, $item_id);
430 * Updates the tags associated with an item
433 * Suppose user 1 is tagged only with "algorithms", "computers" and "software"
434 * By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
435 * User 1 will now be tagged only with "algorithms", "software" and "mathematics"
438 * update_item_tags('user', '1', 'algorithms, 12, 13')
439 * User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
442 * @param string $item_type name of the table where the item is stored. Ex: 'user'
443 * @param string $item_id id of the item to be tagged
444 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
445 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
448 function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
450 //if $tag_names_csv is an empty string, remove all tag associations of the item
451 if( empty($tag_names_or_ids_csv) ){
452 untag_an_item($item_type, $item_id);
456 //convert any tag ids passed to their corresponding tag names
457 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
459 //associate the tags passed with the item
460 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
462 //get the ids of the tags passed
463 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
465 // delete any tag instance with $item_type and $item_id
466 // that are not in $tag_names_csv
467 $tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
470 itemid = '{$item_id}'
472 itemtype = '{$item_type}'
474 tagid NOT IN ({$tags_id_csv})
477 delete_records_select('tag_instance', $select);
482 * Removes the association of an item with a tag
484 * Ex: untag_an_item('user', '1', 'history, 11, roman' )
485 * The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
486 * Calling untag_an_item('user','1') will remove all tags associated with user 1.
488 * @param string $item_type name of the table where the item is stored. Ex: 'user'
489 * @param string $item_id id of the item to be untagged
490 * @param string $tag_names_or_ids_csv comma separated tag **normalized** names or ids of existing tags (optional, if none is given, all tags of the item will be removed)
493 function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
495 if ($tag_names_or_ids_csv == ""){
497 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
502 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
504 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
506 delete_records_select('tag_instance',
507 "tagid IN ({$tag_ids_csv_with_apos}) AND itemtype='$item_type' AND itemid='$item_id'");
510 //update_tag_correlations($item_type, $item_id);
515 * Function that gets the tags that are associated with an item
517 * Ex: get_item_tags('user', '1')
519 * @param string $item_type name of the table where the item is stored. Ex: 'user'
520 * @param string $item_id id of the item beeing queried
521 * @param string $sort an order to sort the results in, a valid SQL ORDER BY parameter (default is 'ti.ordering ASC')
522 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
523 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
524 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
525 * @return mixed an array of objects, or false if no records were found or an error occured.
528 function get_item_tags($item_type, $item_id, $sort='ti.ordering ASC', $fields=DEFAULT_TAG_TABLE_FIELDS
, $limitfrom='', $limitnum='', $tagtype='') {
532 $fields = 'tg.' . $fields;
533 $fields = str_replace(',', ',tg.', $fields);
536 $sort = ' ORDER BY '. $sort;
540 $tagwhere = " AND tg.tagtype = '$tagtype' ";
549 {$CFG->prefix}tag_instance ti
555 ti.itemtype = '{$item_type}' AND
556 ti.itemid = '{$item_id}'
561 return get_records_sql($query, $limitfrom, $limitnum);
568 * Function that returns the items of a certain type associated with a certain tag
570 * Ex 1: get_items_tagged_with('user', 'banana')
571 * Ex 2: get_items_tagged_with('user', '11')
573 * @param string $item_type name of the table where the item is stored. Ex: 'user'
574 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
575 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
576 * (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
577 * @param string $fields a comma separated list of fields to return
578 * (optional, by default all fields are returned). The first field will be used as key for the
579 * array so must be a unique field such as 'id'. )
580 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
581 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
582 * @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
585 function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
589 $tag_id = tag_id_from_string($tag_name_or_id);
591 $fields = 'it.' . $fields;
592 $fields = str_replace(',', ',it.', $fields);
595 $sort = ' ORDER BY '. $sort;
602 {$CFG->prefix}{$item_type} it
604 {$CFG->prefix}tag_instance tt
608 tt.itemtype = '{$item_type}' AND
609 tt.tagid = '{$tag_id}'
614 return get_records_sql($query, $limitfrom, $limitnum);
619 * Returns the number of items tagged with a tag
621 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
622 * @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
623 * type will be counted)
624 * @return int the count. If an error occurrs, 0 is returned.
626 function count_items_tagged_with($tag_name_or_id, $item_type='') {
630 $tag_id = tag_id_from_string($tag_name_or_id);
632 if (empty($item_type)){
637 {$CFG->prefix}tag_instance tt
647 {$CFG->prefix}{$item_type} it
649 {$CFG->prefix}tag_instance tt
653 tt.itemtype = '{$item_type}' AND
654 tt.tagid = '{$tag_id}' ";
658 return count_records_sql($query);
664 * Determines if an item is tagged with a certain tag
666 * @param string $item_type name of the table where the item is stored. Ex: 'user'
667 * @param string $item_id id of the item beeing queried
668 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
669 * @return bool true if a matching record exists, else false.
671 function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
673 $tag_id = tag_id_from_string($tag_name_or_id);
675 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
679 * Search for tags with names that match some text
681 * @param string $text string that the tag names will be matched against
682 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
683 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
684 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
685 * @return mixed an array of objects, or false if no records were found or an error occured.
688 function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
692 $text = tag_normalize($text);
697 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
701 {$CFG->prefix}tag_instance ti
709 tg.id, tg.name, tg.rawname
716 tg.id, tg.name, tg.rawname
727 return get_records_sql($query, $limitfrom , $limitnum);
732 * Function that returns tags that start with some text
734 * @param string $text string that the tag names will be matched against
735 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
736 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
737 * @return mixed an array of objects, or false if no records were found or an error occured.
739 function similar_tags($text, $limitfrom='' , $limitnum='' ) {
742 $text = moodle_strtolower($text);
744 $query = "SELECT tg.id, tg.name, tg.rawname
745 FROM {$CFG->prefix}tag tg
746 WHERE tg.name LIKE '{$text}%'";
748 return get_records_sql($query, $limitfrom , $limitnum);
752 * Returns tags related to a tag
754 * Related tags of a tag come from two sources:
755 * - manually added related tags, which are tag_instance entries for that tag
756 * - correlated tags, which are a calculated
758 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
759 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
760 * @return array an array of tag objects
763 function related_tags($tag_name_or_id, $limitnum=10) {
765 $tag_id = tag_id_from_string($tag_name_or_id);
767 //gets the manually added related tags
768 if (!$manual_related_tags = get_item_tags('tag', $tag_id, 'ti.ordering ASC', DEFAULT_TAG_TABLE_FIELDS
)) {
769 $manual_related_tags = array();
772 //gets the correlated tags
773 $automatic_related_tags = correlated_tags($tag_id);
775 $related_tags = array_merge($manual_related_tags, $automatic_related_tags);
777 return array_slice(object_array_unique($related_tags), 0 , $limitnum);
781 * Returns the correlated tags of a tag
782 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
784 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
785 * @return array an array of tag objects, or empty array if none
787 function correlated_tags($tag_name_or_id) {
789 $tag_id = tag_id_from_string($tag_name_or_id);
791 if (!$tag_correlation = get_record('tag_correlation', 'tagid', $tag_id)) {
795 if (empty($tag_correlation->correlatedtags
)) {
799 if (!$result = get_records_select('tag', "id IN ({$tag_correlation->correlatedtags})", '', DEFAULT_TAG_TABLE_FIELDS
)) {
807 * Recalculates tag correlations of all the tags associated with an item
808 * This function could be called whenever the tags associations with an item changes
809 * ( for example when tag_an_item() or untag_an_item() is called )
811 * @param string $item_type name of the table where the item is stored. Ex: 'user'
812 * @param string $item_id id of the item
814 function update_tag_correlations($item_type, $item_id) {
816 $item_tags = get_item_tags($item_type, $item_id);
818 foreach ($item_tags as $tag) {
819 cache_correlated_tags($tag->id
);
824 * Calculates and stores the correlated tags of a tag.
825 * The correlations are stored in the 'tag_correlation' table.
827 * Two tags are correlated if they appear together a lot.
828 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
830 * The rationale for the 'tag_correlation' table is performance.
831 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
832 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
834 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
835 * @param number $min_correlation cutoff percentage (optional, default is 0.25)
836 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
838 function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
841 $tag_id = tag_id_from_string($tag_name_or_id);
843 // query that counts how many times any tag appears together in items
844 // with the tag passed as argument ($tag_id)
845 $query = "SELECT tb.tagid , COUNT(*) nr
846 FROM {$CFG->prefix}tag_instance ta
847 INNER JOIN {$CFG->prefix}tag_instance tb ON ta.itemid = tb.itemid
848 WHERE ta.tagid = {$tag_id}
852 $correlated = array();
854 if ($tag_correlations = get_records_sql($query, 0, $limitnum)) {
855 $cutoff = $tag_correlations[$tag_id]->nr
* $min_correlation;
857 foreach($tag_correlations as $correlation) {
858 if($correlation->nr
>= $cutoff && $correlation->tagid
!= $tag_id ){
859 $correlated[] = $correlation->tagid
;
864 $correlated = implode(',', $correlated);
866 //saves correlation info in the caching table
867 if ($tag_correlation_obj = get_record('tag_correlation', 'tagid', $tag_id)) {
868 $tag_correlation_obj->correlatedtags
= $correlated;
869 update_record('tag_correlation', $tag_correlation_obj);
872 $tag_correlation_obj = new object();
873 $tag_correlation_obj->tagid
= $tag_id;
874 $tag_correlation_obj->correlatedtags
= $correlated;
875 insert_record('tag_correlation', $tag_correlation_obj);
880 * This function cleans up the 'tag_instance' table
881 * It removes orphans in 'tag_instances' table
884 function tag_instance_table_cleanup() {
888 //get the itemtypes present in the 'tag_instance' table
893 {$CFG->prefix}tag_instance
896 if ($items_types = get_records_sql($query)) {
898 // for each itemtype, remove tag_instances that are orphans
899 // That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
900 // then this tag_instance is an orphan and it will be removed.
901 foreach ($items_types as $type) {
904 {$CFG->prefix}tag_instance.id
909 FROM {$CFG->prefix}tag_instance sq2
910 LEFT JOIN {$CFG->prefix}{$type->itemtype} item
911 ON sq2.itemid = item.id
912 WHERE item.id IS NULL
913 AND sq2.itemtype = '{$type->itemtype}')
917 delete_records_select('tag_instance', $query);
921 // remove tag_instances that are orphans because tagid does not correspond to an
924 {$CFG->prefix}tag_instance.id
929 FROM {$CFG->prefix}tag_instance sq2
930 LEFT JOIN {$CFG->prefix}tag tg
932 WHERE tg.id IS NULL )
937 delete_records_select('tag_instance', $query);
942 * Function that normalizes a list of tag names
944 * Ex: tag_normalize('bANAana') -> returns 'banana'
945 * tag_normalize('lots of spaces') -> returns 'lots of spaces'
946 * tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
947 * tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
948 * -> returns 'tag one,tag two,tag three,and another tag'
950 * @param string $tag_names_csv unnormalized CSV tag names
951 * @return string **normalized** CSV tag names
954 function tag_normalize($tag_names_csv, $lowercase=true) {
955 $tag_names_csv = clean_param($tag_names_csv, PARAM_TAGLIST
);
958 $tag_names_csv = moodle_strtolower($tag_names_csv);
961 return $tag_names_csv;
964 function tag_flag_inappropriate($tag_names_or_ids_csv){
966 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
968 $tag_ids = explode(',', $tag_ids_csv);
970 foreach ($tag_ids as $id){
971 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
974 $tag->timemodified
= time();
976 update_record('tag', $tag);
980 function tag_flag_reset($tag_names_or_ids_csv){
984 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
986 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
988 $timemodified = time();
995 tg.timemodified = {$timemodified}
999 ({$tag_ids_csv_with_apos})
1002 execute_sql($query, false);
1006 * Function that updates tags names.
1007 * Updates only if the new name suggested for a tag doesn´t exist already.
1009 * @param Array $tags_names_changed array of new tag names indexed by tag ids.
1010 * @return Array array of tags names that were effectively updated, indexed by tag ids.
1012 function tag_update_name($tags_names_changed){
1014 $tags_names_updated = array();
1016 foreach ($tags_names_changed as $id => $newname){
1018 $norm_newname = tag_normalize($newname);
1020 if( !tag_exists($norm_newname) && is_tag_name_valid($norm_newname) ) {
1022 $tag = tag_by_id($id);
1024 $tags_names_updated[$id] = $tag->name
;
1026 // rawname keeps the original casing of the string
1027 $tag->rawname
= tag_normalize($newname, false);
1029 // name lowercases the string
1030 $tag->name
= $norm_newname;
1032 $tag->timemodified
= time();
1034 update_record('tag',$tag);
1039 return $tags_names_updated;
1044 * Function that returns comma separated HTML links to the tag pages of the tags passed
1046 * @param array $tag_objects an array of tag objects
1047 * @return string CSV, HTML links to tag pages
1050 function tag_links_csv($tag_objects) {
1055 if (empty($tag_objects)) {
1059 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1060 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1062 foreach ($tag_objects as $tag){
1063 //highlight tags that have been flagged as inappropriate for those who can manage them
1064 $tagname = tag_display_name($tag);
1065 if ($tag->flag
> 0 && $can_manage_tags) {
1066 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
1068 $tag_links .= ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.$tagname.'</a>,';
1071 return rtrim($tag_links, ',');
1075 * Function that returns comma separated names of the tags passed
1076 * Example of string that might be returned: 'history, wars, greek history'
1078 * @param array $tag_objects
1079 * @return string CSV tag names
1082 function tag_names_csv($tag_objects) {
1084 if (empty($tag_objects)) {
1090 foreach ($tag_objects as $tag){
1091 $tags[] = tag_display_name($tag);
1094 return implode(', ', $tags);
1099 * Returns most popular tags, ordered by their popularity
1101 * @param int $nr_of_tags number of random tags to be returned
1102 * @param unknown_type $tag_type
1103 * @return mixed an array of tag objects with the following fields: id, name and count
1105 function popular_tags_count($nr_of_tags=20, $tag_type = 'default') {
1111 tg.rawname, tg.id, tg.name, COUNT(ti.id) AS count, tg.flag
1113 {$CFG->prefix}tag_instance ti
1115 {$CFG->prefix}tag tg
1119 tg.id, tg.rawname, tg.name
1125 return get_records_sql($query,0,$nr_of_tags);
1130 function tag_cron(){
1132 tag_instance_table_cleanup();
1134 if ($tags = get_all_tags('*')) {
1136 foreach ($tags as $tag){
1137 cache_correlated_tags($tag->id
);
1142 /*-------------------- Printing functions -------------------- */
1145 * Prints a box that contains the management links of a tag
1147 * @param $tag_object
1148 * @param $return if true return html string
1151 function print_tag_management_box($tag_object, $return=false) {
1155 $tagname = tag_display_name($tag_object);
1159 if (!isguestuser()) {
1161 $output .= print_box_start('box','tag-management-box', true);
1163 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1167 // if the user is not tagged with the $tag_object tag, a link "add blahblah to my interests" will appear
1168 if( !is_item_tagged_with('user', $USER->id
, $tag_object->id
)) {
1169 $links[] = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&sesskey='.sesskey().'&id='. $tag_object->id
.'">'.get_string('addtagtomyinterests','tag',$tagname). '</a>';
1172 // only people with moodle/tag:edit capability may edit the tag description
1173 if ( has_capability('moodle/tag:edit',$systemcontext) && is_item_tagged_with('user', $USER->id
, $tag_object->id
) ) {
1174 $links[] = '<a href="'. $CFG->wwwroot
. '/tag/edit.php?id='.$tag_object->id
.'">'.get_string('edittag', 'tag').'</a>';
1177 // flag as inappropriate link
1178 $links[] = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=flaginappropriate&sesskey='.sesskey().'&id='. $tag_object->id
.'">' . get_string('flagasinappropriate','tag',$tagname). '</a>';
1180 // Manage all tags links
1181 if ( has_capability('moodle/tag:manage',$systemcontext) ) {
1182 $links[] = '<a href="'.$CFG->wwwroot
.'/tag/manage.php">' . get_string('managetags', 'tag') . '</a>' ;
1185 $output .= implode(' | ', $links);
1187 $output .= print_box_end(true);
1200 * Prints a box with the description of a tag and its related tags
1202 * @param unknown_type $tag_object
1203 * @param $return if true return html string
1206 function print_tag_description_box($tag_object, $return=false) {
1210 $tagname = tag_display_name($tag_object);
1211 $related_tags = related_tags($tag_object->id
);
1213 $content = !empty($tag_object->description
) ||
$related_tags;
1218 $output .= print_box_start('generalbox', 'tag-description',true);
1221 if (!empty($tag_object->description
)) {
1222 $options = new object();
1223 $options->para
= false;
1224 $output .= format_text($tag_object->description
, $tag_object->descriptionformat
, $options);
1227 if ($related_tags) {
1228 $output .= '<br /><br /><strong>'.get_string('relatedtags','tag').': </strong>' . tag_links_csv($related_tags);
1232 $output .= print_box_end(true);
1243 * Prints a table of the users tagged with the tag passed as argument
1245 * @param $tag_object
1246 * @param int $users_per_row number of users per row to display
1247 * @param int $limitfrom prints users starting at this point (optional, required if $limitnum is set).
1248 * @param int $limitnum prints this many users (optional, required if $limitfrom is set).
1249 * @param $return if true return html string
1252 function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='', $return=false) {
1254 //List of users with this tag
1255 $userlist = array_values( get_items_tagged_with(
1259 'id, firstname, lastname, picture',
1263 $output = print_user_list($userlist, true);
1275 * Prints a list of users
1276 * @param array $userlist an array of user objects
1277 * @param $return if true return html string
1279 function print_user_list($userlist, $return=false) {
1283 foreach ($userlist as $user){
1284 $output .= print_user_box( $user , true);
1297 * Prints an individual user box
1299 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
1300 * @param $return if true return html string
1302 function print_user_box($user, $return=false) {
1305 $textlib = textlib_get_instance();
1307 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
1310 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1311 $profilelink = $CFG->wwwroot
.'/user/view.php?id='.$user->id
;
1316 $output .= print_box_start('user-box', 'user'.$user->id
, true);
1318 if (!empty($profilelink)) {
1319 $output .= '<a href="'.$profilelink.'">';
1323 if ($user->picture
) {
1324 $output .= '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/user/pix.php/'. $user->id
.'/f1.jpg"'.'/>';
1326 $output .= '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/pix/u/f1.png"'.'/>';
1329 $output .= '<br />';
1331 if (!empty($profilelink)) {
1335 $fullname = fullname($user);
1336 //truncate name if it's too big
1337 if ($textlib->strlen($fullname) > 26) $fullname = $textlib->substr($fullname,0,26) . '...';
1339 $output .= '<strong>' . $fullname . '</strong>';
1341 $output .= print_box_end(true);
1353 * Prints the tag search box
1354 * @param $return if true return html string
1357 function print_tag_search_box($return=false) {
1362 $output .= print_box_start('','tag-search-box', true);
1364 $output .= '<form action="'.$CFG->wwwroot
.'/tag/search.php" style="display:inline">';
1366 $output .= '<input id="searchform_search" name="query" type="text" size="40" />';
1367 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
1368 $output .= '</div>';
1369 $output .= '</form>';
1371 $output .= print_box_end(true);
1382 * Prints the tag search results
1384 * @param string $query text that tag names will be matched against
1385 * @param int $page current page
1386 * @param int $perpage nr of users displayed per page
1387 * @param $return if true return html string
1389 function print_tag_search_results($query, $page, $perpage, $return=false) {
1393 $count = sizeof( search_tags($query,false) );
1394 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
1396 $baseurl = $CFG->wwwroot
.'/tag/search.php?query=' . $query;
1400 // link "Add $query to my interests"
1402 if( !is_item_tagged_with('user', $USER->id
, $query )) {
1403 $addtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&sesskey='.sesskey().'&name='. $query .'">';
1404 $addtaglink .= get_string('addtagtomyinterests','tag',$query). '</a>';
1408 if($tags) { // there are results to display!!
1410 $output .= print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3, 'main' ,true);
1412 //print a link "Add $query to my interests"
1413 if (!empty($addtaglink)) {
1414 $output .= print_box($addtaglink,'box','tag-management-box',true);
1417 $nr_of_lis_per_ul = 6;
1418 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
1420 $output .= '<ul id="tag-search-results">';
1421 for($i = 0; $i < $nr_of_uls; $i++
) {
1423 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul ) as $tag) {
1424 $tag_link = ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.tag_display_name($tag).'</a>';
1425 $output .= '•' . $tag_link . '<br/>';
1430 $output .= '<div> </div>'; // <-- small layout hack in order to look good in Firefox
1432 $output .= print_paging_bar($count, $page, $perpage, $baseurl.'&', 'page', false, true);
1434 else { //no results were found!!
1436 $output .= print_heading(get_string('noresultsfor', 'tag', $query), '', 3, 'main' , true);
1438 //print a link "Add $query to my interests"
1439 if (!empty($addtaglink)) {
1440 $output .= print_box($addtaglink,'box','tag-management-box', true);
1456 * Prints a tag cloud
1458 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
1459 * @param boolean $shuffle wether or not to shuffle the array passed
1460 * @param int $max_size maximum text size, in percentage
1461 * @param int $min_size minimum text size, in percentage
1462 * @param $return if true return html string
1464 function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80, $return=false) {
1468 if (empty($tagcloud)) {
1479 foreach ($tagcloud as $key => $value){
1480 if(!empty($value->count
)) {
1481 $count[$key] = log10($value->count
);
1491 $spread = $max - $min;
1492 if (0 == $spread) { // we don't want to divide by zero
1496 $step = ($max_size - $min_size)/($spread);
1498 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1499 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1501 //prints the tag cloud
1502 $output = '<ul id="tag-cloud-list">';
1503 foreach ($tagcloud as $key => $tag) {
1505 $size = $min_size +
((log10($tag->count
) - $min) * $step);
1506 $size = ceil($size);
1508 $style = 'style="font-size: '.$size.'%"';
1509 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
1510 $href = 'href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'"';
1512 //highlight tags that have been flagged as inappropriate for those who can manage them
1513 $tagname = tag_display_name($tag);
1514 if ($tag->flag
> 0 && $can_manage_tags) {
1515 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
1518 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
1520 $output .= $tag_link;