MDL-10260 added new user_delete() hook into auth plugins; refactored user delete...
[moodle.git] / tag / lib.php
CommitLineData
c933a060 1<?php // $Id$
2
96ddd872 3require_once(dirname(__FILE__) . '/../config.php');
c933a060 4
b3541b6a 5define('DEFAULT_TAG_TABLE_FIELDS', 'id, tagtype, name, rawname, flag');
c933a060 6/**
7 * Creates tags
8
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'
13 *
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
17 */
18function tag_create($tag_names_csv, $tag_type="default") {
19 global $USER;
20
4f81c51d 21 $tags = explode(",", $tag_names_csv );
c933a060 22
23 $tag_object = new StdClass;
24 $tag_object->tagtype = $tag_type;
25 $tag_object->userid = $USER->id;
26
27 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
28 $can_create_tags = has_capability('moodle/tag:create',$systemcontext);
29
4f81c51d 30 $norm_tag_names_csv = '';
31 foreach ($tags as $tag) {
c933a060 32
4f81c51d 33 // rawname keeps the original casing of the string
34 $tag_object->rawname = tag_normalize($tag, false);
35
26d8649f 36 // name lowercases the string
4f81c51d 37 $tag_object->name = tag_normalize($tag);
38 $norm_tag_names_csv .= $tag_object->name . ',';
26d8649f 39
40 $tag_object->timemodified = time();
4f81c51d 41
26d8649f 42 $exists = record_exists('tag', 'name', $tag_object->name);
43
44 if ( $can_create_tags && !$exists && !empty($tag_object->name) && !is_numeric($tag_object->name) ) {
c933a060 45 insert_record('tag', $tag_object);
46 }
47 }
48
4f81c51d 49 $norm_tag_names_csv = substr($norm_tag_names_csv,0,-1);
50
51 return tags_id( $norm_tag_names_csv );
c933a060 52
53}
54
55/**
56 * Deletes tags
57 *
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!
60 *
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.
63 *
64 *
65 * @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
66 */
67
68function tag_delete($tag_names_or_ids_csv) {
69
70 //covert all ids to names
71 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
72
73 //put apostrophes in names
74 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $tag_names_csv) . "'";
75
76 delete_records_select('tag',"name IN ($tag_names_csv_with_apos)");
77
78}
79
80/**
81 * Get all tags from the records
82 *
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
b3541b6a 86 * (optional, by default 'id, tagtype, name, rawname, flag'). The first field will be used as key for the
c933a060 87 * array so must be a unique field such as 'id'.
88 */
b3541b6a 89function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields=DEFAULT_TAG_TABLE_FIELDS) {
c933a060 90
91 if ($tag_types_csv == '*'){
92 return get_records('tag', '', '', $sort, $fields);
93 }
94
95 $tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
96
97 return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
98}
99
100/**
101 * Determines if a tag exists
102 *
103 * @param string $tag_name_or_id **normalized** tag name, or an id.
104 * @return true if exists or false otherwise
105 *
106 */
107function tag_exists($tag_name_or_id) {
108
109 if (is_numeric($tag_name_or_id)) {
110 return record_exists('tag', 'id', $tag_name_or_id);
111 }
112 elseif (is_string($tag_name_or_id)) {
113 return record_exists('tag', 'name', $tag_name_or_id);
114 }
115}
116
117/**
118 * Function that returns the id of a tag
119 *
120 * @param String $tag_name **normalized** name of the tag
121 * @return int id of the matching tag
122 */
123function tag_id($tag_name) {
124 $tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
4f81c51d 125
126 if ($tag){
127 return $tag->id;
128 }
129 else{
130 return false;
131 }
c933a060 132}
133
134/**
135 * Function that returns the ids of tags
136 *
137 * Ex: tags_id('computers, algorithms')
138 *
139 * @param String $tag_names_csv comma separated **normalized** tag names.
140 * @return Array array with the tags ids, indexed by their **normalized** names
141 */
142function tags_id($tag_names_csv) {
143
144 $normalized_tag_names_csv = tag_normalize($tag_names_csv);
145 $tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
146
147 $tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" );
148
149 $tags_ids = array();
150 foreach ($tag_objects as $tag) {
151 $tags_ids[$tag->name] = $tag->id;
152 }
153
154 return $tags_ids;
155}
156
157/**
158 * Function that returns the name of a tag
159 *
160 * @param int $tag_id id of the tag
161 * @return String name of the tag with the id passed
162 */
163function tag_name($tag_id) {
164 $tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
4f81c51d 165
166 if ($tag){
167 return $tag->name;
168 }
169 else{
170 return '';
171 }
c933a060 172}
173
174/**
175 * Function that retrieves the names of tags given their ids
176 *
177 * @param String $tag_ids_csv comma separated tag ids
178 * @return Array an array with the tags names, indexed by their ids
179 */
180
181function tags_name($tag_ids_csv) {
182
4f81c51d 183 //remove any white spaces
184 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
185
c933a060 186 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
187
188 $tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
189
190 $tags_names = array();
191 foreach ($tag_objects as $tag) {
192 $tags_names[$tag->id] = $tag->name;
193 }
194
195 return $tags_names;
196}
197
4f81c51d 198/**
199 * Function that returns the name of a tag for display.
200 *
201 * @param mixed $tag_object
202 * @return string
203 */
204function tag_display_name($tag_object){
205
206 global $CFG;
207
c91146b9 208 if( empty($CFG->keeptagnamecase) ) {
4f81c51d 209 //this is the normalized tag name
210 return mb_convert_case($tag_object->name, MB_CASE_TITLE,"UTF-8");
211 }
212 else {
213 //original casing of the tag name
214 return $tag_object->rawname;
215 }
216
217}
218
c933a060 219/**
220 * Function that retrieves a tag object by its id
221 *
222 * @param String $tag_id
223 * @return mixed a fieldset object containing the first matching record, or false if none found
224 */
225function tag_by_id($tag_id) {
226
227 return get_record('tag','id',$tag_id);
228}
229
230/**
231 * Function that retrieves a tag object by its name
232 *
233 * @param String $tag_name
234 * @return mixed a fieldset object containing the first matching record, or false if none found
235 */
236function tag_by_name($tag_name) {
237 $tag = get_record('tag','name',$tag_name);
238 return $tag;
239}
240
241/**
4f81c51d 242 * In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
c933a060 243 *
4f81c51d 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
c933a060 250 *
4f81c51d 251 * tag_id_from_string('moodle, 12, education, programming, 33, 11')
252 * will return '10,12,22,,33,11'
253 *
c933a060 254 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
255 *
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
258 */
259function tag_id_from_string($tag_names_or_ids_csv) {
260
261 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
262
263 $tag_ids = array();
264 foreach ($tag_names_or_ids as $name_or_id) {
265
266 if (is_numeric($name_or_id)){
4f81c51d 267 $tag_ids[] = trim($name_or_id);
c933a060 268 }
269 elseif (is_string($name_or_id)) {
270 $tag_ids[] = tag_id( $name_or_id );
271 }
272
273 }
274
275 $tag_ids_csv = implode(',',$tag_ids);
276 $tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
277
4f81c51d 278 return $tag_ids_csv;
c933a060 279}
280
281/**
4f81c51d 282 * In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
283 *
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
c933a060 290 *
4f81c51d 291 * tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
292 * will return the string 'mOOdle,moodle,HiStOrY,,education'
c933a060 293 *
294 * This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
295 *
b3541b6a 296 * @param string $tag_names_or_ids_csv comma separated names or ids of tags
297 * @return int comma separated names of the tags
c933a060 298 */
299function tag_name_from_string($tag_names_or_ids_csv) {
300
301 $tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
302
303 $tag_names = array();
304 foreach ($tag_names_or_ids as $name_or_id) {
305
306 if (is_numeric($name_or_id)){
307 $tag_names[] = tag_name($name_or_id);
308 }
309 elseif (is_string($name_or_id)) {
4f81c51d 310 $tag_names[] = trim($name_or_id);
c933a060 311 }
312
313 }
314
315 $tag_names_csv = implode(',',$tag_names);
316
4f81c51d 317 return $tag_names_csv;
c933a060 318
319}
320
321/**
322 * Associates a tag with an item
323 *
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.
327 *
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
330 *
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")
335 */
336
337function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
338
c933a060 339 //convert any tag ids passed to their corresponding tag names
4f81c51d 340 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
c933a060 341
342 //create the tags
343 $tags_created_ids = tag_create($tag_names_csv,$tag_type);
344
345 $tag_instance = new StdClass;
346 $tag_instance->itemtype = $item_type;
347 $tag_instance->itemid = $item_id;
348
349 //create tag instances
350 foreach ($tags_created_ids as $tag_id) {
26d8649f 351
c933a060 352 $tag_instance->tagid = $tag_id;
26d8649f 353
354 $exists = record_exists('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
355
356 if (!$exists) {
357 insert_record('tag_instance',$tag_instance);
358 }
c933a060 359 }
360
361
362 // update_tag_correlations($item_type, $item_id);
363
364}
365
366
367/**
368 * Updates the tags associated with an item
369 *
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"
374 *
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
378 *
379 *
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")
384 */
385
386function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
387
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;
392 }
393
c933a060 394 //convert any tag ids passed to their corresponding tag names
4f81c51d 395 $tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
c933a060 396
397 //associate the tags passed with the item
398 tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
399
400 //get the ids of the tags passed
4f81c51d 401 $existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
c933a060 402
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) . "'" ;
406
407 $select = "
408 itemid = '{$item_id}'
409 AND
410 itemtype = '{$item_type}'
411 AND
412 tagid NOT IN ({$tags_id_csv})
413 ";
414
415 delete_records_select('tag_instance', $select);
416
417}
418
419/**
420 * Removes the association of an item with a tag
421 *
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.
425 *
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)
430 */
431
432function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
433
434 if ($tag_names_or_ids_csv == ""){
435
436 delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
437
438 }
439 else {
440
441 $tag_ids_csv = tag_id_from_string($norm_tag_names_or_ids_csv);
442
443 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
444
445 delete_records_select('tag_instance',
446 "tagid IN ($tags_id_csv_with_apos) AND itemtype='$item_type' AND itemid='$item_id'");
447 }
448
449 //update_tag_correlations($item_type, $item_id);
450
451}
452
453/**
454 * Function that gets the tags that are associated with an item
455 *
456 * Ex: get_item_tags('user', '1')
457 *
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
b3541b6a 460 * @param string $fields tag fields to be selected (optional, default is 'id, name, rawname, tagtype, flag')
c933a060 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.
464 */
465
b3541b6a 466function get_item_tags($item_type, $item_id, $fields=DEFAULT_TAG_TABLE_FIELDS, $limitfrom='', $limitnum='') {
c933a060 467
468 global $CFG;
469
470 $fields = 'tg.' . $fields;
471 $fields = str_replace(',', ',tg.', $fields);
472
473 $query = "
474 SELECT
475 {$fields}
476 FROM
477 {$CFG->prefix}tag_instance ti
478 INNER JOIN
479 {$CFG->prefix}tag tg
480 ON
481 tg.id = ti.tagid
482 WHERE
483 ti.itemtype = '{$item_type}' AND
484 ti.itemid = '{$item_id}'";
485
486 return get_records_sql($query, $limitfrom, $limitnum);
487
488}
489
490
491
492/**
493 * Function that returns the items of a certain type associated with a certain tag
494 *
495 * Ex 1: get_items_tagged_with('user', 'banana')
496 * Ex 2: get_items_tagged_with('user', '11')
497 *
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
4f81c51d 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' )
c933a060 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.
509 */
510
511function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
512
513 global $CFG;
514
515 $tag_id = tag_id_from_string($tag_name_or_id);
516
517 $fields = 'it.' . $fields;
518 $fields = str_replace(',', ',it.', $fields);
519
520 if ($sort) {
521 $sort = ' ORDER BY '. $sort;
522 }
523
524 $query = "
525 SELECT
526 {$fields}
527 FROM
528 {$CFG->prefix}{$item_type} it
529 INNER JOIN
530 {$CFG->prefix}tag_instance tt
531 ON
532 it.id = tt.itemid
533 WHERE
534 tt.itemtype = '{$item_type}' AND
535 tt.tagid = '{$tag_id}'
536 {$sort}
537 ";
538
539
540 return get_records_sql($query, $limitfrom, $limitnum);
541
542}
543
544/**
545 * Returns the number of items tagged with a tag
546 *
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.
551 */
552function count_items_tagged_with($tag_name_or_id, $item_type='') {
553
554 global $CFG;
555
556 $tag_id = tag_id_from_string($tag_name_or_id);
557
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}";
566 }
567 else
568 {
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
576 ON
577 it.id = tt.itemid
578 WHERE
579 tt.itemtype = '{$item_type}' AND
580 tt.tagid = '{$tag_id}' ";
581 }
582
583
584 return count_records_sql($query);
585
586}
587
588
589/**
590 * Determines if an item is tagged with a certain tag
591 *
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.
596 */
597function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
598
599 $tag_id = tag_id_from_string($tag_name_or_id);
600
601 return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
602}
603
604/**
605 * Search for tags with names that match some text
606 *
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.
612 */
613
614function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
615
616 global $CFG;
617
618 $text = tag_normalize($text);
619
620 if ($ordered) {
621 $query = "
622 SELECT
4f81c51d 623 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
c933a060 624 FROM
625 {$CFG->prefix}tag tg
626 LEFT JOIN
627 {$CFG->prefix}tag_instance ti
628 ON
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
4f81c51d 642 tg.id, tg.name, tg.rawname
c933a060 643 FROM
644 {$CFG->prefix}tag tg
645 WHERE
646 tg.name
647 LIKE
648 '%{$text}%'
649 ";
650 }
651
652
653 return get_records_sql($query, $limitfrom , $limitnum);
654
655}
656
657/**
658 * Function that returns tags that start with some text
659 *
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.
664 */
665function similar_tags($text, $limitfrom='' , $limitnum='' ) {
666
667 global $CFG;
668
669 $text = tag_normalize($text);
670
671 $query = "
672 SELECT
4f81c51d 673 tg.id, tg.name, tg.rawname
c933a060 674 FROM
4f81c51d 675 {$CFG->prefix}tag tg
c933a060 676 WHERE
4f81c51d 677 tg.name
c933a060 678 LIKE
679 '{$text}%'
680 ";
681
682 return get_records_sql($query, $limitfrom , $limitnum);
683}
684
685/**
686 * Returns tags related to a tag
687 *
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
691 *
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
695 */
696
697function related_tags($tag_name_or_id, $limitnum=10) {
698
699 $tag_id = tag_id_from_string($tag_name_or_id);
700
701 //gets the manually added related tags
b3541b6a 702 $manual_related_tags = get_item_tags('tag',$tag_id, DEFAULT_TAG_TABLE_FIELDS);
c933a060 703 if ($manual_related_tags == false) $manual_related_tags = array();
704
705 //gets the correlated tags
706 $automatic_related_tags = correlated_tags($tag_id);
707 if ($automatic_related_tags == false) $automatic_related_tags = array();
708
709 $related_tags = array_merge($manual_related_tags,$automatic_related_tags);
710
711 return array_slice( object_array_unique($related_tags) , 0 , $limitnum );
712
713
714}
715
716/**
717 * Returns the correlated tags of a tag
718 * The correlated tags are retrieved from the tag_correlation table, which is a caching table.
719 *
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
722 */
723function correlated_tags($tag_name_or_id) {
724
725 $tag_id = tag_id_from_string($tag_name_or_id);
726
727 if (!$tag_correlation = get_record('tag_correlation','tagid',$tag_id)) {
728 return array();
729 }
730
731 $tags_id_csv_with_apos = stripcslashes($tag_correlation->correlatedtags);
732
b3541b6a 733 return get_records_select('tag', "id IN ({$tags_id_csv_with_apos})", '', DEFAULT_TAG_TABLE_FIELDS);
c933a060 734}
735
736/**
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 )
740 *
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
743 */
744function update_tag_correlations($item_type, $item_id) {
745
746 $item_tags = get_item_tags($item_type, $item_id);
747
748 foreach ($item_tags as $tag) {
749 cache_correlated_tags($tag->id);
750 }
751}
752
753/**
754 * Calculates and stores the correlated tags of a tag.
755 * The correlations are stored in the 'tag_correlation' table.
756 *
757 * Two tags are correlated if they appear together a lot.
758 * Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
759 *
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.
763 *
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)
767 */
768function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
769
770 global $CFG;
771
772 $tag_id = tag_id_from_string($tag_name_or_id);
773
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
783 ON
784 ta.itemid = tb.itemid
785 WHERE
786 ta.tagid = {$tag_id}
787 GROUP BY
788 tb.tagid
789 ORDER BY
790 nr DESC";
791
792 $tag_correlations = get_records_sql($query, 0, $limitnum);
793
794 $tags_id_csv_with_apos = "'";
795 $cutoff = $tag_correlations[$tag_id]->nr * $min_correlation;
796
797 foreach($tag_correlations as $correlation) {
798 if($correlation->nr >= $cutoff && $correlation->tagid != $tag_id ){
799 $tags_id_csv_with_apos .= $correlation->tagid."','";
800 }
801 }
802 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
803
804
805 //saves correlation info in the caching table
806
807 $tag_correlation_obj = get_record('tag_correlation','tagid',$tag_id);
808
809 if ($tag_correlation_obj) {
810 $tag_correlation_obj->correlatedtags = addslashes($tags_id_csv_with_apos);
811 update_record('tag_correlation',$tag_correlation_obj);
812 }
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);
818 }
819
820
821}
822
823/**
824 * This function cleans up the 'tag_instance' table
825 * It removes orphans in 'tag_instances' table
826 *
827 */
828function tag_instance_table_cleanup() {
829
830 global $CFG;
831
832 //get the itemtypes present in the 'tag_instance' table
833 $query = "
834 SELECT
835 DISTINCT(itemtype)
836 FROM
837 {$CFG->prefix}tag_instance
838 ";
839
840 $items_types = get_records_sql($query);
841
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) {
846
847 $query = "
848 {$CFG->prefix}tag_instance.id
849 IN
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}')
858 sq1
859 ) ";
860
861 delete_records_select('tag_instance', $query);
862 }
863
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
868 IN
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 )
876 sq1
877 )
878 ";
879
880 delete_records_select('tag_instance', $query);
881}
882
883
884/**
885 * Function that normalizes a tag name
886 *
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'
892 *
893 * @param string $tag_names_csv unnormalized CSV tag names
894 * @return string **normalized** CSV tag names
895 */
896
4f81c51d 897function tag_normalize($tag_names_csv, $lowercase=true) {
c933a060 898
899 $tags = explode(',', $tag_names_csv);
900
901 if (sizeof($tags) > 1) {
902
903 foreach ($tags as $key => $tag) {
904 $tags[$key] = tag_normalize($tag);
905 }
906
907 return implode(',' , $tags);
908
909 }
910
911 // only one tag was passed
912 else {
4f81c51d 913
914 if ($lowercase){
915 $value = moodle_strtolower($tag_names_csv);
916 }
917 else {
918 $value = $tag_names_csv;
919 }
920
921 //$value = preg_replace('|[^\w ]|i', '', strtolower(trim($tag_names_csv)));
5557c75a 922 $value = preg_replace('|[\!\@\#\$\%\^\&\*\(\)\-\+\=\~\`\\"\'\_.\[\]\{\}\:\;\?\ยด\^\\\/\<\>\|]|i', '', trim($value));
c933a060 923
924 //removes excess white spaces
925 $value = preg_replace('/\s\s+/', ' ', $value);
926
927 return $value;
928 }
929
930}
931
c933a060 932function tag_flag_inappropriate($tag_names_or_ids_csv){
933
934 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
935
936 $tag_ids = explode(',', $tag_ids_csv);
937
938 foreach ($tag_ids as $id){
939 $tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
940
941 $tag->flag++;
942 $tag->timemodified = time();
943
944 update_record('tag', $tag);
945 }
946}
947
948function tag_flag_reset($tag_names_or_ids_csv){
949
950 global $CFG;
951
952 $tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
953
954 $tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
955
956 $timemodified = time();
957
958 $query = "
959 UPDATE
960 {$CFG->prefix}tag tg
961 SET
962 tg.flag = 0,
963 tg.timemodified = {$timemodified}
964 WHERE
965 tg.id
966 IN
967 ({$tag_ids_csv_with_apos})
968 ";
969
970 execute_sql($query, false);
971}
972
973/**
974 * Function that returns comma separated HTML links to the tag pages of the tags passed
975 *
976 * @param array $tag_objects an array of tag objects
977 * @return string CSV, HTML links to tag pages
978 */
979
980function tag_links_csv($tag_objects) {
981
982 global $CFG;
983 $tag_links = '';
984
985 if (empty($tag_objects)) {
986 return '';
987 }
988
989 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
990 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
991
992 foreach ($tag_objects as $tag){
993 //highlight tags that have been flagged as inappropriate for those who can manage them
4f81c51d 994 $tagname = tag_display_name($tag);
c933a060 995 if ($tag->flag > 0 && $can_manage_tags) {
996 $tagname = '<span class="flagged-tag">' . $tagname . '</span>';
997 }
998 $tag_links .= ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.$tagname.'</a>,';
999 }
1000
1001 return rtrim($tag_links, ',');
1002}
1003
1004/**
1005 * Function that returns comma separated names of the tags passed
1006 * Example of string that might be returned: 'history, wars, greek history'
1007 *
1008 * @param array $tag_objects
1009 * @return string CSV tag names
1010 */
1011
1012function tag_names_csv($tag_objects) {
1013
1014 if (empty($tag_objects)) {
1015 return '';
1016 }
1017
1018 $tags = array();
1019
1020 foreach ($tag_objects as $tag){
4f81c51d 1021 $tags[] = tag_display_name($tag);
c933a060 1022 }
1023
5557c75a 1024 return implode(', ', $tags);
c933a060 1025}
1026
1027
1028/**
1029 * Returns a number of random tags, ordered by their popularity
1030 *
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
1034 */
1035function rand_tags_count($nr_of_tags=20, $tag_type = 'default') {
1036
1037 global $CFG;
1038
1039 if (!$tags = get_all_tags($tag_type)) {
1040 return array();
1041 }
1042
1043 if(sizeof($tags) < $nr_of_tags) {
1044 $nr_of_tags = sizeof($tags);
1045 }
1046
1047 $rndtags = array_rand($tags, $nr_of_tags);
1048
1049 $tags_id_csv_with_apos = "'";
1050 foreach($rndtags as $tagid) {
1051 $tags_id_csv_with_apos .= $tags[$tagid]->id . "','";
1052 }
1053 $tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
1054
1055
1056 $query = "
1057 SELECT
4f81c51d 1058 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, tg.flag
c933a060 1059 FROM
1060 {$CFG->prefix}tag_instance ti
1061 INNER JOIN
1062 {$CFG->prefix}tag tg
1063 ON
1064 tg.id = ti.tagid
1065 WHERE
1066 ti.tagid
1067 IN
1068 ({$tags_id_csv_with_apos})
1069 GROUP BY
1070 tagid
1071 ORDER BY
1072 count
1073 ASC";
1074
1075 return get_records_sql($query);
1076
1077
1078}
1079
19e41f75 1080function tag_cron(){
1081
1082 tag_instance_table_cleanup();
1083
1084 $tags = get_all_tags('*');
1085
1086 foreach ($tags as $tag){
1087 cache_correlated_tags($tag->id);
1088 }
1089
1090}
9f788215 1091/*-------------------- Printing functions -------------------- */
c933a060 1092
1093/**
1094 * Prints a box that contains the management links of a tag
1095 *
1096 * @param $tag_object
1097 */
1098
1099function print_tag_management_box($tag_object) {
1100
1101 global $USER, $CFG;
1102
4f81c51d 1103 $tagname = tag_display_name($tag_object);
c933a060 1104
1105 print_box_start('box','tag-management-box');
1106
1107 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1108
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 .' | ';
1113 }
1114
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 .' | ';
1120 }
1121
4f81c51d 1122 // only people with moodle/tag:edit capability may edit the tag description
c933a060 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> | ';
1125 }
1126
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;
1131
1132 print_box_end();
1133
1134}
1135
1136/**
1137 * Prints a box with the description of a tag and its related tags
1138 *
1139 * @param unknown_type $tag_object
1140 */
1141
1142function print_tag_description_box($tag_object) {
1143
1144 global $USER, $CFG;
1145
4f81c51d 1146 $tagname = tag_display_name($tag_object);
c933a060 1147 $related_tags = related_tags($tag_object->id); //get_item_tags('tags',$tag_object->id);
1148
c933a060 1149
bafc13f9 1150 print_box_start('generalbox', 'tag-description');
5557c75a 1151
c933a060 1152 if (!empty($tag_object->description)) {
bafc13f9 1153 $options = new object;
1154 $options->para=false;
1155 echo format_text($tag_object->description, $tag_object->descriptionformat, $options );
c933a060 1156 }
1157 else {
1158 echo format_text(get_string('thistaghasnodesc','tag'));
1159 }
1160
c933a060 1161 if ($related_tags) {
5557c75a 1162 echo '<br/><br/><b>'.get_string('relatedtags','tag').': </b>' . tag_links_csv($related_tags);
c933a060 1163 }
1164
1165 print_box_end();
1166}
1167
1168/**
1169 * Prints a table of the users tagged with the tag passed as argument
1170 *
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).
1175 */
1176
327136f7 1177function print_tagged_users_table($tag_object, $limitfrom='' , $limitnum='') {
c933a060 1178
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) );
1187
1188 //user table box
1189 print_box_start('generalbox', 'tag-user-table');
1190
327136f7 1191 print_user_list($userlist);
c933a060 1192
1193 print_box_end();
1194 //end table box
1195
1196
1197
1198}
1199
1200/**
327136f7 1201 * Prints a list of users
c933a060 1202 *
1203 * @param array $userlist an array of user objects
c933a060 1204 */
327136f7 1205function print_user_list($userlist) {
c933a060 1206
327136f7 1207 foreach ($userlist as $user){
1208 print_user_box( $user );
c933a060 1209 }
327136f7 1210
c933a060 1211
1212}
1213
1214/**
1215 * Prints an individual user box
1216 *
1217 * @param $user user object (contains the following fields: id, firstname, lastname and picture)
1218 */
1219function print_user_box($user) {
b7ff675c 1220
c933a060 1221 global $CFG;
1222
1223 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1224
1225 $profilelink = '';
1226 if ( has_capability('moodle/user:viewdetails', $usercontext) ) {
1227 $profilelink = $CFG->wwwroot.'/user/view.php?id='.$user->id;
1228 }
1229
b7ff675c 1230 print_box_start('user-box', 'user'.$user->id);
c933a060 1231
b7ff675c 1232 if (!empty($profilelink)) {
1233 echo '<a href="'.$profilelink.'">';
1234 }
1235
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"'.'/>';
1241 }
1242
1243 echo '<br />';
1244
1245 if (!empty($profilelink)) {
1246 echo '</a>';
1247 }
1248
1249 $fullname = fullname($user);
1250 //truncate name if it's too big
1251 if (strlen($fullname) > 26) $fullname = substr($fullname,0,26) . '...';
1252
1253 echo '<strong>' . $fullname . '</strong>';
c933a060 1254
1255 print_box_end();
1256
1257}
1258
1259/**
1260 * Prints the tag search box
1261 *
1262 */
1263function print_tag_search_box($search='') {
1264
1265 global $CFG;
1266
1267 print_box_start('','tag-search-box');
1268
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>';
1275
1276 print_box_end();
1277}
1278
1279/**
1280 * Prints the tag search results
1281 *
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
1285 */
1286function print_tag_search_results($query, $page, $perpage) {
1287
1288 global $CFG, $USER;
1289
1290 $count = sizeof( search_tags($query,false) );
1291 $tags = array_values(search_tags($query, true, $page * $perpage , $perpage));
1292
1293 $baseurl = $CFG->wwwroot.'/tag/search.php?query=' . $query;
1294
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>';
1300 }
1301
1302
1303 if($tags) { // there are results to display!!
1304
5557c75a 1305 print_heading(get_string('searchresultsfor', 'tag', $query) . " : {$count}", '', 3);
c933a060 1306
1307 //print a link "Add $query to my interests"
1308 if (!empty($addtaglink)) {
1309 print_box($addtaglink,'box','tag-management-box');
1310 }
1311
1312 $nr_of_lis_per_ul = 6;
1313 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul);
1314
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) {
4f81c51d 1319 $tag_link = ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.tag_display_name($tag).'</a>';
c933a060 1320 echo '&#8226;' . $tag_link . '<br/>';
1321 }
1322 echo '</li>';
1323 }
1324 echo '</ul>';
1325 echo '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
1326
1327 print_paging_bar($count, $page, $perpage, $baseurl.'&amp;', 'page');
1328 }
1329 else { //no results were found!!
1330
5557c75a 1331 print_heading(get_string('noresultsfor', 'tag', $query), '', 3);
c933a060 1332
1333 //print a link "Add $query to my interests"
1334 if (!empty($addtaglink)) {
1335 print_box($addtaglink,'box','tag-management-box');
1336 }
1337
1338 }
1339
1340
1341}
1342
1343/**
1344 * Prints a tag cloud
1345 *
4f81c51d 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
c933a060 1348 * @param int $max_size maximum text size, in percentage
1349 * @param int $min_size minimum text size, in percentage
1350 */
1351function print_tag_cloud($tagcloud, $shuffle=true, $max_size=180, $min_size=80) {
1352
1353 global $CFG;
1354
1355 if (empty($tagcloud)) {
1356 return;
1357 }
1358
1359 if ( $shuffle ) {
1360 shuffle($tagcloud);
1361 }
1362
1363 $count = array();
1364 foreach ($tagcloud as $key => $value){
1365 if(!empty($value->count)) {
1366 $count[$key] = log10($value->count);
1367 }
1368 else{
1369 $count[$key] = 0;
1370 }
1371 }
1372
1373 $max = max($count);
1374 $min = min($count);
1375
1376 $spread = $max - $min;
1377 if (0 == $spread) { // we don't want to divide by zero
1378 $spread = 1;
1379 }
1380
1381 $step = ($max_size - $min_size)/($spread);
1382
1383 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1384 $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
1385
1386 //prints the tag cloud
1387 echo '<ul id="tag-cloud-list">';
1388 foreach ($tagcloud as $key => $tag) {
1389
1390 $size = $min_size + ((log10($tag->count) - $min) * $step);
1391 $size = ceil($size);
1392
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.'"';
1396
1397 //highlight tags that have been flagged as inappropriate for those who can manage them
4f81c51d 1398 $tagname = tag_display_name($tag);
c933a060 1399 if ($tag->flag > 0 && $can_manage_tags) {
4f81c51d 1400 $tagname = '<span class="flagged-tag">' . tag_display_name($tag) . '</span>';
c933a060 1401 }
1402
1403 $tag_link = '<li><a '.$href.' '.$title.' '. $style .'>'.$tagname.'</a></li> ';
1404
1405 echo $tag_link;
1406
1407 }
1408 echo '</ul>';
1409
1410}
1411
1412function print_tag_management_list($perpage='100') {
1413
1414 global $CFG, $USER;
1415 require_once($CFG->libdir.'/tablelib.php');
1416
1417 //setup table
4f81c51d 1418
1419 $tablecolumns = array('id','name', 'owner', 'count', 'flag', 'timemodified', '');
1420 $tableheaders = array( get_string('id' , 'tag'),
1421 get_string('name' , 'tag'),
c933a060 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')
1427 );
1428
1429 $table = new flexible_table('tag-management-list-'.$USER->id);
1430
1431 $baseurl = $CFG->wwwroot.'/tag/manage.php';
1432
1433 $table->define_columns($tablecolumns);
1434 $table->define_headers($tableheaders);
1435 $table->define_baseurl($baseurl);
1436
1437 $table->sortable(true, 'flag', SORT_DESC);
1438
1439 $table->set_attribute('cellspacing', '0');
1440 $table->set_attribute('id', 'tag-management-list');
1441 $table->set_attribute('class', 'generaltable generalbox');
1442
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'
1450 ));
1451
1452 $table->setup();
1453
1454 if ($table->get_sql_sort()) {
1455 $sort = ' ORDER BY '.$table->get_sql_sort();
1456 } else {
1457 $sort = '';
1458 }
1459
1460 if ($table->get_sql_where()) {
1461 $where = 'WHERE '.$table->get_sql_where();
1462 } else {
1463 $where = '';
1464 }
1465
1466 $query = "
1467 SELECT
4f81c51d 1468 tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count, u.id AS owner, tg.flag, tg.timemodified
c933a060 1469 FROM
1470 {$CFG->prefix}tag_instance ti
1471 RIGHT JOIN
1472 {$CFG->prefix}tag tg
1473 ON
1474 tg.id = ti.tagid
1475 LEFT JOIN
1476 {$CFG->prefix}user u
1477 ON
1478 tg.userid = u.id
1479 {$where}
1480 GROUP BY
1481 tg.id
1482 {$sort}
1483 ";
1484
1485 $totalcount = count_records('tag');
1486
1487 $table->initialbars($totalcount > $perpage);
1488 $table->pagesize($perpage, $totalcount);
1489
1490
1491 echo '<form id="tag-management-form" method="post" action="'.$CFG->wwwroot.'/tag/manage.php">';
1492
1493 //retrieve tags from DB
1494 if ($tagrecords = get_records_sql($query, $table->get_page_start(), $table->get_page_size())) {
1495
1496 $taglist = array_values($tagrecords);
1497
1498 //print_tag_cloud(array_values(get_records_sql($query)), false);
1499
1500 //populate table with data
1501 foreach ($taglist as $tag ){
4f81c51d 1502
1503 $id = $tag->id;
1504 $name = '<a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'. tag_display_name($tag) .'</a>';
c933a060 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.'" />';
1510
1511 //if the tag if flagged, highlight it
1512 if ($tag->flag > 0) {
4f81c51d 1513 $id = '<span class="flagged-tag">' . $id . '</span>';
c933a060 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>';
1519 }
1520
4f81c51d 1521 $data = array($id, $name , $owner ,$count ,$flag, $timemodified, $checkbox);
c933a060 1522
1523 $table->add_data($data);
1524 }
1525
1526
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">
938e7302 1531 <option value="" selected="selected">'. get_string('withselectedtags', 'tag') .'</option>
c933a060 1532 <option value="reset">'. get_string('resetflag', 'tag') .'</option>
1533 <option value="delete">'. get_string('delete', 'tag') .'</option>
1534 </select>';
1535
1536 echo '<button id="tag-management-submit" type="submit">'. get_string('ok') .'</button>';
1537
1538 }
1539
1540 $table->print_html();
1541
1542 echo '</form>';
1543}
1544
1545?>