3 require_once($CFG->libdir
.'/textlib.class.php');
5 define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
6 define('MAX_TAG_LENGTH',50);
11 * Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
12 * will create the following normalized {@link tag_normalize()} entries in tags table:
16 * @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
17 * @param string $tag_type type of tag to be created ("default" is the default value).
18 * @return an array of tags ids, indexed by their normalized names
20 function tag_create($tag_names_csv, $tag_type="default") {
22 $textlib = textlib_get_instance();
24 $tags = explode(",", $tag_names_csv );
26 $tag_object = new StdClass
;
27 $tag_object->tagtype
= $tag_type;
28 $tag_object->userid
= $USER->id
;
30 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
31 $can_create_tags = has_capability('moodle/tag:create',$systemcontext);
33 $norm_tag_names_csv = '';
34 foreach ($tags as $tag) {
36 // rawname keeps the original casing of the string
37 $tag_object->rawname
= tag_normalize($tag, false);
39 // name lowercases the string
40 $tag_object->name
= tag_normalize($tag);
41 $norm_tag_names_csv .= $tag_object->name
. ',';
43 $tag_object->timemodified
= time();
45 $exists = record_exists('tag', 'name', $tag_object->name
);
47 if ( !$exists && is_tag_name_valid($tag_object->name
) ) {
48 if ($can_create_tags) {
49 insert_record('tag', $tag_object);
52 require_capability('moodle/tag:create',$systemcontext);
57 $norm_tag_names_csv = $textlib->substr($norm_tag_names_csv,0,-1);
59 return tags_id( $norm_tag_names_csv );
66 * Ex 1: tag_delete('a very cool tag, another nice tag')
67 * Will delete the tags with names 'a very cool tag' and 'another nice tag' from the 'tags' table, if they exist!
69 * Ex 2: tag_delete('computers, 123, 143, algorithms')
70 * Will delete tags with names 'computers' and 'algorithms' and tags with ids 123 and 143.
73 * @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
76 function tag_delete($tag_names_or_ids_csv) {
78 //covert all names to ids
79 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
82 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
84 // tag instances needs to be deleted as well
85 // delete_records_select('tag_instance',"tagid IN ($tag_ids_csv_with_apos)");
86 // Luiz: (in near future) tag instances should be cascade deleted by RDMS referential integrity constraints, when moodle implements it
87 // For now, tag_instance orphans should be removed using tag_instance_table_cleanup()
89 return delete_records_select('tag',"name IN ($tag_ids_csv_with_apos)");
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);
125 elseif (is_string($tag_name_or_id)) {
126 return record_exists('tag', 'name', $tag_name_or_id);
131 * Function that returns the id of a tag
133 * @param String $tag_name **normalized** name of the tag
134 * @return int id of the matching tag
136 function tag_id($tag_name) {
137 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
148 * Function that returns the ids of tags
150 * Ex: tags_id('computers, algorithms')
152 * @param String $tag_names_csv comma separated **normalized** tag names.
153 * @return Array array with the tags ids, indexed by their **normalized** names
155 function tags_id($tag_names_csv) {
157 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
158 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
160 $tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" );
163 foreach ($tag_objects as $tag) {
164 $tags_ids[$tag->name
] = $tag->id
;
171 * Function that returns the name of a tag
173 * @param int $tag_id id of the tag
174 * @return String name of the tag with the id passed
176 function tag_name($tag_id) {
177 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
188 * Function that retrieves the names of tags given their ids
190 * @param String $tag_ids_csv comma separated tag ids
191 * @return Array an array with the tags names, indexed by their ids
194 function tags_name($tag_ids_csv) {
196 //remove any white spaces
197 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
199 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
201 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
203 $tags_names = array();
204 foreach ($tag_objects as $tag) {
205 $tags_names[$tag->id
] = $tag->name
;
212 * Function that returns the name of a tag for display.
214 * @param mixed $tag_object
217 function tag_display_name($tag_object){
221 if( empty($CFG->keeptagnamecase
) ) {
222 //this is the normalized tag name
223 return mb_convert_case($tag_object->name
, MB_CASE_TITLE
,"UTF-8");
226 //original casing of the tag name
227 return $tag_object->rawname
;
233 * Function that retrieves a tag object by its id
235 * @param String $tag_id
236 * @return mixed a fieldset object containing the first matching record, or false if none found
238 function tag_by_id($tag_id) {
240 return get_record('tag','id',$tag_id);
244 * Function that retrieves a tag object by its name
246 * @param String $tag_name
247 * @return mixed a fieldset object containing the first matching record, or false if none found
249 function tag_by_name($tag_name) {
250 $tag = get_record('tag','name',$tag_name);
255 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
258 * Suppose the DB contains only the following entries in the tags table:
264 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
265 * will return '10,12,22,,33,11'
267 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
269 * @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
270 * @return int comma separated ids of the tags
272 function tag_id_from_string($tag_names_or_ids_csv) {
274 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
277 foreach ($tag_names_or_ids as $name_or_id) {
279 if (is_numeric($name_or_id)){
280 $tag_ids[] = trim($name_or_id);
282 elseif (is_string($name_or_id)) {
283 $tag_ids[] = tag_id( $name_or_id );
288 $tag_ids_csv = implode(',',$tag_ids);
289 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
295 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
298 * Suppose the DB contains only the following entries in the tags table:
304 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
305 * will return the string 'mOOdle,moodle,HiStOrY,,education'
307 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
309 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
310 * @return int comma separated names of the tags
312 function tag_name_from_string($tag_names_or_ids_csv) {
314 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
316 $tag_names = array();
317 foreach ($tag_names_or_ids as $name_or_id) {
319 if (is_numeric($name_or_id)){
320 $tag_names[] = tag_name($name_or_id);
322 elseif (is_string($name_or_id)) {
323 $tag_names[] = trim($name_or_id);
328 $tag_names_csv = implode(',',$tag_names);
330 return $tag_names_csv;
336 * Determines if a tag name is valid
338 * @param string $name
341 function is_tag_name_valid($name){
343 $normalized = tag_normalize($name);
345 return !strcmp($normalized, $name) && !empty($name) && !is_numeric($name);
351 * Associates a tag with an item
353 * Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
354 * This will tag an user whose id is 1 with "history", "religions", "roman"
355 * If the tag names passed do not exist, they will get created.
357 * Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
358 * This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
360 * @param string $item_type name of the table where the item is stored. Ex: 'user'
361 * @param string $item_id id of the item to be tagged
362 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
363 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
366 function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
369 //convert any tag ids passed to their corresponding tag names
370 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
373 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
375 //tag instances of an item are ordered, get the last one
378 MAX(ordering) max_order
380 {$CFG->prefix}tag_instance ti
382 ti.itemtype = '{$item_type}'
384 ti.itemid = '{$item_id}'
387 $max_order = get_field_sql($query);
389 $tag_names = explode(',', tag_normalize($tag_names_csv));
392 foreach($tag_names as $tag_name){
393 $ordering[$tag_name] = ++
$max_order;
396 //setup tag_instance object
397 $tag_instance = new StdClass
;
398 $tag_instance->itemtype
= $item_type;
399 $tag_instance->itemid
= $item_id;
402 //create tag instances
403 foreach ($tags_created_ids as $tag_normalized_name => $tag_id) {
405 $tag_instance->tagid
= $tag_id;
406 $tag_instance->ordering
= $ordering[$tag_normalized_name];
407 $tag_instance->timemodified
= time();
408 $tag_instance_exists = get_record('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
410 if (!$tag_instance_exists) {
411 insert_record('tag_instance',$tag_instance);
414 $tag_instance_exists->timemodified
= time();
415 $tag_instance_exists->ordering
= $ordering[$tag_normalized_name];
416 update_record('tag_instance',$tag_instance_exists);
421 // update_tag_correlations($item_type, $item_id);
427 * Updates the tags associated with an item
430 * Suppose user 1 is tagged only with "algorithms", "computers" and "software"
431 * By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
432 * User 1 will now be tagged only with "algorithms", "software" and "mathematics"
435 * update_item_tags('user', '1', 'algorithms, 12, 13')
436 * User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
439 * @param string $item_type name of the table where the item is stored. Ex: 'user'
440 * @param string $item_id id of the item to be tagged
441 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
442 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
445 function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
447 //if $tag_names_csv is an empty string, remove all tag associations of the item
448 if( empty($tag_names_or_ids_csv) ){
449 untag_an_item($item_type, $item_id);
453 //convert any tag ids passed to their corresponding tag names
454 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
456 //associate the tags passed with the item
457 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
459 //get the ids of the tags passed
460 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
462 // delete any tag instance with $item_type and $item_id
463 // that are not in $tag_names_csv
464 $tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
467 itemid = '{$item_id}'
469 itemtype = '{$item_type}'
471 tagid NOT IN ({$tags_id_csv})
474 delete_records_select('tag_instance', $select);
479 * Removes the association of an item with a tag
481 * Ex: untag_an_item('user', '1', 'history, 11, roman' )
482 * The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
483 * Calling untag_an_item('user','1') will remove all tags associated with user 1.
485 * @param string $item_type name of the table where the item is stored. Ex: 'user'
486 * @param string $item_id id of the item to be untagged
487 * @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)
490 function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
492 if ($tag_names_or_ids_csv == ""){
494 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
499 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
501 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
503 delete_records_select('tag_instance',
504 "tagid IN ({$tag_ids_csv_with_apos}) AND itemtype='$item_type' AND itemid='$item_id'");
507 //update_tag_correlations($item_type, $item_id);
512 * Function that gets the tags that are associated with an item
514 * Ex: get_item_tags('user', '1')
516 * @param string $item_type name of the table where the item is stored. Ex: 'user'
517 * @param string $item_id id of the item beeing queried
518 * @param string $sort an order to sort the results in, a valid SQL ORDER BY parameter (default is 'ti.ordering ASC')
519 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
520 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
521 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
522 * @return mixed an array of objects, or false if no records were found or an error occured.
525 function get_item_tags($item_type, $item_id, $sort='ti.ordering ASC', $fields=DEFAULT_TAG_TABLE_FIELDS
, $limitfrom='', $limitnum='', $tagtype='') {
529 $fields = 'tg.' . $fields;
530 $fields = str_replace(',', ',tg.', $fields);
533 $sort = ' ORDER BY '. $sort;
537 $tagwhere = " AND tg.tagtype = '$tagtype' ";
546 {$CFG->prefix}tag_instance ti
552 ti.itemtype = '{$item_type}' AND
553 ti.itemid = '{$item_id}'
558 return get_records_sql($query, $limitfrom, $limitnum);
565 * Function that returns the items of a certain type associated with a certain tag
567 * Ex 1: get_items_tagged_with('user', 'banana')
568 * Ex 2: get_items_tagged_with('user', '11')
570 * @param string $item_type name of the table where the item is stored. Ex: 'user'
571 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
572 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
573 * (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
574 * @param string $fields a comma separated list of fields to return
575 * (optional, by default all fields are returned). The first field will be used as key for the
576 * array so must be a unique field such as 'id'. )
577 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
578 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
579 * @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
582 function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
586 $tag_id = tag_id_from_string($tag_name_or_id);
588 $fields = 'it.' . $fields;
589 $fields = str_replace(',', ',it.', $fields);
592 $sort = ' ORDER BY '. $sort;
599 {$CFG->prefix}{$item_type} it
601 {$CFG->prefix}tag_instance tt
605 tt.itemtype = '{$item_type}' AND
606 tt.tagid = '{$tag_id}'
611 return get_records_sql($query, $limitfrom, $limitnum);
616 * Returns the number of items tagged with a tag
618 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
619 * @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
620 * type will be counted)
621 * @return int the count. If an error occurrs, 0 is returned.
623 function count_items_tagged_with($tag_name_or_id, $item_type='') {
627 $tag_id = tag_id_from_string($tag_name_or_id);
629 if (empty($item_type)){
634 {$CFG->prefix}tag_instance tt
644 {$CFG->prefix}{$item_type} it
646 {$CFG->prefix}tag_instance tt
650 tt.itemtype = '{$item_type}' AND
651 tt.tagid = '{$tag_id}' ";
655 return count_records_sql($query);
661 * Determines if an item is tagged with a certain tag
663 * @param string $item_type name of the table where the item is stored. Ex: 'user'
664 * @param string $item_id id of the item beeing queried
665 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
666 * @return bool true if a matching record exists, else false.
668 function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
670 $tag_id = tag_id_from_string($tag_name_or_id);
672 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
676 * Search for tags with names that match some text
678 * @param string $text string that the tag names will be matched against
679 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
680 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
681 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
682 * @return mixed an array of objects, or false if no records were found or an error occured.
685 function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
689 $text = tag_normalize($text);
694 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
698 {$CFG->prefix}tag_instance ti
713 tg.id, tg.name, tg.rawname
724 return get_records_sql($query, $limitfrom , $limitnum);
729 * Function that returns tags that start with some text
731 * @param string $text string that the tag names will be matched against
732 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
733 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
734 * @return mixed an array of objects, or false if no records were found or an error occured.
736 function similar_tags($text, $limitfrom='' , $limitnum='' ) {
740 $text = tag_normalize($text);
744 tg.id, tg.name, tg.rawname
753 return get_records_sql($query, $limitfrom , $limitnum);
757 * Returns tags related to a tag
759 * Related tags of a tag come from two sources:
760 * - manually added related tags, which are tag_instance entries for that tag
761 * - correlated tags, which are a calculated
763 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
764 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
765 * @return mixed an array of tag objects
768 function related_tags($tag_name_or_id, $limitnum=10) {
770 $tag_id = tag_id_from_string($tag_name_or_id);
772 //gets the manually added related tags
773 $manual_related_tags = get_item_tags('tag',$tag_id, 'ti.ordering ASC',DEFAULT_TAG_TABLE_FIELDS
);
774 if ($manual_related_tags == false) $manual_related_tags = array();
776 //gets the correlated tags
777 $automatic_related_tags = correlated_tags($tag_id);
778 if ($automatic_related_tags == false) $automatic_related_tags = array();
780 $related_tags = array_merge($manual_related_tags,$automatic_related_tags);
782 return array_slice( object_array_unique($related_tags) , 0 , $limitnum );
788 * Returns the correlated tags of a tag
789 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
791 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
792 * @return mixed an array of tag objects
794 function correlated_tags($tag_name_or_id) {
796 $tag_id = tag_id_from_string($tag_name_or_id);
798 if (!$tag_correlation = get_record('tag_correlation','tagid',$tag_id)) {
802 $tags_id_csv_with_apos = stripcslashes($tag_correlation->correlatedtags
);
804 return get_records_select('tag', "id IN ({$tags_id_csv_with_apos})", '', DEFAULT_TAG_TABLE_FIELDS
);
808 * Recalculates tag correlations of all the tags associated with an item
809 * This function could be called whenever the tags associations with an item changes
810 * ( for example when tag_an_item() or untag_an_item() is called )
812 * @param string $item_type name of the table where the item is stored. Ex: 'user'
813 * @param string $item_id id of the item
815 function update_tag_correlations($item_type, $item_id) {
817 $item_tags = get_item_tags($item_type, $item_id);
819 foreach ($item_tags as $tag) {
820 cache_correlated_tags($tag->id
);
825 * Calculates and stores the correlated tags of a tag.
826 * The correlations are stored in the 'tag_correlation' table.
828 * Two tags are correlated if they appear together a lot.
829 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
831 * The rationale for the 'tag_correlation' table is performance.
832 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
833 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
835 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
836 * @param number $min_correlation cutoff percentage (optional, default is 0.25)
837 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
839 function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
842 $textlib = textlib_get_instance();
844 $tag_id = tag_id_from_string($tag_name_or_id);
846 // query that counts how many times any tag appears together in items
847 // with the tag passed as argument ($tag_id)
850 tb.tagid , COUNT(*) nr
852 {$CFG->prefix}tag_instance ta
854 {$CFG->prefix}tag_instance tb
856 ta.itemid = tb.itemid
864 $tag_correlations = get_records_sql($query, 0, $limitnum);
866 $tags_id_csv_with_apos = "'";
867 $cutoff = $tag_correlations[$tag_id]->nr
* $min_correlation;
869 foreach($tag_correlations as $correlation) {
870 if($correlation->nr
>= $cutoff && $correlation->tagid
!= $tag_id ){
871 $tags_id_csv_with_apos .= $correlation->tagid
."','";
874 $tags_id_csv_with_apos = $textlib->substr($tags_id_csv_with_apos,0,-2);
877 //saves correlation info in the caching table
879 $tag_correlation_obj = get_record('tag_correlation','tagid',$tag_id);
881 if ($tag_correlation_obj) {
882 $tag_correlation_obj->correlatedtags
= addslashes($tags_id_csv_with_apos);
883 update_record('tag_correlation',$tag_correlation_obj);
886 $tag_correlation_obj = new StdClass
;
887 $tag_correlation_obj->tagid
= $tag_id;
888 $tag_correlation_obj->correlatedtags
= addslashes($tags_id_csv_with_apos);
889 insert_record('tag_correlation',$tag_correlation_obj);
896 * This function cleans up the 'tag_instance' table
897 * It removes orphans in 'tag_instances' table
900 function tag_instance_table_cleanup() {
904 //get the itemtypes present in the 'tag_instance' table
909 {$CFG->prefix}tag_instance
912 $items_types = get_records_sql($query);
914 // for each itemtype, remove tag_instances that are orphans
915 // That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
916 // then this tag_instance is an orphan and it will be removed.
917 foreach ($items_types as $type) {
920 {$CFG->prefix}tag_instance.id
925 FROM {$CFG->prefix}tag_instance sq2
926 LEFT JOIN {$CFG->prefix}{$type->itemtype} item
927 ON sq2.itemid = item.id
928 WHERE item.id IS NULL
929 AND sq2.itemtype = '{$type->itemtype}')
933 delete_records_select('tag_instance', $query);
936 // remove tag_instances that are orphans because tagid does not correspond to an
939 {$CFG->prefix}tag_instance.id
944 FROM {$CFG->prefix}tag_instance sq2
945 LEFT JOIN {$CFG->prefix}tag tg
947 WHERE tg.id IS NULL )
952 delete_records_select('tag_instance', $query);
957 * Function that normalizes a tag name
959 * Ex: tag_normalize('bANAana') -> returns 'banana'
960 * tag_normalize('lots of spaces') -> returns 'lots of spaces'
961 * tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
962 * tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
963 * -> returns 'tag one,tag two,tag three,and another tag'
965 * @param string $tag_names_csv unnormalized CSV tag names
966 * @return string **normalized** CSV tag names
969 function tag_normalize($tag_names_csv, $lowercase=true) {
971 $textlib = textlib_get_instance();
973 $tags = explode(',', $tag_names_csv);
975 if (sizeof($tags) > 1) {
977 foreach ($tags as $key => $tag) {
978 $tags[$key] = tag_normalize($tag);
981 return implode(',' , $tags);
985 // only one tag was passed
989 $value = moodle_strtolower($tag_names_csv);
992 $value = $tag_names_csv;
995 //$value = preg_replace('|[^\w ]|i', '', strtolower(trim($tag_names_csv)));
996 $value = preg_replace('|[\,\!\@\#\$\%\^\&\*\(\)\-\+\=\~\`\\"\'\_.\[\]\{\}\:\;\?\´\^\\\/\<\>\|]|i', '', trim($value));
998 //removes excess white spaces
999 $value = preg_replace('/\s\s+/', ' ', $value);
1001 return $textlib->substr($value,0,MAX_TAG_LENGTH
);
1006 function tag_flag_inappropriate($tag_names_or_ids_csv){
1008 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
1010 $tag_ids = explode(',', $tag_ids_csv);
1012 foreach ($tag_ids as $id){
1013 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
1016 $tag->timemodified
= time();
1018 update_record('tag', $tag);
1022 function tag_flag_reset($tag_names_or_ids_csv){
1026 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
1028 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
1030 $timemodified = time();
1034 {$CFG->prefix}tag tg
1037 tg.timemodified = {$timemodified}
1041 ({$tag_ids_csv_with_apos})
1044 execute_sql($query, false);
1048 * Function that updates tags names.
1049 * Updates only if the new name suggested for a tag doesn´t exist already.
1051 * @param Array $tags_names_changed array of new tag names indexed by tag ids.
1052 * @return Array array of tags names that were effectively updated, indexed by tag ids.
1054 function tag_update_name($tags_names_changed){
1056 $tags_names_updated = array();
1058 foreach ($tags_names_changed as $id => $newname){
1060 $norm_newname = tag_normalize($newname);
1062 if( !tag_exists($norm_newname) && is_tag_name_valid($norm_newname) ) {
1064 $tag = tag_by_id($id);
1066 $tags_names_updated[$id] = $tag->name
;
1068 // rawname keeps the original casing of the string
1069 $tag->rawname
= tag_normalize($newname, false);
1071 // name lowercases the string
1072 $tag->name
= $norm_newname;
1074 $tag->timemodified
= time();
1076 update_record('tag',$tag);
1081 return $tags_names_updated;
1086 * Function that returns comma separated HTML links to the tag pages of the tags passed
1088 * @param array $tag_objects an array of tag objects
1089 * @return string CSV, HTML links to tag pages
1092 function tag_links_csv($tag_objects) {
1097 if (empty($tag_objects)) {
1101 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1102 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1104 foreach ($tag_objects as $tag){
1105 //highlight tags that have been flagged as inappropriate for those who can manage them
1106 $tagname = tag_display_name($tag);
1107 if ($tag->flag
> 0 && $can_manage_tags) {
1108 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
1110 $tag_links .= ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.$tagname.'</a>,';
1113 return rtrim($tag_links, ',');
1117 * Function that returns comma separated names of the tags passed
1118 * Example of string that might be returned: 'history, wars, greek history'
1120 * @param array $tag_objects
1121 * @return string CSV tag names
1124 function tag_names_csv($tag_objects) {
1126 if (empty($tag_objects)) {
1132 foreach ($tag_objects as $tag){
1133 $tags[] = tag_display_name($tag);
1136 return implode(', ', $tags);
1141 * Returns most popular tags, ordered by their popularity
1143 * @param int $nr_of_tags number of random tags to be returned
1144 * @param unknown_type $tag_type
1145 * @return mixed an array of tag objects with the following fields: id, name and count
1147 function popular_tags_count($nr_of_tags=20, $tag_type = 'default') {
1153 tg.rawname, tg.id, tg.name, COUNT(ti.id) AS count, tg.flag
1155 {$CFG->prefix}tag_instance ti
1157 {$CFG->prefix}tag tg
1169 return get_records_sql($query,0,$nr_of_tags);
1174 function tag_cron(){
1176 tag_instance_table_cleanup();
1178 $tags = get_all_tags('*');
1180 foreach ($tags as $tag){
1181 cache_correlated_tags($tag->id
);
1185 /*-------------------- Printing functions -------------------- */
1188 * Prints a box that contains the management links of a tag
1190 * @param $tag_object
1191 * @param $return if true return html string
1194 function print_tag_management_box($tag_object, $return=false) {
1198 $tagname = tag_display_name($tag_object);
1202 $output .= print_box_start('box','tag-management-box', true);
1204 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1207 if ( has_capability('moodle/tag:manage',$systemcontext) ) {
1208 $manage_link = "<a href=\"{$CFG->wwwroot}/tag/manage.php\">" . get_string('managetags', 'tag') . "</a>" ;
1209 $output .= $manage_link .' | ';
1212 // if the user is not tagged with the $tag_object tag, a link "add blahblah to my interests" will appear
1213 if( !is_item_tagged_with('user', $USER->id
, $tag_object->id
)) {
1214 $addtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&id='. $tag_object->id
.'">';
1215 $addtaglink .= get_string('addtagtomyinterests','tag',$tagname). '</a>';
1216 $output .= $addtaglink .' | ';
1219 // only people with moodle/tag:edit capability may edit the tag description
1220 if ( has_capability('moodle/tag:edit',$systemcontext) && is_item_tagged_with('user', $USER->id
, $tag_object->id
) ) {
1221 $output .= ' <a href="'. $CFG->wwwroot
. '/tag/edit.php?id='.$tag_object->id
.'">'.get_string('edittag', 'tag').'</a> | ';
1224 // flag as inappropriate link
1225 $flagtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=flaginappropriate&id='. $tag_object->id
.'">';
1226 $flagtaglink .= get_string('flagasinappropriate','tag',$tagname). '</a>';
1227 $output .= $flagtaglink;
1229 $output .= print_box_end(true);
1242 * Prints a box with the description of a tag and its related tags
1244 * @param unknown_type $tag_object
1245 * @param $return if true return html string
1248 function print_tag_description_box($tag_object, $return=false) {
1252 $tagname = tag_display_name($tag_object);
1253 $related_tags = related_tags($tag_object->id
);
1255 $content = !empty($tag_object->description
) ||
$related_tags;
1260 $output .= print_box_start('generalbox', 'tag-description',true);
1263 if (!empty($tag_object->description
)) {
1264 $options = new object;
1265 $options->para
=false;
1266 $output .= format_text($tag_object->description
, $tag_object->descriptionformat
, $options );
1269 if ($related_tags) {
1270 $output .= '<br/><br/><b>'.get_string('relatedtags','tag').': </b>' . tag_links_csv($related_tags);
1274 $output .= print_box_end(true);
1285 * Prints a table of the users tagged with the tag passed as argument
1287 * @param $tag_object
1288 * @param int $users_per_row number of users per row to display
1289 * @param int $limitfrom prints users starting at this point (optional, required if $limitnum is set).
1290 * @param int $limitnum prints this many users (optional, required if $limitfrom is set).
1291 * @param $return if true return html string
1294 function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='', $return=false) {
1296 //List of users with this tag
1297 $userlist = array_values( get_items_tagged_with(
1301 'id, firstname, lastname, picture',
1305 $output = print_user_list($userlist, true);
1317 * Prints a list of users
1318 * @param array $userlist an array of user objects
1319 * @param $return if true return html string
1321 function print_user_list($userlist, $return=false) {
1325 foreach ($userlist as $user){
1326 $output .= print_user_box( $user , true);
1339 * Prints an individual user box
1341 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
1342 * @param $return if true return html string
1344 function print_user_box($user, $return=false) {
1347 $textlib = textlib_get_instance();
1349 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
1352 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1353 $profilelink = $CFG->wwwroot
.'/user/view.php?id='.$user->id
;
1358 $output .= print_box_start('user-box', 'user'.$user->id
, true);
1360 if (!empty($profilelink)) {
1361 $output .= '<a href="'.$profilelink.'">';
1365 if ($user->picture
) {
1366 $output .= '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/user/pix.php/'. $user->id
.'/f1.jpg"'.'/>';
1368 $output .= '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/pix/u/f1.png"'.'/>';
1371 $output .= '<br />';
1373 if (!empty($profilelink)) {
1377 $fullname = fullname($user);
1378 //truncate name if it's too big
1379 if ($textlib->strlen($fullname) > 26) $fullname = $textlib->substr($fullname,0,26) . '...';
1381 $output .= '<strong>' . $fullname . '</strong>';
1383 $output .= print_box_end(true);
1395 * Prints the tag search box
1396 * @param $return if true return html string
1399 function print_tag_search_box($return=false) {
1404 $output .= print_box_start('','tag-search-box', true);
1406 $output .= '<form action="'.$CFG->wwwroot
.'/tag/search.php" style="display:inline">';
1408 $output .= '<input id="searchform_search" name="query" type="text" size="40" />';
1409 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
1410 $output .= '</div>';
1411 $output .= '</form>';
1413 $output .= print_box_end(true);
1424 * Prints the tag search results
1426 * @param string $query text that tag names will be matched against
1427 * @param int $page current page
1428 * @param int $perpage nr of users displayed per page
1429 * @param $return if true return html string
1431 function print_tag_search_results($query, $page, $perpage, $return=false) {
1435 $count = sizeof( search_tags($query,false) );
1436 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
1438 $baseurl = $CFG->wwwroot
.'/tag/search.php?query=' . $query;
1442 // link "Add $query to my interests"
1444 if( !is_item_tagged_with('user', $USER->id
, $query )) {
1445 $addtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&name='. $query .'">';
1446 $addtaglink .= get_string('addtagtomyinterests','tag',$query). '</a>';
1450 if($tags) { // there are results to display!!
1452 $output .= print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3, 'main' ,true);
1454 //print a link "Add $query to my interests"
1455 if (!empty($addtaglink)) {
1456 $output .= print_box($addtaglink,'box','tag-management-box',true);
1459 $nr_of_lis_per_ul = 6;
1460 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
1462 $output .= '<ul id="tag-search-results">';
1463 for($i = 0; $i < $nr_of_uls; $i++
) {
1465 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul ) as $tag) {
1466 $tag_link = ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.tag_display_name($tag).'</a>';
1467 $output .= '•' . $tag_link . '<br/>';
1472 $output .= '<div> </div>'; // <-- small layout hack in order to look good in Firefox
1474 $output .= print_paging_bar($count, $page, $perpage, $baseurl.'&', 'page', false, true);
1476 else { //no results were found!!
1478 $output .= print_heading(get_string('noresultsfor', 'tag', $query), '', 3, 'main' , true);
1480 //print a link "Add $query to my interests"
1481 if (!empty($addtaglink)) {
1482 $output .= print_box($addtaglink,'box','tag-management-box', true);
1498 * Prints a tag cloud
1500 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
1501 * @param boolean $shuffle wether or not to shuffle the array passed
1502 * @param int $max_size maximum text size, in percentage
1503 * @param int $min_size minimum text size, in percentage
1504 * @param $return if true return html string
1506 function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80, $return=false) {
1510 if (empty($tagcloud)) {
1521 foreach ($tagcloud as $key => $value){
1522 if(!empty($value->count
)) {
1523 $count[$key] = log10($value->count
);
1533 $spread = $max - $min;
1534 if (0 == $spread) { // we don't want to divide by zero
1538 $step = ($max_size - $min_size)/($spread);
1540 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1541 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1543 //prints the tag cloud
1544 $output = '<ul id="tag-cloud-list">';
1545 foreach ($tagcloud as $key => $tag) {
1547 $size = $min_size +
((log10($tag->count
) - $min) * $step);
1548 $size = ceil($size);
1550 $style = 'style="font-size: '.$size.'%"';
1551 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
1552 $href = 'href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'"';
1554 //highlight tags that have been flagged as inappropriate for those who can manage them
1555 $tagname = tag_display_name($tag);
1556 if ($tag->flag
> 0 && $can_manage_tags) {
1557 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
1560 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
1562 $output .= $tag_link;
1575 function print_tag_management_list($perpage='100') {
1578 require_once($CFG->libdir
.'/tablelib.php');
1582 $tablecolumns = array('id','name', 'fullname', 'count', 'flag', 'timemodified', 'rawname', 'tagtype', '');
1583 $tableheaders = array( get_string('id' , 'tag'),
1584 get_string('name' , 'tag'),
1585 get_string('owner','tag'),
1586 get_string('count','tag'),
1587 get_string('flag','tag'),
1588 get_string('timemodified','tag'),
1589 get_string('newname', 'tag'),
1590 get_string('tagtype', 'tag'),
1591 get_string('select', 'tag')
1594 $table = new flexible_table('tag-management-list-'.$USER->id
);
1596 $baseurl = $CFG->wwwroot
.'/tag/manage.php';
1598 $table->define_columns($tablecolumns);
1599 $table->define_headers($tableheaders);
1600 $table->define_baseurl($baseurl);
1602 $table->sortable(true, 'flag', SORT_DESC
);
1604 $table->set_attribute('cellspacing', '0');
1605 $table->set_attribute('id', 'tag-management-list');
1606 $table->set_attribute('class', 'generaltable generalbox');
1608 $table->set_control_variables(array(
1609 TABLE_VAR_SORT
=> 'ssort',
1610 TABLE_VAR_HIDE
=> 'shide',
1611 TABLE_VAR_SHOW
=> 'sshow',
1612 TABLE_VAR_IFIRST
=> 'sifirst',
1613 TABLE_VAR_ILAST
=> 'silast',
1614 TABLE_VAR_PAGE
=> 'spage'
1619 if ($table->get_sql_sort()) {
1620 $sort = ' ORDER BY '.$table->get_sql_sort();
1625 if ($table->get_sql_where()) {
1626 $where = 'WHERE '.$table->get_sql_where();
1633 tg.id, tg.name, tg.rawname, tg.tagtype, COUNT(ti.id) AS count, u.id AS owner, tg.flag, tg.timemodified, u.firstname, u.lastname
1635 {$CFG->prefix}tag_instance ti
1637 {$CFG->prefix}tag tg
1641 {$CFG->prefix}user u
1651 $totalcount = count_records_sql("SELECT COUNT(DISTINCT(tg.id))
1652 FROM {$CFG->prefix}tag tg LEFT JOIN {$CFG->prefix}user u ON u.id = tg.userid
1655 $table->initialbars(true); // always initial bars
1656 $table->pagesize($perpage, $totalcount);
1658 echo '<form id="tag-management-form" method="post" action="'.$CFG->wwwroot
.'/tag/manage.php">';
1660 //retrieve tags from DB
1661 if ($tagrecords = get_records_sql($query, $table->get_page_start(), $table->get_page_size())) {
1663 $taglist = array_values($tagrecords);
1665 //print_tag_cloud(array_values(get_records_sql($query)), false);
1667 //populate table with data
1668 foreach ($taglist as $tag ){
1671 $name = '<a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'. tag_display_name($tag) .'</a>';
1672 $owner = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$tag->owner
.'">' . fullname($tag) . '</a>';
1673 $count = $tag->count
;
1675 $timemodified = format_time(time() - $tag->timemodified
);
1676 $checkbox = '<input type="checkbox" name="tagschecked[]" value="'.$tag->id
.'" />';
1677 $text = '<input type="text" name="newname['.$tag->id
.']" />';
1679 // get all the possible tag types from db
1680 $tagtypes = array();
1681 if ($ptypes = get_records_sql("SELECT DISTINCT(tagtype), id FROM {$CFG->prefix}tag")) {
1682 foreach ($ptypes as $ptype) {
1683 $tagtypes[$ptype->tagtype
] = $ptype->tagtype
;
1687 $tagtypes['default']='default';
1688 $tagtypes['official']='official';
1690 $tagtype = choose_from_menu ($tagtypes, 'tagtypes['.$tag->id
.']', $tag->tagtype
, '', '', '0', true);
1692 //if the tag if flagged, highlight it
1693 if ($tag->flag
> 0) {
1694 $id = '<span class="flagged-tag">' . $id . '</span>';
1695 $name = '<span class="flagged-tag">' . $name . '</span>';
1696 $owner = '<span class="flagged-tag">' . $owner . '</span>';
1697 $count = '<span class="flagged-tag">' . $count . '</span>';
1698 $flag = '<span class="flagged-tag">' . $flag . '</span>';
1699 $timemodified = '<span class="flagged-tag">' . $timemodified . '</span>';
1700 $tagtype = '<span class="flagged-tag">'. $tagtype. '</span>';
1703 $data = array($id, $name , $owner ,$count ,$flag, $timemodified, $text, $tagtype, $checkbox);
1705 $table->add_data($data);
1709 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
1710 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
1712 echo '<select id="menuformaction" name="action">
1713 <option value="" selected="selected">'. get_string('withselectedtags', 'tag') .'</option>
1714 <option value="reset">'. get_string('resetflag', 'tag') .'</option>
1715 <option value="delete">'. get_string('delete', 'tag') .'</option>
1716 <option value="changetype">'. get_string('changetype', 'tag') .'</option>
1717 <option value="changename">'. get_string('changename', 'tag') .'</option>
1720 echo '<button id="tag-management-submit" type="submit">'. get_string('ok') .'</button>';
1724 $table->print_html();