Moved check for plugin import/export to the start rather than the end
[moodle-linuxchix.git] / tag / lib.php
blobf403f5531720373ae17fcf6217eb2020e1da35f9
1 <?php // $Id$
3 require_once(dirname(__FILE__) . '/../config.php');
5 define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
6 /**
7 * Creates tags
9 * Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
10 * will create the following normalized {@link tag_normalize()} entries in tags table:
11 * 'a very cool tag'
12 * 'another nice tag'
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") {
19 global $USER;
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 ( $can_create_tags && !$exists && !empty($tag_object->name) && !is_numeric($tag_object->name) ) {
45 insert_record('tag', $tag_object);
49 $norm_tag_names_csv = substr($norm_tag_names_csv,0,-1);
51 return tags_id( $norm_tag_names_csv );
55 /**
56 * Deletes tags
58 * Ex 1: tag_delete('a very cool tag, another nice tag')
59 * Will delete the tags with names 'a very cool tag' and 'another nice tag' from the 'tags' table, if they exist!
61 * Ex 2: tag_delete('computers, 123, 143, algorithms')
62 * Will delete tags with names 'computers' and 'algorithms' and tags with ids 123 and 143.
65 * @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
68 function tag_delete($tag_names_or_ids_csv) {
70 //covert all ids to names
71 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
73 //put apostrophes in names
74 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $tag_names_csv) . "'";
76 delete_records_select('tag',"name IN ($tag_names_csv_with_apos)");
80 /**
81 * Get all tags from the records
83 * @param string $tag_types_csv (optional, default value is "default". If '*' is passed, tags of any type will be returned).
84 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
85 * @param string $fields a comma separated list of fields to return
86 * (optional, by default 'id, tagtype, name, rawname, flag'). The first field will be used as key for the
87 * array so must be a unique field such as 'id'.
89 function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields=DEFAULT_TAG_TABLE_FIELDS) {
91 if ($tag_types_csv == '*'){
92 return get_records('tag', '', '', $sort, $fields);
95 $tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
97 return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
101 * Determines if a tag exists
103 * @param string $tag_name_or_id **normalized** tag name, or an id.
104 * @return true if exists or false otherwise
107 function tag_exists($tag_name_or_id) {
109 if (is_numeric($tag_name_or_id)) {
110 return record_exists('tag', 'id', $tag_name_or_id);
112 elseif (is_string($tag_name_or_id)) {
113 return record_exists('tag', 'name', $tag_name_or_id);
118 * Function that returns the id of a tag
120 * @param String $tag_name **normalized** name of the tag
121 * @return int id of the matching tag
123 function tag_id($tag_name) {
124 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
126 if ($tag){
127 return $tag->id;
129 else{
130 return false;
135 * Function that returns the ids of tags
137 * Ex: tags_id('computers, algorithms')
139 * @param String $tag_names_csv comma separated **normalized** tag names.
140 * @return Array array with the tags ids, indexed by their **normalized** names
142 function tags_id($tag_names_csv) {
144 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
145 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
147 $tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" );
149 $tags_ids = array();
150 foreach ($tag_objects as $tag) {
151 $tags_ids[$tag->name] = $tag->id;
154 return $tags_ids;
158 * Function that returns the name of a tag
160 * @param int $tag_id id of the tag
161 * @return String name of the tag with the id passed
163 function tag_name($tag_id) {
164 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
166 if ($tag){
167 return $tag->name;
169 else{
170 return '';
175 * Function that retrieves the names of tags given their ids
177 * @param String $tag_ids_csv comma separated tag ids
178 * @return Array an array with the tags names, indexed by their ids
181 function tags_name($tag_ids_csv) {
183 //remove any white spaces
184 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
186 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
188 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
190 $tags_names = array();
191 foreach ($tag_objects as $tag) {
192 $tags_names[$tag->id] = $tag->name;
195 return $tags_names;
199 * Function that returns the name of a tag for display.
201 * @param mixed $tag_object
202 * @return string
204 function tag_display_name($tag_object){
206 global $CFG;
208 if( empty($CFG->keeptagnamecase) ) {
209 //this is the normalized tag name
210 return mb_convert_case($tag_object->name, MB_CASE_TITLE,"UTF-8");
212 else {
213 //original casing of the tag name
214 return $tag_object->rawname;
220 * Function that retrieves a tag object by its id
222 * @param String $tag_id
223 * @return mixed a fieldset object containing the first matching record, or false if none found
225 function tag_by_id($tag_id) {
227 return get_record('tag','id',$tag_id);
231 * Function that retrieves a tag object by its name
233 * @param String $tag_name
234 * @return mixed a fieldset object containing the first matching record, or false if none found
236 function tag_by_name($tag_name) {
237 $tag = get_record('tag','name',$tag_name);
238 return $tag;
242 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
244 * Ex:
245 * Suppose the DB contains only the following entries in the tags table:
246 * id name
247 * 10 moodle
248 * 12 science
249 * 22 education
251 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
252 * will return '10,12,22,,33,11'
254 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
256 * @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
257 * @return int comma separated ids of the tags
259 function tag_id_from_string($tag_names_or_ids_csv) {
261 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
263 $tag_ids = array();
264 foreach ($tag_names_or_ids as $name_or_id) {
266 if (is_numeric($name_or_id)){
267 $tag_ids[] = trim($name_or_id);
269 elseif (is_string($name_or_id)) {
270 $tag_ids[] = tag_id( $name_or_id );
275 $tag_ids_csv = implode(',',$tag_ids);
276 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
278 return $tag_ids_csv;
282 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
284 * Ex:
285 * Suppose the DB contains only the following entries in the tags table:
286 * id name
287 * 10 moodle
288 * 12 science
289 * 22 education
291 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
292 * will return the string 'mOOdle,moodle,HiStOrY,,education'
294 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
296 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
297 * @return int comma separated names of the tags
299 function tag_name_from_string($tag_names_or_ids_csv) {
301 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
303 $tag_names = array();
304 foreach ($tag_names_or_ids as $name_or_id) {
306 if (is_numeric($name_or_id)){
307 $tag_names[] = tag_name($name_or_id);
309 elseif (is_string($name_or_id)) {
310 $tag_names[] = trim($name_or_id);
315 $tag_names_csv = implode(',',$tag_names);
317 return $tag_names_csv;
322 * Associates a tag with an item
324 * Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
325 * This will tag an user whose id is 1 with "history", "religions", "roman"
326 * If the tag names passed do not exist, they will get created.
328 * Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
329 * This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
331 * @param string $item_type name of the table where the item is stored. Ex: 'user'
332 * @param string $item_id id of the item to be tagged
333 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
334 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
337 function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
339 //convert any tag ids passed to their corresponding tag names
340 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
342 //create the tags
343 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
345 $tag_instance = new StdClass;
346 $tag_instance->itemtype = $item_type;
347 $tag_instance->itemid = $item_id;
349 //create tag instances
350 foreach ($tags_created_ids as $tag_id) {
352 $tag_instance->tagid = $tag_id;
354 $exists = record_exists('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
356 if (!$exists) {
357 insert_record('tag_instance',$tag_instance);
362 // update_tag_correlations($item_type, $item_id);
368 * Updates the tags associated with an item
370 * Ex 1:
371 * Suppose user 1 is tagged only with "algorithms", "computers" and "software"
372 * By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
373 * User 1 will now be tagged only with "algorithms", "software" and "mathematics"
375 * Ex 2:
376 * update_item_tags('user', '1', 'algorithms, 12, 13')
377 * User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
380 * @param string $item_type name of the table where the item is stored. Ex: 'user'
381 * @param string $item_id id of the item to be tagged
382 * @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
383 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
386 function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
388 //if $tag_names_csv is an empty string, remove all tag associations of the item
389 if( empty($tag_names_or_ids_csv) ){
390 untag_an_item($item_type, $item_id);
391 return;
394 //convert any tag ids passed to their corresponding tag names
395 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
397 //associate the tags passed with the item
398 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
400 //get the ids of the tags passed
401 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
403 // delete any tag instance with $item_type and $item_id
404 // that are not in $tag_names_csv
405 $tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
407 $select = "
408 itemid = '{$item_id}'
410 itemtype = '{$item_type}'
412 tagid NOT IN ({$tags_id_csv})
415 delete_records_select('tag_instance', $select);
420 * Removes the association of an item with a tag
422 * Ex: untag_an_item('user', '1', 'history, 11, roman' )
423 * The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
424 * Calling untag_an_item('user','1') will remove all tags associated with user 1.
426 * @param string $item_type name of the table where the item is stored. Ex: 'user'
427 * @param string $item_id id of the item to be untagged
428 * @param string $tag_names_or_ids_csv comma separated tag **normalized** names or ids of existing tags (optional,
429 * if none is given, all tags of the item will be removed)
432 function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
434 if ($tag_names_or_ids_csv == ""){
436 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
439 else {
441 $tag_ids_csv = tag_id_from_string($norm_tag_names_or_ids_csv);
443 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
445 delete_records_select('tag_instance',
446 "tagid IN ($tags_id_csv_with_apos) AND itemtype='$item_type' AND itemid='$item_id'");
449 //update_tag_correlations($item_type, $item_id);
454 * Function that gets the tags that are associated with an item
456 * Ex: get_item_tags('user', '1')
458 * @param string $item_type name of the table where the item is stored. Ex: 'user'
459 * @param string $item_id id of the item beeing queried
460 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
461 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
462 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
463 * @return mixed an array of objects, or false if no records were found or an error occured.
466 function get_item_tags($item_type, $item_id, $fields=DEFAULT_TAG_TABLE_FIELDS, $limitfrom='', $limitnum='') {
468 global $CFG;
470 $fields = 'tg.' . $fields;
471 $fields = str_replace(',', ',tg.', $fields);
473 $query = "
474 SELECT
475 {$fields}
476 FROM
477 {$CFG->prefix}tag_instance ti
478 INNER JOIN
479 {$CFG->prefix}tag tg
481 tg.id = ti.tagid
482 WHERE
483 ti.itemtype = '{$item_type}' AND
484 ti.itemid = '{$item_id}'";
486 return get_records_sql($query, $limitfrom, $limitnum);
493 * Function that returns the items of a certain type associated with a certain tag
495 * Ex 1: get_items_tagged_with('user', 'banana')
496 * Ex 2: get_items_tagged_with('user', '11')
498 * @param string $item_type name of the table where the item is stored. Ex: 'user'
499 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
500 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
501 * (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
502 * @param string $fields a comma separated list of fields to return
503 * (optional, by default all fields are returned). The first field will be used as key for the
504 * array so must be a unique field such as 'id'. To avoid field name ambiguity in the query,
505 * use the identifier "it" Ex: 'it.name, it.id' )
506 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
507 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
508 * @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
511 function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
513 global $CFG;
515 $tag_id = tag_id_from_string($tag_name_or_id);
517 $fields = 'it.' . $fields;
518 $fields = str_replace(',', ',it.', $fields);
520 if ($sort) {
521 $sort = ' ORDER BY '. $sort;
524 $query = "
525 SELECT
526 {$fields}
527 FROM
528 {$CFG->prefix}{$item_type} it
529 INNER JOIN
530 {$CFG->prefix}tag_instance tt
532 it.id = tt.itemid
533 WHERE
534 tt.itemtype = '{$item_type}' AND
535 tt.tagid = '{$tag_id}'
536 {$sort}
540 return get_records_sql($query, $limitfrom, $limitnum);
545 * Returns the number of items tagged with a tag
547 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
548 * @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
549 * type will be counted)
550 * @return int the count. If an error occurrs, 0 is returned.
552 function count_items_tagged_with($tag_name_or_id, $item_type='') {
554 global $CFG;
556 $tag_id = tag_id_from_string($tag_name_or_id);
558 if (empty($item_type)){
559 $query = "
560 SELECT
561 COUNT(*) AS count
562 FROM
563 {$CFG->prefix}tag_instance tt
564 WHERE
565 tagid = {$tag_id}";
567 else
569 $query = "
570 SELECT
571 COUNT(*) AS count
572 FROM
573 {$CFG->prefix}{$item_type} it
574 INNER JOIN
575 {$CFG->prefix}tag_instance tt
577 it.id = tt.itemid
578 WHERE
579 tt.itemtype = '{$item_type}' AND
580 tt.tagid = '{$tag_id}' ";
584 return count_records_sql($query);
590 * Determines if an item is tagged with a certain tag
592 * @param string $item_type name of the table where the item is stored. Ex: 'user'
593 * @param string $item_id id of the item beeing queried
594 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
595 * @return bool true if a matching record exists, else false.
597 function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
599 $tag_id = tag_id_from_string($tag_name_or_id);
601 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
605 * Search for tags with names that match some text
607 * @param string $text string that the tag names will be matched against
608 * @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
609 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
610 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
611 * @return mixed an array of objects, or false if no records were found or an error occured.
614 function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
616 global $CFG;
618 $text = tag_normalize($text);
620 if ($ordered) {
621 $query = "
622 SELECT
623 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
624 FROM
625 {$CFG->prefix}tag tg
626 LEFT JOIN
627 {$CFG->prefix}tag_instance ti
629 tg.id = ti.tagid
630 WHERE
631 tg.name
632 LIKE
633 '%{$text}%'
634 GROUP BY
635 tg.id
636 ORDER BY
637 count
638 DESC";
639 } else {
640 $query = "
641 SELECT
642 tg.id, tg.name, tg.rawname
643 FROM
644 {$CFG->prefix}tag tg
645 WHERE
646 tg.name
647 LIKE
648 '%{$text}%'
653 return get_records_sql($query, $limitfrom , $limitnum);
658 * Function that returns tags that start with some text
660 * @param string $text string that the tag names will be matched against
661 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
662 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
663 * @return mixed an array of objects, or false if no records were found or an error occured.
665 function similar_tags($text, $limitfrom='' , $limitnum='' ) {
667 global $CFG;
669 $text = tag_normalize($text);
671 $query = "
672 SELECT
673 tg.id, tg.name, tg.rawname
674 FROM
675 {$CFG->prefix}tag tg
676 WHERE
677 tg.name
678 LIKE
679 '{$text}%'
682 return get_records_sql($query, $limitfrom , $limitnum);
686 * Returns tags related to a tag
688 * Related tags of a tag come from two sources:
689 * - manually added related tags, which are tag_instance entries for that tag
690 * - correlated tags, which are a calculated
692 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
693 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
694 * @return mixed an array of tag objects
697 function related_tags($tag_name_or_id, $limitnum=10) {
699 $tag_id = tag_id_from_string($tag_name_or_id);
701 //gets the manually added related tags
702 $manual_related_tags = get_item_tags('tag',$tag_id, DEFAULT_TAG_TABLE_FIELDS);
703 if ($manual_related_tags == false) $manual_related_tags = array();
705 //gets the correlated tags
706 $automatic_related_tags = correlated_tags($tag_id);
707 if ($automatic_related_tags == false) $automatic_related_tags = array();
709 $related_tags = array_merge($manual_related_tags,$automatic_related_tags);
711 return array_slice( object_array_unique($related_tags) , 0 , $limitnum );
717 * Returns the correlated tags of a tag
718 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
720 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
721 * @return mixed an array of tag objects
723 function correlated_tags($tag_name_or_id) {
725 $tag_id = tag_id_from_string($tag_name_or_id);
727 if (!$tag_correlation = get_record('tag_correlation','tagid',$tag_id)) {
728 return array();
731 $tags_id_csv_with_apos = stripcslashes($tag_correlation->correlatedtags);
733 return get_records_select('tag', "id IN ({$tags_id_csv_with_apos})", '', DEFAULT_TAG_TABLE_FIELDS);
737 * Recalculates tag correlations of all the tags associated with an item
738 * This function could be called whenever the tags associations with an item changes
739 * ( for example when tag_an_item() or untag_an_item() is called )
741 * @param string $item_type name of the table where the item is stored. Ex: 'user'
742 * @param string $item_id id of the item
744 function update_tag_correlations($item_type, $item_id) {
746 $item_tags = get_item_tags($item_type, $item_id);
748 foreach ($item_tags as $tag) {
749 cache_correlated_tags($tag->id);
754 * Calculates and stores the correlated tags of a tag.
755 * The correlations are stored in the 'tag_correlation' table.
757 * Two tags are correlated if they appear together a lot.
758 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
760 * The rationale for the 'tag_correlation' table is performance.
761 * It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
762 * So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
764 * @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
765 * @param number $min_correlation cutoff percentage (optional, default is 0.25)
766 * @param int $limitnum return a subset comprising this many records (optional, default is 10)
768 function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
770 global $CFG;
772 $tag_id = tag_id_from_string($tag_name_or_id);
774 // query that counts how many times any tag appears together in items
775 // with the tag passed as argument ($tag_id)
776 $query =
777 " SELECT
778 tb.tagid , COUNT(*) nr
779 FROM
780 {$CFG->prefix}tag_instance ta
781 INNER JOIN
782 {$CFG->prefix}tag_instance tb
784 ta.itemid = tb.itemid
785 WHERE
786 ta.tagid = {$tag_id}
787 GROUP BY
788 tb.tagid
789 ORDER BY
790 nr DESC";
792 $tag_correlations = get_records_sql($query, 0, $limitnum);
794 $tags_id_csv_with_apos = "'";
795 $cutoff = $tag_correlations[$tag_id]->nr * $min_correlation;
797 foreach($tag_correlations as $correlation) {
798 if($correlation->nr >= $cutoff && $correlation->tagid != $tag_id ){
799 $tags_id_csv_with_apos .= $correlation->tagid."','";
802 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
805 //saves correlation info in the caching table
807 $tag_correlation_obj = get_record('tag_correlation','tagid',$tag_id);
809 if ($tag_correlation_obj) {
810 $tag_correlation_obj->correlatedtags = addslashes($tags_id_csv_with_apos);
811 update_record('tag_correlation',$tag_correlation_obj);
813 else {
814 $tag_correlation_obj = new StdClass;
815 $tag_correlation_obj->tagid = $tag_id;
816 $tag_correlation_obj->correlatedtags = addslashes($tags_id_csv_with_apos);
817 insert_record('tag_correlation',$tag_correlation_obj);
824 * This function cleans up the 'tag_instance' table
825 * It removes orphans in 'tag_instances' table
828 function tag_instance_table_cleanup() {
830 global $CFG;
832 //get the itemtypes present in the 'tag_instance' table
833 $query = "
834 SELECT
835 DISTINCT(itemtype)
836 FROM
837 {$CFG->prefix}tag_instance
840 $items_types = get_records_sql($query);
842 // for each itemtype, remove tag_instances that are orphans
843 // That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
844 // then this tag_instance is an orphan and it will be removed.
845 foreach ($items_types as $type) {
847 $query = "
848 {$CFG->prefix}tag_instance.id
850 ( SELECT sq1.id
851 FROM
852 (SELECT sq2.*
853 FROM {$CFG->prefix}tag_instance sq2
854 LEFT JOIN {$CFG->prefix}{$type->itemtype} item
855 ON sq2.itemid = item.id
856 WHERE item.id IS NULL
857 AND sq2.itemtype = '{$type->itemtype}')
859 ) ";
861 delete_records_select('tag_instance', $query);
864 // remove tag_instances that are orphans because tagid does not correspond to an
865 // existing tag
866 $query = "
867 {$CFG->prefix}tag_instance.id
869 (SELECT sq1.id
870 FROM
871 (SELECT sq2.*
872 FROM {$CFG->prefix}tag_instance sq2
873 LEFT JOIN {$CFG->prefix}tag tg
874 ON sq2.tagid = tg.id
875 WHERE tg.id IS NULL )
880 delete_records_select('tag_instance', $query);
885 * Function that normalizes a tag name
887 * Ex: tag_normalize('bANAana') -> returns 'banana'
888 * tag_normalize('lots of spaces') -> returns 'lots of spaces'
889 * tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
890 * tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
891 * -> returns 'tag one,tag two,tag three,and another tag'
893 * @param string $tag_names_csv unnormalized CSV tag names
894 * @return string **normalized** CSV tag names
897 function tag_normalize($tag_names_csv, $lowercase=true) {
899 $tags = explode(',', $tag_names_csv);
901 if (sizeof($tags) > 1) {
903 foreach ($tags as $key => $tag) {
904 $tags[$key] = tag_normalize($tag);
907 return implode(',' , $tags);
911 // only one tag was passed
912 else {
914 if ($lowercase){
915 $value = moodle_strtolower($tag_names_csv);
917 else {
918 $value = $tag_names_csv;
921 //$value = preg_replace('|[^\w ]|i', '', strtolower(trim($tag_names_csv)));
922 $value = preg_replace('|[\!\@\#\$\%\^\&\*\(\)\-\+\=\~\`\\"\'\_.\[\]\{\}\:\;\?\´\^\\\/\<\>\|]|i', '', trim($value));
924 //removes excess white spaces
925 $value = preg_replace('/\s\s+/', ' ', $value);
927 return $value;
932 function tag_flag_inappropriate($tag_names_or_ids_csv){
934 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
936 $tag_ids = explode(',', $tag_ids_csv);
938 foreach ($tag_ids as $id){
939 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
941 $tag->flag++;
942 $tag->timemodified = time();
944 update_record('tag', $tag);
948 function tag_flag_reset($tag_names_or_ids_csv){
950 global $CFG;
952 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
954 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
956 $timemodified = time();
958 $query = "
959 UPDATE
960 {$CFG->prefix}tag tg
961 SET
962 tg.flag = 0,
963 tg.timemodified = {$timemodified}
964 WHERE
965 tg.id
967 ({$tag_ids_csv_with_apos})
970 execute_sql($query, false);
974 * Function that returns comma separated HTML links to the tag pages of the tags passed
976 * @param array $tag_objects an array of tag objects
977 * @return string CSV, HTML links to tag pages
980 function tag_links_csv($tag_objects) {
982 global $CFG;
983 $tag_links = '';
985 if (empty($tag_objects)) {
986 return '';
989 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
990 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
992 foreach ($tag_objects as $tag){
993 //highlight tags that have been flagged as inappropriate for those who can manage them
994 $tagname = tag_display_name($tag);
995 if ($tag->flag > 0 && $can_manage_tags) {
996 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
998 $tag_links .= ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.$tagname.'</a>,';
1001 return rtrim($tag_links, ',');
1005 * Function that returns comma separated names of the tags passed
1006 * Example of string that might be returned: 'history, wars, greek history'
1008 * @param array $tag_objects
1009 * @return string CSV tag names
1012 function tag_names_csv($tag_objects) {
1014 if (empty($tag_objects)) {
1015 return '';
1018 $tags = array();
1020 foreach ($tag_objects as $tag){
1021 $tags[] = tag_display_name($tag);
1024 return implode(', ', $tags);
1029 * Returns a number of random tags, ordered by their popularity
1031 * @param int $nr_of_tags number of random tags to be returned
1032 * @param unknown_type $tag_type
1033 * @return mixed an array of tag objects with the following fields: id, name and count
1035 function rand_tags_count($nr_of_tags=20, $tag_type = 'default') {
1037 global $CFG;
1039 if (!$tags = get_all_tags($tag_type)) {
1040 return array();
1043 if(sizeof($tags) < $nr_of_tags) {
1044 $nr_of_tags = sizeof($tags);
1047 $rndtags = array_rand($tags, $nr_of_tags);
1049 $tags_id_csv_with_apos = "'";
1050 foreach($rndtags as $tagid) {
1051 $tags_id_csv_with_apos .= $tags[$tagid]->id . "','";
1053 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
1056 $query = "
1057 SELECT
1058 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, tg.flag
1059 FROM
1060 {$CFG->prefix}tag_instance ti
1061 INNER JOIN
1062 {$CFG->prefix}tag tg
1064 tg.id = ti.tagid
1065 WHERE
1066 ti.tagid
1068 ({$tags_id_csv_with_apos})
1069 GROUP BY
1070 tagid
1071 ORDER BY
1072 count
1073 ASC";
1075 return get_records_sql($query);
1080 function tag_cron(){
1082 tag_instance_table_cleanup();
1084 $tags = get_all_tags('*');
1086 foreach ($tags as $tag){
1087 cache_correlated_tags($tag->id);
1091 /*-------------------- Printing functions -------------------- */
1094 * Prints a box that contains the management links of a tag
1096 * @param $tag_object
1099 function print_tag_management_box($tag_object) {
1101 global $USER, $CFG;
1103 $tagname = tag_display_name($tag_object);
1105 print_box_start('box','tag-management-box');
1107 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1109 $addtaglink = '';
1110 if ( has_capability('moodle/tag:manage',$systemcontext) ) {
1111 $manage_link = "<a href=\"{$CFG->wwwroot}/tag/manage.php\">" . get_string('managetags', 'tag') . "</a>" ;
1112 echo $manage_link .' | ';
1115 // if the user is not tagged with the $tag_object tag, a link "add blahblah to my interests" will appear
1116 if( !is_item_tagged_with('user', $USER->id, $tag_object->id )) {
1117 $addtaglink = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=addinterest&amp;id='. $tag_object->id .'">';
1118 $addtaglink .= get_string('addtagtomyinterests','tag',$tagname). '</a>';
1119 echo $addtaglink .' | ';
1122 // only people with moodle/tag:edit capability may edit the tag description
1123 if ( has_capability('moodle/tag:edit',$systemcontext) && is_item_tagged_with('user', $USER->id, $tag_object->id ) ) {
1124 echo ' <a href="'. $CFG->wwwroot . '/tag/edit.php?id='.$tag_object->id .'">'.get_string('edittag', 'tag').'</a> | ';
1127 // flag as inappropriate link
1128 $flagtaglink = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=flaginappropriate&amp;id='. $tag_object->id .'">';
1129 $flagtaglink .= get_string('flagasinappropriate','tag',$tagname). '</a>';
1130 echo $flagtaglink;
1132 print_box_end();
1137 * Prints a box with the description of a tag and its related tags
1139 * @param unknown_type $tag_object
1142 function print_tag_description_box($tag_object) {
1144 global $USER, $CFG;
1146 $tagname = tag_display_name($tag_object);
1147 $related_tags = related_tags($tag_object->id); //get_item_tags('tags',$tag_object->id);
1150 print_box_start('generalbox', 'tag-description');
1152 if (!empty($tag_object->description)) {
1153 $options = new object;
1154 $options->para=false;
1155 echo format_text($tag_object->description, $tag_object->descriptionformat, $options );
1157 else {
1158 echo format_text(get_string('thistaghasnodesc','tag'));
1161 if ($related_tags) {
1162 echo '<br/><br/><b>'.get_string('relatedtags','tag').': </b>' . tag_links_csv($related_tags);
1165 print_box_end();
1169 * Prints a table of the users tagged with the tag passed as argument
1171 * @param $tag_object
1172 * @param int $users_per_row number of users per row to display
1173 * @param int $limitfrom prints users starting at this point (optional, required if $limitnum is set).
1174 * @param int $limitnum prints this many users (optional, required if $limitfrom is set).
1177 function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='') {
1179 //List of users with this tag
1180 $userlist = array_values( get_items_tagged_with(
1181 'user',
1182 $tag_object->id,
1183 'lastaccess DESC' ,
1184 'id, firstname, lastname, picture',
1185 $limitfrom,
1186 $limitnum) );
1188 //user table box
1189 print_box_start('generalbox', 'tag-user-table');
1191 print_user_list($userlist);
1193 print_box_end();
1194 //end table box
1201 * Prints a list of users
1203 * @param array $userlist an array of user objects
1205 function print_user_list($userlist) {
1207 foreach ($userlist as $user){
1208 print_user_box( $user );
1215 * Prints an individual user box
1217 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
1219 function print_user_box($user) {
1221 global $CFG;
1223 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1225 $profilelink = '';
1226 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1227 $profilelink = $CFG->wwwroot.'/user/view.php?id='.$user->id;
1230 print_box_start('user-box', 'user'.$user->id);
1232 if (!empty($profilelink)) {
1233 echo '<a href="'.$profilelink.'">';
1236 //print user image
1237 if ($user->picture) {
1238 echo '<img alt="" class="user-image" src="'. $CFG->wwwroot .'/user/pix.php/'. $user->id .'/f1.jpg"'.'/>';
1239 } else {
1240 echo '<img alt="" class="user-image" src="'. $CFG->wwwroot .'/pix/u/f1.png"'.'/>';
1243 echo '<br />';
1245 if (!empty($profilelink)) {
1246 echo '</a>';
1249 $fullname = fullname($user);
1250 //truncate name if it's too big
1251 if (strlen($fullname) > 26) $fullname = substr($fullname,0,26) . '...';
1253 echo '<strong>' . $fullname . '</strong>';
1255 print_box_end();
1260 * Prints the tag search box
1263 function print_tag_search_box($search='') {
1265 global $CFG;
1267 print_box_start('','tag-search-box');
1269 echo '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
1270 echo '<div>';
1271 echo '<input id="searchform_search" name="query" type="text" size="40" />';
1272 echo '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
1273 echo '</div>';
1274 echo '</form>';
1276 print_box_end();
1280 * Prints the tag search results
1282 * @param string $query text that tag names will be matched against
1283 * @param int $page current page
1284 * @param int $perpage nr of users displayed per page
1286 function print_tag_search_results($query, $page, $perpage) {
1288 global $CFG, $USER;
1290 $count = sizeof( search_tags($query,false) );
1291 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
1293 $baseurl = $CFG->wwwroot.'/tag/search.php?query=' . $query;
1295 // link "Add $query to my interests"
1296 $addtaglink = '';
1297 if( !is_item_tagged_with('user', $USER->id, $query )) {
1298 $addtaglink = '<a href="' . $CFG->wwwroot . '/user/tag.php?action=addinterest&name='. $query .'">';
1299 $addtaglink .= get_string('addtagtomyinterests','tag',$query). '</a>';
1303 if($tags) { // there are results to display!!
1305 print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3);
1307 //print a link "Add $query to my interests"
1308 if (!empty($addtaglink)) {
1309 print_box($addtaglink,'box','tag-management-box');
1312 $nr_of_lis_per_ul = 6;
1313 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
1315 echo '<ul id="tag-search-results">';
1316 for($i = 0; $i < $nr_of_uls; $i++) {
1317 echo '<li>';
1318 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul ) as $tag) {
1319 $tag_link = ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.tag_display_name($tag).'</a>';
1320 echo '&#8226;' . $tag_link . '<br/>';
1322 echo '</li>';
1324 echo '</ul>';
1325 echo '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
1327 print_paging_bar($count, $page, $perpage, $baseurl.'&amp;', 'page');
1329 else { //no results were found!!
1331 print_heading(get_string('noresultsfor', 'tag', $query), '', 3);
1333 //print a link "Add $query to my interests"
1334 if (!empty($addtaglink)) {
1335 print_box($addtaglink,'box','tag-management-box');
1344 * Prints a tag cloud
1346 * @param array $tagcloud array of tag objects (fields: id, name, rawname, count and flag)
1347 * @param boolean $shuffle wether or not to shuffle the array passed
1348 * @param int $max_size maximum text size, in percentage
1349 * @param int $min_size minimum text size, in percentage
1351 function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80) {
1353 global $CFG;
1355 if (empty($tagcloud)) {
1356 return;
1359 if ( $shuffle ) {
1360 shuffle($tagcloud);
1363 $count = array();
1364 foreach ($tagcloud as $key => $value){
1365 if(!empty($value->count)) {
1366 $count[$key] = log10($value->count);
1368 else{
1369 $count[$key] = 0;
1373 $max = max($count);
1374 $min = min($count);
1376 $spread = $max - $min;
1377 if (0 == $spread) { // we don't want to divide by zero
1378 $spread = 1;
1381 $step = ($max_size - $min_size)/($spread);
1383 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1384 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1386 //prints the tag cloud
1387 echo '<ul id="tag-cloud-list">';
1388 foreach ($tagcloud as $key => $tag) {
1390 $size = $min_size + ((log10($tag->count) - $min) * $step);
1391 $size = ceil($size);
1393 $style = 'style="font-size: '.$size.'%"';
1394 $title = 'title="'.s(get_string('thingstaggedwith','tag', $tag)).'"';
1395 $href = 'href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'"';
1397 //highlight tags that have been flagged as inappropriate for those who can manage them
1398 $tagname = tag_display_name($tag);
1399 if ($tag->flag > 0 && $can_manage_tags) {
1400 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
1403 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
1405 echo $tag_link;
1408 echo '</ul>';
1412 function print_tag_management_list($perpage='100') {
1414 global $CFG, $USER;
1415 require_once($CFG->libdir.'/tablelib.php');
1417 //setup table
1419 $tablecolumns = array('id','name', 'owner', 'count', 'flag', 'timemodified', '');
1420 $tableheaders = array( get_string('id' , 'tag'),
1421 get_string('name' , 'tag'),
1422 get_string('owner','tag'),
1423 get_string('count','tag'),
1424 get_string('flag','tag'),
1425 get_string('timemodified','tag'),
1426 get_string('select', 'tag')
1429 $table = new flexible_table('tag-management-list-'.$USER->id);
1431 $baseurl = $CFG->wwwroot.'/tag/manage.php';
1433 $table->define_columns($tablecolumns);
1434 $table->define_headers($tableheaders);
1435 $table->define_baseurl($baseurl);
1437 $table->sortable(true, 'flag', SORT_DESC);
1439 $table->set_attribute('cellspacing', '0');
1440 $table->set_attribute('id', 'tag-management-list');
1441 $table->set_attribute('class', 'generaltable generalbox');
1443 $table->set_control_variables(array(
1444 TABLE_VAR_SORT => 'ssort',
1445 TABLE_VAR_HIDE => 'shide',
1446 TABLE_VAR_SHOW => 'sshow',
1447 TABLE_VAR_IFIRST => 'sifirst',
1448 TABLE_VAR_ILAST => 'silast',
1449 TABLE_VAR_PAGE => 'spage'
1452 $table->setup();
1454 if ($table->get_sql_sort()) {
1455 $sort = ' ORDER BY '.$table->get_sql_sort();
1456 } else {
1457 $sort = '';
1460 if ($table->get_sql_where()) {
1461 $where = 'WHERE '.$table->get_sql_where();
1462 } else {
1463 $where = '';
1466 $query = "
1467 SELECT
1468 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, u.id AS owner, tg.flag, tg.timemodified
1469 FROM
1470 {$CFG->prefix}tag_instance ti
1471 RIGHT JOIN
1472 {$CFG->prefix}tag tg
1474 tg.id = ti.tagid
1475 LEFT JOIN
1476 {$CFG->prefix}user u
1478 tg.userid = u.id
1479 {$where}
1480 GROUP BY
1481 tg.id
1482 {$sort}
1485 $totalcount = count_records('tag');
1487 $table->initialbars($totalcount > $perpage);
1488 $table->pagesize($perpage, $totalcount);
1491 echo '<form id="tag-management-form" method="post" action="'.$CFG->wwwroot.'/tag/manage.php">';
1493 //retrieve tags from DB
1494 if ($tagrecords = get_records_sql($query, $table->get_page_start(), $table->get_page_size())) {
1496 $taglist = array_values($tagrecords);
1498 //print_tag_cloud(array_values(get_records_sql($query)), false);
1500 //populate table with data
1501 foreach ($taglist as $tag ){
1503 $id = $tag->id;
1504 $name = '<a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'. tag_display_name($tag) .'</a>';
1505 $owner = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$tag->owner.'">' . $tag->owner . '</a>';
1506 $count = $tag->count;
1507 $flag = $tag->flag;
1508 $timemodified = format_time(time() - $tag->timemodified);
1509 $checkbox = '<input type="checkbox" name="tagschecked[]" value="'.$tag->id.'" />';
1511 //if the tag if flagged, highlight it
1512 if ($tag->flag > 0) {
1513 $id = '<span class="flagged-tag">' . $id . '</span>';
1514 $name = '<span class="flagged-tag">' . $name . '</span>';
1515 $owner = '<span class="flagged-tag">' . $owner . '</span>';
1516 $count = '<span class="flagged-tag">' . $count . '</span>';
1517 $flag = '<span class="flagged-tag">' . $flag . '</span>';
1518 $timemodified = '<span class="flagged-tag">' . $timemodified . '</span>';
1521 $data = array($id, $name , $owner ,$count ,$flag, $timemodified, $checkbox);
1523 $table->add_data($data);
1527 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
1528 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
1529 echo '<br/><br/>';
1530 echo '<select id="menuformaction" name="action">
1531 <option value="" selected="selected">'. get_string('withselectedtags', 'tag') .'</option>
1532 <option value="reset">'. get_string('resetflag', 'tag') .'</option>
1533 <option value="delete">'. get_string('delete', 'tag') .'</option>
1534 </select>';
1536 echo '<button id="tag-management-submit" type="submit">'. get_string('ok') .'</button>';
1540 $table->print_html();
1542 echo '</form>';