3 require_once(dirname(__FILE__
) . '/../config.php');
5 define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
9 * Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
10 * will create the following normalized {@link tag_normalize()} entries in tags table:
14 * @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
15 * @param string $tag_type type of tag to be created ("default" is the default value).
16 * @return an array of tags ids, indexed by their normalized names
18 function tag_create($tag_names_csv, $tag_type="default") {
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 = 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 ids to names
76 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
77 $tag_ids_csv = tag_id_from_string($tag_names_csv);
78 //put apostrophes in names
79 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $tag_names_csv) . "'";
80 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
82 // tag instances needs to be deleted as well
83 delete_records_select('tag_instance',"tagid IN ($tag_ids_csv_with_apos)");
84 return delete_records_select('tag',"name IN ($tag_names_csv_with_apos)");
89 * Get all tags from the records
91 * @param string $tag_types_csv (optional, default value is "default". If '*' is passed, tags of any type will be returned).
92 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
93 * @param string $fields a comma separated list of fields to return
94 * (optional, by default 'id, tagtype, name, rawname, flag'). The first field will be used as key for the
95 * array so must be a unique field such as 'id'.
97 function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields=DEFAULT_TAG_TABLE_FIELDS
) {
99 if ($tag_types_csv == '*'){
100 return get_records('tag', '', '', $sort, $fields);
103 $tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
105 return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
109 * Determines if a tag exists
111 * @param string $tag_name_or_id **normalized** tag name, or an id.
112 * @return true if exists or false otherwise
115 function tag_exists($tag_name_or_id) {
117 if (is_numeric($tag_name_or_id)) {
118 return record_exists('tag', 'id', $tag_name_or_id);
120 elseif (is_string($tag_name_or_id)) {
121 return record_exists('tag', 'name', $tag_name_or_id);
126 * Function that returns the id of a tag
128 * @param String $tag_name **normalized** name of the tag
129 * @return int id of the matching tag
131 function tag_id($tag_name) {
132 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
143 * Function that returns the ids of tags
145 * Ex: tags_id('computers, algorithms')
147 * @param String $tag_names_csv comma separated **normalized** tag names.
148 * @return Array array with the tags ids, indexed by their **normalized** names
150 function tags_id($tag_names_csv) {
152 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
153 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
155 $tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" );
158 foreach ($tag_objects as $tag) {
159 $tags_ids[$tag->name
] = $tag->id
;
166 * Function that returns the name of a tag
168 * @param int $tag_id id of the tag
169 * @return String name of the tag with the id passed
171 function tag_name($tag_id) {
172 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
183 * Function that retrieves the names of tags given their ids
185 * @param String $tag_ids_csv comma separated tag ids
186 * @return Array an array with the tags names, indexed by their ids
189 function tags_name($tag_ids_csv) {
191 //remove any white spaces
192 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
194 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
196 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
198 $tags_names = array();
199 foreach ($tag_objects as $tag) {
200 $tags_names[$tag->id
] = $tag->name
;
207 * Function that returns the name of a tag for display.
209 * @param mixed $tag_object
212 function tag_display_name($tag_object){
216 if( empty($CFG->keeptagnamecase
) ) {
217 //this is the normalized tag name
218 return mb_convert_case($tag_object->name
, MB_CASE_TITLE
,"UTF-8");
221 //original casing of the tag name
222 return $tag_object->rawname
;
228 * Function that retrieves a tag object by its id
230 * @param String $tag_id
231 * @return mixed a fieldset object containing the first matching record, or false if none found
233 function tag_by_id($tag_id) {
235 return get_record('tag','id',$tag_id);
239 * Function that retrieves a tag object by its name
241 * @param String $tag_name
242 * @return mixed a fieldset object containing the first matching record, or false if none found
244 function tag_by_name($tag_name) {
245 $tag = get_record('tag','name',$tag_name);
250 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
253 * Suppose the DB contains only the following entries in the tags table:
259 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
260 * will return '10,12,22,,33,11'
262 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
264 * @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
265 * @return int comma separated ids of the tags
267 function tag_id_from_string($tag_names_or_ids_csv) {
269 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
272 foreach ($tag_names_or_ids as $name_or_id) {
274 if (is_numeric($name_or_id)){
275 $tag_ids[] = trim($name_or_id);
277 elseif (is_string($name_or_id)) {
278 $tag_ids[] = tag_id( $name_or_id );
283 $tag_ids_csv = implode(',',$tag_ids);
284 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
290 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
293 * Suppose the DB contains only the following entries in the tags table:
299 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
300 * will return the string 'mOOdle,moodle,HiStOrY,,education'
302 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
304 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
305 * @return int comma separated names of the tags
307 function tag_name_from_string($tag_names_or_ids_csv) {
309 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
311 $tag_names = array();
312 foreach ($tag_names_or_ids as $name_or_id) {
314 if (is_numeric($name_or_id)){
315 $tag_names[] = tag_name($name_or_id);
317 elseif (is_string($name_or_id)) {
318 $tag_names[] = trim($name_or_id);
323 $tag_names_csv = implode(',',$tag_names);
325 return $tag_names_csv;
331 * Determines if a tag name is valid
333 * @param string $name
336 function is_tag_name_valid($name){
338 $normalized = tag_normalize($name);
340 return !strcmp($normalized, $name) && !empty($name) && !is_numeric($name);
346 * Associates a tag with an item
348 * Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
349 * This will tag an user whose id is 1 with "history", "religions", "roman"
350 * If the tag names passed do not exist, they will get created.
352 * Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
353 * This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
355 * @param string $item_type name of the table where the item is stored. Ex: 'user'
356 * @param string $item_id id of the item to be tagged
357 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
358 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
361 function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
364 //convert any tag ids passed to their corresponding tag names
365 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
368 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
370 //tag instances of an item are ordered, get the last one
373 MAX(ordering) max_order
375 {$CFG->prefix}tag_instance ti
377 ti.itemtype = '{$item_type}'
379 ti.itemid = '{$item_id}'
382 $max_order = get_field_sql($query);
384 $tag_names = explode(',', tag_normalize($tag_names_csv));
387 foreach($tag_names as $tag_name){
388 $ordering[$tag_name] = ++
$max_order;
391 //setup tag_instance object
392 $tag_instance = new StdClass
;
393 $tag_instance->itemtype
= $item_type;
394 $tag_instance->itemid
= $item_id;
397 //create tag instances
398 foreach ($tags_created_ids as $tag_normalized_name => $tag_id) {
400 $tag_instance->tagid
= $tag_id;
401 $tag_instance->ordering
= $ordering[$tag_normalized_name];
402 $tag_instance->timemodified
= time();
403 $tag_instance_exists = get_record('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
405 if (!$tag_instance_exists) {
406 insert_record('tag_instance',$tag_instance);
409 $tag_instance_exists->timemodified
= time();
410 $tag_instance_exists->ordering
= $ordering[$tag_normalized_name];
411 update_record('tag_instance',$tag_instance_exists);
416 // update_tag_correlations($item_type, $item_id);
422 * Updates the tags associated with an item
425 * Suppose user 1 is tagged only with "algorithms", "computers" and "software"
426 * By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
427 * User 1 will now be tagged only with "algorithms", "software" and "mathematics"
430 * update_item_tags('user', '1', 'algorithms, 12, 13')
431 * User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
434 * @param string $item_type name of the table where the item is stored. Ex: 'user'
435 * @param string $item_id id of the item to be tagged
436 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
437 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
440 function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
442 //if $tag_names_csv is an empty string, remove all tag associations of the item
443 if( empty($tag_names_or_ids_csv) ){
444 untag_an_item($item_type, $item_id);
448 //convert any tag ids passed to their corresponding tag names
449 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
451 //associate the tags passed with the item
452 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
454 //get the ids of the tags passed
455 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
457 // delete any tag instance with $item_type and $item_id
458 // that are not in $tag_names_csv
459 $tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
462 itemid = '{$item_id}'
464 itemtype = '{$item_type}'
466 tagid NOT IN ({$tags_id_csv})
469 delete_records_select('tag_instance', $select);
474 * Removes the association of an item with a tag
476 * Ex: untag_an_item('user', '1', 'history, 11, roman' )
477 * The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
478 * Calling untag_an_item('user','1') will remove all tags associated with user 1.
480 * @param string $item_type name of the table where the item is stored. Ex: 'user'
481 * @param string $item_id id of the item to be untagged
482 * @param string $tag_names_or_ids_csv comma separated tag **normalized** names or ids of existing tags (optional,
483 * if none is given, all tags of the item will be removed)
486 function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
488 if ($tag_names_or_ids_csv == ""){
490 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
495 $tag_ids_csv = tag_id_from_string($norm_tag_names_or_ids_csv);
497 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
499 delete_records_select('tag_instance',
500 "tagid IN ($tags_id_csv_with_apos) AND itemtype='$item_type' AND itemid='$item_id'");
503 //update_tag_correlations($item_type, $item_id);
508 * Function that gets the tags that are associated with an item
510 * Ex: get_item_tags('user', '1')
512 * @param string $item_type name of the table where the item is stored. Ex: 'user'
513 * @param string $item_id id of the item beeing queried
514 * @param string $sort an order to sort the results in, a valid SQL ORDER BY parameter (default is 'ti.order ASC')
515 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
516 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
517 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
518 * @return mixed an array of objects, or false if no records were found or an error occured.
521 function get_item_tags($item_type, $item_id, $sort='ti.ordering ASC', $fields=DEFAULT_TAG_TABLE_FIELDS
, $limitfrom='', $limitnum='') {
525 $fields = 'tg.' . $fields;
526 $fields = str_replace(',', ',tg.', $fields);
529 $sort = ' ORDER BY '. $sort;
536 {$CFG->prefix}tag_instance ti
542 ti.itemtype = '{$item_type}' AND
543 ti.itemid = '{$item_id}'
547 return get_records_sql($query, $limitfrom, $limitnum);
554 * Function that returns the items of a certain type associated with a certain tag
556 * Ex 1: get_items_tagged_with('user', 'banana')
557 * Ex 2: get_items_tagged_with('user', '11')
559 * @param string $item_type name of the table where the item is stored. Ex: 'user'
560 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
561 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
562 * (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
563 * @param string $fields a comma separated list of fields to return
564 * (optional, by default all fields are returned). The first field will be used as key for the
565 * array so must be a unique field such as 'id'. To avoid field name ambiguity in the query,
566 * use the identifier "it" Ex: 'it.name, it.id' )
567 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
568 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
569 * @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
572 function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
576 $tag_id = tag_id_from_string($tag_name_or_id);
578 $fields = 'it.' . $fields;
579 $fields = str_replace(',', ',it.', $fields);
582 $sort = ' ORDER BY '. $sort;
589 {$CFG->prefix}{$item_type} it
591 {$CFG->prefix}tag_instance tt
595 tt.itemtype = '{$item_type}' AND
596 tt.tagid = '{$tag_id}'
601 return get_records_sql($query, $limitfrom, $limitnum);
606 * Returns the number of items tagged with a tag
608 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
609 * @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
610 * type will be counted)
611 * @return int the count. If an error occurrs, 0 is returned.
613 function count_items_tagged_with($tag_name_or_id, $item_type='') {
617 $tag_id = tag_id_from_string($tag_name_or_id);
619 if (empty($item_type)){
624 {$CFG->prefix}tag_instance tt
634 {$CFG->prefix}{$item_type} it
636 {$CFG->prefix}tag_instance tt
640 tt.itemtype = '{$item_type}' AND
641 tt.tagid = '{$tag_id}' ";
645 return count_records_sql($query);
651 * Determines if an item is tagged with a certain tag
653 * @param string $item_type name of the table where the item is stored. Ex: 'user'
654 * @param string $item_id id of the item beeing queried
655 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
656 * @return bool true if a matching record exists, else false.
658 function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
660 $tag_id = tag_id_from_string($tag_name_or_id);
662 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
666 * Search for tags with names that match some text
668 * @param string $text string that the tag names will be matched against
669 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
670 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
671 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
672 * @return mixed an array of objects, or false if no records were found or an error occured.
675 function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
679 $text = tag_normalize($text);
684 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
688 {$CFG->prefix}tag_instance ti
703 tg.id, tg.name, tg.rawname
714 return get_records_sql($query, $limitfrom , $limitnum);
719 * Function that returns tags that start with some text
721 * @param string $text string that the tag names will be matched against
722 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
723 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
724 * @return mixed an array of objects, or false if no records were found or an error occured.
726 function similar_tags($text, $limitfrom='' , $limitnum='' ) {
730 $text = tag_normalize($text);
734 tg.id, tg.name, tg.rawname
743 return get_records_sql($query, $limitfrom , $limitnum);
747 * Returns tags related to a tag
749 * Related tags of a tag come from two sources:
750 * - manually added related tags, which are tag_instance entries for that tag
751 * - correlated tags, which are a calculated
753 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
754 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
755 * @return mixed an array of tag objects
758 function related_tags($tag_name_or_id, $limitnum=10) {
760 $tag_id = tag_id_from_string($tag_name_or_id);
762 //gets the manually added related tags
763 $manual_related_tags = get_item_tags('tag',$tag_id, 'ti.ordering ASC',DEFAULT_TAG_TABLE_FIELDS
);
764 if ($manual_related_tags == false) $manual_related_tags = array();
766 //gets the correlated tags
767 $automatic_related_tags = correlated_tags($tag_id);
768 if ($automatic_related_tags == false) $automatic_related_tags = array();
770 $related_tags = array_merge($manual_related_tags,$automatic_related_tags);
772 return array_slice( object_array_unique($related_tags) , 0 , $limitnum );
778 * Returns the correlated tags of a tag
779 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
781 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
782 * @return mixed an array of tag objects
784 function correlated_tags($tag_name_or_id) {
786 $tag_id = tag_id_from_string($tag_name_or_id);
788 if (!$tag_correlation = get_record('tag_correlation','tagid',$tag_id)) {
792 $tags_id_csv_with_apos = stripcslashes($tag_correlation->correlatedtags
);
794 return get_records_select('tag', "id IN ({$tags_id_csv_with_apos})", '', DEFAULT_TAG_TABLE_FIELDS
);
798 * Recalculates tag correlations of all the tags associated with an item
799 * This function could be called whenever the tags associations with an item changes
800 * ( for example when tag_an_item() or untag_an_item() is called )
802 * @param string $item_type name of the table where the item is stored. Ex: 'user'
803 * @param string $item_id id of the item
805 function update_tag_correlations($item_type, $item_id) {
807 $item_tags = get_item_tags($item_type, $item_id);
809 foreach ($item_tags as $tag) {
810 cache_correlated_tags($tag->id
);
815 * Calculates and stores the correlated tags of a tag.
816 * The correlations are stored in the 'tag_correlation' table.
818 * Two tags are correlated if they appear together a lot.
819 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
821 * The rationale for the 'tag_correlation' table is performance.
822 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
823 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
825 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
826 * @param number $min_correlation cutoff percentage (optional, default is 0.25)
827 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
829 function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
833 $tag_id = tag_id_from_string($tag_name_or_id);
835 // query that counts how many times any tag appears together in items
836 // with the tag passed as argument ($tag_id)
839 tb.tagid , COUNT(*) nr
841 {$CFG->prefix}tag_instance ta
843 {$CFG->prefix}tag_instance tb
845 ta.itemid = tb.itemid
853 $tag_correlations = get_records_sql($query, 0, $limitnum);
855 $tags_id_csv_with_apos = "'";
856 $cutoff = $tag_correlations[$tag_id]->nr
* $min_correlation;
858 foreach($tag_correlations as $correlation) {
859 if($correlation->nr
>= $cutoff && $correlation->tagid
!= $tag_id ){
860 $tags_id_csv_with_apos .= $correlation->tagid
."','";
863 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
866 //saves correlation info in the caching table
868 $tag_correlation_obj = get_record('tag_correlation','tagid',$tag_id);
870 if ($tag_correlation_obj) {
871 $tag_correlation_obj->correlatedtags
= addslashes($tags_id_csv_with_apos);
872 update_record('tag_correlation',$tag_correlation_obj);
875 $tag_correlation_obj = new StdClass
;
876 $tag_correlation_obj->tagid
= $tag_id;
877 $tag_correlation_obj->correlatedtags
= addslashes($tags_id_csv_with_apos);
878 insert_record('tag_correlation',$tag_correlation_obj);
885 * This function cleans up the 'tag_instance' table
886 * It removes orphans in 'tag_instances' table
889 function tag_instance_table_cleanup() {
893 //get the itemtypes present in the 'tag_instance' table
898 {$CFG->prefix}tag_instance
901 $items_types = get_records_sql($query);
903 // for each itemtype, remove tag_instances that are orphans
904 // That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
905 // then this tag_instance is an orphan and it will be removed.
906 foreach ($items_types as $type) {
909 {$CFG->prefix}tag_instance.id
914 FROM {$CFG->prefix}tag_instance sq2
915 LEFT JOIN {$CFG->prefix}{$type->itemtype} item
916 ON sq2.itemid = item.id
917 WHERE item.id IS NULL
918 AND sq2.itemtype = '{$type->itemtype}')
922 delete_records_select('tag_instance', $query);
925 // remove tag_instances that are orphans because tagid does not correspond to an
928 {$CFG->prefix}tag_instance.id
933 FROM {$CFG->prefix}tag_instance sq2
934 LEFT JOIN {$CFG->prefix}tag tg
936 WHERE tg.id IS NULL )
941 delete_records_select('tag_instance', $query);
946 * Function that normalizes a tag name
948 * Ex: tag_normalize('bANAana') -> returns 'banana'
949 * tag_normalize('lots of spaces') -> returns 'lots of spaces'
950 * tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
951 * tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
952 * -> returns 'tag one,tag two,tag three,and another tag'
954 * @param string $tag_names_csv unnormalized CSV tag names
955 * @return string **normalized** CSV tag names
958 function tag_normalize($tag_names_csv, $lowercase=true) {
960 $tags = explode(',', $tag_names_csv);
962 if (sizeof($tags) > 1) {
964 foreach ($tags as $key => $tag) {
965 $tags[$key] = tag_normalize($tag);
968 return implode(',' , $tags);
972 // only one tag was passed
976 $value = moodle_strtolower($tag_names_csv);
979 $value = $tag_names_csv;
982 //$value = preg_replace('|[^\w ]|i', '', strtolower(trim($tag_names_csv)));
983 $value = preg_replace('|[\,\!\@\#\$\%\^\&\*\(\)\-\+\=\~\`\\"\'\_.\[\]\{\}\:\;\?\´\^\\\/\<\>\|]|i', '', trim($value));
985 //removes excess white spaces
986 $value = preg_replace('/\s\s+/', ' ', $value);
993 function tag_flag_inappropriate($tag_names_or_ids_csv){
995 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
997 $tag_ids = explode(',', $tag_ids_csv);
999 foreach ($tag_ids as $id){
1000 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
1003 $tag->timemodified
= time();
1005 update_record('tag', $tag);
1009 function tag_flag_reset($tag_names_or_ids_csv){
1013 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
1015 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
1017 $timemodified = time();
1021 {$CFG->prefix}tag tg
1024 tg.timemodified = {$timemodified}
1028 ({$tag_ids_csv_with_apos})
1031 execute_sql($query, false);
1035 * Function that updates tags names.
1036 * Updates only if the new name suggested for a tag doesn´t exist already.
1038 * @param Array $tags_names_changed array of new tag names indexed by tag ids.
1039 * @return Array array of tags names that were effectively updated, indexed by tag ids.
1041 function tag_update_name($tags_names_changed){
1043 $tags_names_updated = array();
1045 foreach ($tags_names_changed as $id => $newname){
1047 $norm_newname = tag_normalize($newname);
1049 if( !tag_exists($norm_newname) && is_tag_name_valid($norm_newname) ) {
1051 $tag = tag_by_id($id);
1053 $tags_names_updated[$id] = $tag->name
;
1055 // rawname keeps the original casing of the string
1056 $tag->rawname
= tag_normalize($newname, false);
1058 // name lowercases the string
1059 $tag->name
= $norm_newname;
1061 $tag->timemodified
= time();
1063 update_record('tag',$tag);
1068 return $tags_names_updated;
1073 * Function that returns comma separated HTML links to the tag pages of the tags passed
1075 * @param array $tag_objects an array of tag objects
1076 * @return string CSV, HTML links to tag pages
1079 function tag_links_csv($tag_objects) {
1084 if (empty($tag_objects)) {
1088 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1089 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1091 foreach ($tag_objects as $tag){
1092 //highlight tags that have been flagged as inappropriate for those who can manage them
1093 $tagname = tag_display_name($tag);
1094 if ($tag->flag
> 0 && $can_manage_tags) {
1095 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
1097 $tag_links .= ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.$tagname.'</a>,';
1100 return rtrim($tag_links, ',');
1104 * Function that returns comma separated names of the tags passed
1105 * Example of string that might be returned: 'history, wars, greek history'
1107 * @param array $tag_objects
1108 * @return string CSV tag names
1111 function tag_names_csv($tag_objects) {
1113 if (empty($tag_objects)) {
1119 foreach ($tag_objects as $tag){
1120 $tags[] = tag_display_name($tag);
1123 return implode(', ', $tags);
1128 * Returns a number of random tags, ordered by their popularity
1130 * @param int $nr_of_tags number of random tags to be returned
1131 * @param unknown_type $tag_type
1132 * @return mixed an array of tag objects with the following fields: id, name and count
1134 function rand_tags_count($nr_of_tags=20, $tag_type = 'default') {
1138 if (!$tags = get_all_tags($tag_type)) {
1142 if(sizeof($tags) < $nr_of_tags) {
1143 $nr_of_tags = sizeof($tags);
1146 $rndtags = array_rand($tags, $nr_of_tags);
1148 $tags_id_csv_with_apos = "'";
1149 foreach($rndtags as $tagid) {
1150 $tags_id_csv_with_apos .= $tags[$tagid]->id
. "','";
1152 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
1157 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, tg.flag
1159 {$CFG->prefix}tag_instance ti
1161 {$CFG->prefix}tag tg
1167 ({$tags_id_csv_with_apos})
1174 return get_records_sql($query);
1179 function tag_cron(){
1181 tag_instance_table_cleanup();
1183 $tags = get_all_tags('*');
1185 foreach ($tags as $tag){
1186 cache_correlated_tags($tag->id
);
1190 /*-------------------- Printing functions -------------------- */
1193 * Prints a box that contains the management links of a tag
1195 * @param $tag_object
1198 function print_tag_management_box($tag_object) {
1202 $tagname = tag_display_name($tag_object);
1204 print_box_start('box','tag-management-box');
1206 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1209 if ( has_capability('moodle/tag:manage',$systemcontext) ) {
1210 $manage_link = "<a href=\"{$CFG->wwwroot}/tag/manage.php\">" . get_string('managetags', 'tag') . "</a>" ;
1211 echo $manage_link .' | ';
1214 // if the user is not tagged with the $tag_object tag, a link "add blahblah to my interests" will appear
1215 if( !is_item_tagged_with('user', $USER->id
, $tag_object->id
)) {
1216 $addtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&id='. $tag_object->id
.'">';
1217 $addtaglink .= get_string('addtagtomyinterests','tag',$tagname). '</a>';
1218 echo $addtaglink .' | ';
1221 // only people with moodle/tag:edit capability may edit the tag description
1222 if ( has_capability('moodle/tag:edit',$systemcontext) && is_item_tagged_with('user', $USER->id
, $tag_object->id
) ) {
1223 echo ' <a href="'. $CFG->wwwroot
. '/tag/edit.php?id='.$tag_object->id
.'">'.get_string('edittag', 'tag').'</a> | ';
1226 // flag as inappropriate link
1227 $flagtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=flaginappropriate&id='. $tag_object->id
.'">';
1228 $flagtaglink .= get_string('flagasinappropriate','tag',$tagname). '</a>';
1236 * Prints a box with the description of a tag and its related tags
1238 * @param unknown_type $tag_object
1241 function print_tag_description_box($tag_object) {
1245 $tagname = tag_display_name($tag_object);
1246 $related_tags = related_tags($tag_object->id
); //get_item_tags('tags',$tag_object->id);
1249 print_box_start('generalbox', 'tag-description');
1251 if (!empty($tag_object->description
)) {
1252 $options = new object;
1253 $options->para
=false;
1254 echo format_text($tag_object->description
, $tag_object->descriptionformat
, $options );
1257 echo format_text(get_string('thistaghasnodesc','tag'));
1260 if ($related_tags) {
1261 echo '<br/><br/><b>'.get_string('relatedtags','tag').': </b>' . tag_links_csv($related_tags);
1268 * Prints a table of the users tagged with the tag passed as argument
1270 * @param $tag_object
1271 * @param int $users_per_row number of users per row to display
1272 * @param int $limitfrom prints users starting at this point (optional, required if $limitnum is set).
1273 * @param int $limitnum prints this many users (optional, required if $limitfrom is set).
1276 function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='') {
1278 //List of users with this tag
1279 $userlist = array_values( get_items_tagged_with(
1283 'id, firstname, lastname, picture',
1288 print_box_start('generalbox', 'tag-user-table');
1290 print_user_list($userlist);
1300 * Prints a list of users
1302 * @param array $userlist an array of user objects
1304 function print_user_list($userlist) {
1306 foreach ($userlist as $user){
1307 print_user_box( $user );
1314 * Prints an individual user box
1316 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
1318 function print_user_box($user) {
1322 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
1325 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1326 $profilelink = $CFG->wwwroot
.'/user/view.php?id='.$user->id
;
1329 print_box_start('user-box', 'user'.$user->id
);
1331 if (!empty($profilelink)) {
1332 echo '<a href="'.$profilelink.'">';
1336 if ($user->picture
) {
1337 echo '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/user/pix.php/'. $user->id
.'/f1.jpg"'.'/>';
1339 echo '<img alt="" class="user-image" src="'. $CFG->wwwroot
.'/pix/u/f1.png"'.'/>';
1344 if (!empty($profilelink)) {
1348 $fullname = fullname($user);
1349 //truncate name if it's too big
1350 if (strlen($fullname) > 26) $fullname = substr($fullname,0,26) . '...';
1352 echo '<strong>' . $fullname . '</strong>';
1359 * Prints the tag search box
1362 function print_tag_search_box($search='') {
1366 print_box_start('','tag-search-box');
1368 echo '<form action="'.$CFG->wwwroot
.'/tag/search.php" style="display:inline">';
1370 echo '<input id="searchform_search" name="query" type="text" size="40" />';
1371 echo '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
1379 * Prints the tag search results
1381 * @param string $query text that tag names will be matched against
1382 * @param int $page current page
1383 * @param int $perpage nr of users displayed per page
1385 function print_tag_search_results($query, $page, $perpage) {
1389 $count = sizeof( search_tags($query,false) );
1390 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
1392 $baseurl = $CFG->wwwroot
.'/tag/search.php?query=' . $query;
1394 // link "Add $query to my interests"
1396 if( !is_item_tagged_with('user', $USER->id
, $query )) {
1397 $addtaglink = '<a href="' . $CFG->wwwroot
. '/user/tag.php?action=addinterest&name='. $query .'">';
1398 $addtaglink .= get_string('addtagtomyinterests','tag',$query). '</a>';
1402 if($tags) { // there are results to display!!
1404 print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3);
1406 //print a link "Add $query to my interests"
1407 if (!empty($addtaglink)) {
1408 print_box($addtaglink,'box','tag-management-box');
1411 $nr_of_lis_per_ul = 6;
1412 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
1414 echo '<ul id="tag-search-results">';
1415 for($i = 0; $i < $nr_of_uls; $i++
) {
1417 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul ) as $tag) {
1418 $tag_link = ' <a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'.tag_display_name($tag).'</a>';
1419 echo '•' . $tag_link . '<br/>';
1424 echo '<div> </div>'; // <-- small layout hack in order to look good in Firefox
1426 print_paging_bar($count, $page, $perpage, $baseurl.'&', 'page');
1428 else { //no results were found!!
1430 print_heading(get_string('noresultsfor', 'tag', $query), '', 3);
1432 //print a link "Add $query to my interests"
1433 if (!empty($addtaglink)) {
1434 print_box($addtaglink,'box','tag-management-box');
1443 * Prints a tag cloud
1445 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
1446 * @param boolean $shuffle wether or not to shuffle the array passed
1447 * @param int $max_size maximum text size, in percentage
1448 * @param int $min_size minimum text size, in percentage
1450 function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80) {
1454 if (empty($tagcloud)) {
1463 foreach ($tagcloud as $key => $value){
1464 if(!empty($value->count
)) {
1465 $count[$key] = log10($value->count
);
1475 $spread = $max - $min;
1476 if (0 == $spread) { // we don't want to divide by zero
1480 $step = ($max_size - $min_size)/($spread);
1482 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1483 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1485 //prints the tag cloud
1486 echo '<ul id="tag-cloud-list">';
1487 foreach ($tagcloud as $key => $tag) {
1489 $size = $min_size +
((log10($tag->count
) - $min) * $step);
1490 $size = ceil($size);
1492 $style = 'style="font-size: '.$size.'%"';
1493 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
1494 $href = 'href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'"';
1496 //highlight tags that have been flagged as inappropriate for those who can manage them
1497 $tagname = tag_display_name($tag);
1498 if ($tag->flag
> 0 && $can_manage_tags) {
1499 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
1502 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
1511 function print_tag_management_list($perpage='100') {
1514 require_once($CFG->libdir
.'/tablelib.php');
1518 $tablecolumns = array('id','name', 'owner', 'count', 'flag', 'timemodified', 'rawname', '');
1519 $tableheaders = array( get_string('id' , 'tag'),
1520 get_string('name' , 'tag'),
1521 get_string('owner','tag'),
1522 get_string('count','tag'),
1523 get_string('flag','tag'),
1524 get_string('timemodified','tag'),
1525 get_string('newname', 'tag'),
1526 get_string('select', 'tag')
1529 $table = new flexible_table('tag-management-list-'.$USER->id
);
1531 $baseurl = $CFG->wwwroot
.'/tag/manage.php';
1533 $table->define_columns($tablecolumns);
1534 $table->define_headers($tableheaders);
1535 $table->define_baseurl($baseurl);
1537 $table->sortable(true, 'flag', SORT_DESC
);
1539 $table->set_attribute('cellspacing', '0');
1540 $table->set_attribute('id', 'tag-management-list');
1541 $table->set_attribute('class', 'generaltable generalbox');
1543 $table->set_control_variables(array(
1544 TABLE_VAR_SORT
=> 'ssort',
1545 TABLE_VAR_HIDE
=> 'shide',
1546 TABLE_VAR_SHOW
=> 'sshow',
1547 TABLE_VAR_IFIRST
=> 'sifirst',
1548 TABLE_VAR_ILAST
=> 'silast',
1549 TABLE_VAR_PAGE
=> 'spage'
1554 if ($table->get_sql_sort()) {
1555 $sort = ' ORDER BY '.$table->get_sql_sort();
1560 if ($table->get_sql_where()) {
1561 $where = 'WHERE '.$table->get_sql_where();
1568 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, u.id AS owner, tg.flag, tg.timemodified
1570 {$CFG->prefix}tag_instance ti
1572 {$CFG->prefix}tag tg
1576 {$CFG->prefix}user u
1585 $totalcount = count_records('tag');
1587 $table->initialbars($totalcount > $perpage);
1588 $table->pagesize($perpage, $totalcount);
1591 echo '<form id="tag-management-form" method="post" action="'.$CFG->wwwroot
.'/tag/manage.php">';
1593 //retrieve tags from DB
1594 if ($tagrecords = get_records_sql($query, $table->get_page_start(), $table->get_page_size())) {
1596 $taglist = array_values($tagrecords);
1598 //print_tag_cloud(array_values(get_records_sql($query)), false);
1600 //populate table with data
1601 foreach ($taglist as $tag ){
1604 $name = '<a href="'.$CFG->wwwroot
.'/tag/index.php?id='.$tag->id
.'">'. tag_display_name($tag) .'</a>';
1605 $owner = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$tag->owner
.'">' . $tag->owner
. '</a>';
1606 $count = $tag->count
;
1608 $timemodified = format_time(time() - $tag->timemodified
);
1609 $checkbox = '<input type="checkbox" name="tagschecked[]" value="'.$tag->id
.'" />';
1610 $text = '<input type="text" name="newname['.$tag->id
.']" />';
1612 //if the tag if flagged, highlight it
1613 if ($tag->flag
> 0) {
1614 $id = '<span class="flagged-tag">' . $id . '</span>';
1615 $name = '<span class="flagged-tag">' . $name . '</span>';
1616 $owner = '<span class="flagged-tag">' . $owner . '</span>';
1617 $count = '<span class="flagged-tag">' . $count . '</span>';
1618 $flag = '<span class="flagged-tag">' . $flag . '</span>';
1619 $timemodified = '<span class="flagged-tag">' . $timemodified . '</span>';
1622 $data = array($id, $name , $owner ,$count ,$flag, $timemodified, $text, $checkbox);
1624 $table->add_data($data);
1628 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
1629 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
1631 echo '<select id="menuformaction" name="action">
1632 <option value="" selected="selected">'. get_string('withselectedtags', 'tag') .'</option>
1633 <option value="reset">'. get_string('resetflag', 'tag') .'</option>
1634 <option value="delete">'. get_string('delete', 'tag') .'</option>
1635 <option value="changename">'. get_string('changename', 'tag') .'</option>
1638 echo '<button id="tag-management-submit" type="submit">'. get_string('ok') .'</button>';
1642 $table->print_html();