mirrored from git://git.moodle.org/moodle.git
/
lib.php
1541 lines (1184 loc) · 46.5 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php // $Id$
require_once('../config.php');
/**
* Creates tags
* Ex: tag_create('A VeRY cOoL Tag, Another NICE tag')
* will create the following normalized {@link tag_normalize()} entries in tags table:
* 'a very cool tag'
* 'another nice tag'
*
* @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
* @param string $tag_type type of tag to be created ("default" is the default value).
* @return an array of tags ids, indexed by their normalized names
*/
function tag_create($tag_names_csv, $tag_type="default") {
global $USER;
$tags = explode(",", $tag_names_csv );
$tag_object = new StdClass;
$tag_object->tagtype = $tag_type;
$tag_object->userid = $USER->id;
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
$can_create_tags = has_capability('moodle/tag:create',$systemcontext);
$norm_tag_names_csv = '';
foreach ($tags as $tag) {
// rawname keeps the original casing of the string
$tag_object->rawname = tag_normalize($tag, false);
// name lowercases the string
$tag_object->name = tag_normalize($tag);
$norm_tag_names_csv .= $tag_object->name . ',';
$tag_object->timemodified = time();
$exists = record_exists('tag', 'name', $tag_object->name);
if ( $can_create_tags && !$exists && !empty($tag_object->name) && !is_numeric($tag_object->name) ) {
insert_record('tag', $tag_object);
}
}
$norm_tag_names_csv = substr($norm_tag_names_csv,0,-1);
return tags_id( $norm_tag_names_csv );
}
/**
* Deletes tags
*
* Ex 1: tag_delete('a very cool tag, another nice tag')
* Will delete the tags with names 'a very cool tag' and 'another nice tag' from the 'tags' table, if they exist!
*
* Ex 2: tag_delete('computers, 123, 143, algorithms')
* Will delete tags with names 'computers' and 'algorithms' and tags with ids 123 and 143.
*
*
* @param string $tag_names_or_ids_csv **normalized** tag names or ids of the tags to be deleted.
*/
function tag_delete($tag_names_or_ids_csv) {
//covert all ids to names
$tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
//put apostrophes in names
$tag_names_csv_with_apos = "'" . str_replace(',', "','", $tag_names_csv) . "'";
delete_records_select('tag',"name IN ($tag_names_csv_with_apos)");
}
/**
* Get all tags from the records
*
* @param string $tag_types_csv (optional, default value is "default". If '*' is passed, tags of any type will be returned).
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return
* (optional, by default 'id, tagtype, name'). The first field will be used as key for the
* array so must be a unique field such as 'id'.
*/
function get_all_tags($tag_types_csv="default", $sort='name ASC', $fields='id, tagtype, name, rawname') {
if ($tag_types_csv == '*'){
return get_records('tag', '', '', $sort, $fields);
}
$tag_types_csv_with_apos = "'" . str_replace(',', "','", $tag_types_csv ) . "'";
return get_records_list('tag', 'tagtype', $tag_types_csv_with_apos, $sort, $fields);
}
/**
* Determines if a tag exists
*
* @param string $tag_name_or_id **normalized** tag name, or an id.
* @return true if exists or false otherwise
*
*/
function tag_exists($tag_name_or_id) {
if (is_numeric($tag_name_or_id)) {
return record_exists('tag', 'id', $tag_name_or_id);
}
elseif (is_string($tag_name_or_id)) {
return record_exists('tag', 'name', $tag_name_or_id);
}
}
/**
* Function that returns the id of a tag
*
* @param String $tag_name **normalized** name of the tag
* @return int id of the matching tag
*/
function tag_id($tag_name) {
$tag = get_record('tag', 'name', trim($tag_name), '', '', '', '', 'id');
if ($tag){
return $tag->id;
}
else{
return false;
}
}
/**
* Function that returns the ids of tags
*
* Ex: tags_id('computers, algorithms')
*
* @param String $tag_names_csv comma separated **normalized** tag names.
* @return Array array with the tags ids, indexed by their **normalized** names
*/
function tags_id($tag_names_csv) {
$normalized_tag_names_csv = tag_normalize($tag_names_csv);
$tag_names_csv_with_apos = "'" . str_replace(',', "','", $normalized_tag_names_csv ) . "'";
$tag_objects = get_records_list('tag','name', $tag_names_csv_with_apos, "" , "name, id" );
$tags_ids = array();
foreach ($tag_objects as $tag) {
$tags_ids[$tag->name] = $tag->id;
}
return $tags_ids;
}
/**
* Function that returns the name of a tag
*
* @param int $tag_id id of the tag
* @return String name of the tag with the id passed
*/
function tag_name($tag_id) {
$tag = get_record('tag', 'id', $tag_id, '', '', '', '', 'name');
if ($tag){
return $tag->name;
}
else{
return '';
}
}
/**
* Function that retrieves the names of tags given their ids
*
* @param String $tag_ids_csv comma separated tag ids
* @return Array an array with the tags names, indexed by their ids
*/
function tags_name($tag_ids_csv) {
//remove any white spaces
$tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
$tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
$tag_objects = get_records_list('tag','id', $tag_ids_csv_with_apos, "" , "name, id" );
$tags_names = array();
foreach ($tag_objects as $tag) {
$tags_names[$tag->id] = $tag->name;
}
return $tags_names;
}
/**
* Function that returns the name of a tag for display.
*
* @param mixed $tag_object
* @return string
*/
function tag_display_name($tag_object){
global $CFG;
if( !empty($CFG->keeptagnamecase) ) {
//this is the normalized tag name
return mb_convert_case($tag_object->name, MB_CASE_TITLE,"UTF-8");
}
else {
//original casing of the tag name
return $tag_object->rawname;
}
}
/**
* Function that retrieves a tag object by its id
*
* @param String $tag_id
* @return mixed a fieldset object containing the first matching record, or false if none found
*/
function tag_by_id($tag_id) {
return get_record('tag','id',$tag_id);
}
/**
* Function that retrieves a tag object by its name
*
* @param String $tag_name
* @return mixed a fieldset object containing the first matching record, or false if none found
*/
function tag_by_name($tag_name) {
$tag = get_record('tag','name',$tag_name);
return $tag;
}
/**
* In a comma separated string of ids or names of tags, replaces all tag names with their correspoding ids
*
* Ex:
* Suppose the DB contains only the following entries in the tags table:
* id name
* 10 moodle
* 12 science
* 22 education
*
* tag_id_from_string('moodle, 12, education, programming, 33, 11')
* will return '10,12,22,,33,11'
*
* This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
*
* @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
* @return int comma separated ids of the tags
*/
function tag_id_from_string($tag_names_or_ids_csv) {
$tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
$tag_ids = array();
foreach ($tag_names_or_ids as $name_or_id) {
if (is_numeric($name_or_id)){
$tag_ids[] = trim($name_or_id);
}
elseif (is_string($name_or_id)) {
$tag_ids[] = tag_id( $name_or_id );
}
}
$tag_ids_csv = implode(',',$tag_ids);
$tag_ids_csv = str_replace(' ', '', $tag_ids_csv);
return $tag_ids_csv;
}
/**
* In a comma separated string of ids or names of tags, replaces all tag ids with their correspoding names
*
* Ex:
* Suppose the DB contains only the following entries in the tags table:
* id name
* 10 moodle
* 12 science
* 22 education
*
* tag_name_from_string('mOOdle, 10, HiStOrY, 17, 22')
* will return the string 'mOOdle,moodle,HiStOrY,,education'
*
* This is a helper function used by functions of this API to process function arguments ($tag_name_or_id)
*
* @param string $tag_names_or_ids_csv comma separated **normalized** names or ids of tags
* @return int comma separated ids of the tags
*/
function tag_name_from_string($tag_names_or_ids_csv) {
$tag_names_or_ids = explode(',', $tag_names_or_ids_csv);
$tag_names = array();
foreach ($tag_names_or_ids as $name_or_id) {
if (is_numeric($name_or_id)){
$tag_names[] = tag_name($name_or_id);
}
elseif (is_string($name_or_id)) {
$tag_names[] = trim($name_or_id);
}
}
$tag_names_csv = implode(',',$tag_names);
return $tag_names_csv;
}
/**
* Associates a tag with an item
*
* Ex 1: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
* This will tag an user whose id is 1 with "history", "religions", "roman"
* If the tag names passed do not exist, they will get created.
*
* Ex 2: tag_an_item('user', '1', 'hisTory, 12, 11, roman')
* This will tag an user whose id is 1 with 'history', 'roman' and with tags of ids 12 and 11
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item to be tagged
* @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
* @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
*/
function tag_an_item($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
//convert any tag ids passed to their corresponding tag names
$tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
//create the tags
$tags_created_ids = tag_create($tag_names_csv,$tag_type);
$tag_instance = new StdClass;
$tag_instance->itemtype = $item_type;
$tag_instance->itemid = $item_id;
//create tag instances
foreach ($tags_created_ids as $tag_id) {
$tag_instance->tagid = $tag_id;
$exists = record_exists('tag_instance', 'tagid', $tag_id, 'itemtype', $item_type, 'itemid', $item_id);
if (!$exists) {
insert_record('tag_instance',$tag_instance);
}
}
// update_tag_correlations($item_type, $item_id);
}
/**
* Updates the tags associated with an item
*
* Ex 1:
* Suppose user 1 is tagged only with "algorithms", "computers" and "software"
* By calling update_item_tags('user', 1, 'algorithms, software, mathematics')
* User 1 will now be tagged only with "algorithms", "software" and "mathematics"
*
* Ex 2:
* update_item_tags('user', '1', 'algorithms, 12, 13')
* User 1 will now be tagged only with "algorithms", and with tags of ids 12 and 13
*
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item to be tagged
* @param string $tag_names_or_ids_csv comma separated tag names (can be unormalized) or ids of existing tags
* @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
*/
function update_item_tags($item_type, $item_id, $tag_names_or_ids_csv, $tag_type="default") {
//if $tag_names_csv is an empty string, remove all tag associations of the item
if( empty($tag_names_or_ids_csv) ){
untag_an_item($item_type, $item_id);
return;
}
//convert any tag ids passed to their corresponding tag names
$tag_names_csv = tag_name_from_string($tag_names_or_ids_csv);
//associate the tags passed with the item
tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type );
//get the ids of the tags passed
$existing_and_new_tags_ids = tags_id( tag_normalize($tag_names_csv) );
// delete any tag instance with $item_type and $item_id
// that are not in $tag_names_csv
$tags_id_csv = "'" . implode("','", $existing_and_new_tags_ids) . "'" ;
$select = "
itemid = '{$item_id}'
AND
itemtype = '{$item_type}'
AND
tagid NOT IN ({$tags_id_csv})
";
delete_records_select('tag_instance', $select);
}
/**
* Removes the association of an item with a tag
*
* Ex: untag_an_item('user', '1', 'history, 11, roman' )
* The user with id 1 will no longer be tagged with 'history', 'roman' and the tag of id 11
* Calling untag_an_item('user','1') will remove all tags associated with user 1.
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item to be untagged
* @param string $tag_names_or_ids_csv comma separated tag **normalized** names or ids of existing tags (optional,
* if none is given, all tags of the item will be removed)
*/
function untag_an_item($item_type, $item_id, $tag_names_or_ids_csv='') {
if ($tag_names_or_ids_csv == ""){
delete_records('tag_instance','itemtype', $item_type, 'itemid', $item_id);
}
else {
$tag_ids_csv = tag_id_from_string($norm_tag_names_or_ids_csv);
$tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv ) . "'";
delete_records_select('tag_instance',
"tagid IN ($tags_id_csv_with_apos) AND itemtype='$item_type' AND itemid='$item_id'");
}
//update_tag_correlations($item_type, $item_id);
}
/**
* Function that gets the tags that are associated with an item
*
* Ex: get_item_tags('user', '1')
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item beeing queried
* @param string $fields tag fields to be selected (optional, default is 'id, name, tagtype')
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function get_item_tags($item_type, $item_id, $fields='id, name, rawname, tagtype, flag', $limitfrom='', $limitnum='') {
global $CFG;
$fields = 'tg.' . $fields;
$fields = str_replace(',', ',tg.', $fields);
$query = "
SELECT
{$fields}
FROM
{$CFG->prefix}tag_instance ti
INNER JOIN
{$CFG->prefix}tag tg
ON
tg.id = ti.tagid
WHERE
ti.itemtype = '{$item_type}' AND
ti.itemid = '{$item_id}'";
return get_records_sql($query, $limitfrom, $limitnum);
}
/**
* Function that returns the items of a certain type associated with a certain tag
*
* Ex 1: get_items_tagged_with('user', 'banana')
* Ex 2: get_items_tagged_with('user', '11')
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* (to avoid field name ambiguity in the query, use the identifier "it" Ex: 'it.name ASC' )
* @param string $fields a comma separated list of fields to return
* (optional, by default all fields are returned). The first field will be used as key for the
* array so must be a unique field such as 'id'. To avoid field name ambiguity in the query,
* use the identifier "it" Ex: 'it.name, it.id' )
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects indexed by their ids, or false if no records were found or an error occured.
*/
function get_items_tagged_with($item_type, $tag_name_or_id, $sort='', $fields='*', $limitfrom='', $limitnum='') {
global $CFG;
$tag_id = tag_id_from_string($tag_name_or_id);
$fields = 'it.' . $fields;
$fields = str_replace(',', ',it.', $fields);
if ($sort) {
$sort = ' ORDER BY '. $sort;
}
$query = "
SELECT
{$fields}
FROM
{$CFG->prefix}{$item_type} it
INNER JOIN
{$CFG->prefix}tag_instance tt
ON
it.id = tt.itemid
WHERE
tt.itemtype = '{$item_type}' AND
tt.tagid = '{$tag_id}'
{$sort}
";
return get_records_sql($query, $limitfrom, $limitnum);
}
/**
* Returns the number of items tagged with a tag
*
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @param string $item_type name of the table where the item is stored. Ex: 'user' (optional, if none is set any
* type will be counted)
* @return int the count. If an error occurrs, 0 is returned.
*/
function count_items_tagged_with($tag_name_or_id, $item_type='') {
global $CFG;
$tag_id = tag_id_from_string($tag_name_or_id);
if (empty($item_type)){
$query = "
SELECT
COUNT(*) AS count
FROM
{$CFG->prefix}tag_instance tt
WHERE
tagid = {$tag_id}";
}
else
{
$query = "
SELECT
COUNT(*) AS count
FROM
{$CFG->prefix}{$item_type} it
INNER JOIN
{$CFG->prefix}tag_instance tt
ON
it.id = tt.itemid
WHERE
tt.itemtype = '{$item_type}' AND
tt.tagid = '{$tag_id}' ";
}
return count_records_sql($query);
}
/**
* Determines if an item is tagged with a certain tag
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item beeing queried
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @return bool true if a matching record exists, else false.
*/
function is_item_tagged_with($item_type,$item_id, $tag_name_or_id) {
$tag_id = tag_id_from_string($tag_name_or_id);
return record_exists('tag_instance','itemtype',$item_type,'itemid',$item_id, 'tagid', $tag_id);
}
/**
* Search for tags with names that match some text
*
* @param string $text string that the tag names will be matched against
* @param boolean $ordered If true, tags are ordered by their popularity. If false, no ordering.
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function search_tags($text, $ordered=true, $limitfrom='' , $limitnum='' ) {
global $CFG;
$text = tag_normalize($text);
if ($ordered) {
$query = "
SELECT
tg.id, tg.name, tg.rawname, COUNT(ti.id) AS count
FROM
{$CFG->prefix}tag tg
LEFT JOIN
{$CFG->prefix}tag_instance ti
ON
tg.id = ti.tagid
WHERE
tg.name
LIKE
'%{$text}%'
GROUP BY
tg.id
ORDER BY
count
DESC";
} else {
$query = "
SELECT
tg.id, tg.name, tg.rawname
FROM
{$CFG->prefix}tag tg
WHERE
tg.name
LIKE
'%{$text}%'
";
}
return get_records_sql($query, $limitfrom , $limitnum);
}
/**
* Function that returns tags that start with some text
*
* @param string $text string that the tag names will be matched against
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function similar_tags($text, $limitfrom='' , $limitnum='' ) {
global $CFG;
$text = tag_normalize($text);
$query = "
SELECT
tg.id, tg.name, tg.rawname
FROM
{$CFG->prefix}tag tg
WHERE
tg.name
LIKE
'{$text}%'
";
return get_records_sql($query, $limitfrom , $limitnum);
}
/**
* Returns tags related to a tag
*
* Related tags of a tag come from two sources:
* - manually added related tags, which are tag_instance entries for that tag
* - correlated tags, which are a calculated
*
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @param int $limitnum return a subset comprising this many records (optional, default is 10)
* @return mixed an array of tag objects
*/
function related_tags($tag_name_or_id, $limitnum=10) {
$tag_id = tag_id_from_string($tag_name_or_id);
//gets the manually added related tags
$manual_related_tags = get_item_tags('tag',$tag_id, 'id, name, rawname, tagtype, flag');
if ($manual_related_tags == false) $manual_related_tags = array();
//gets the correlated tags
$automatic_related_tags = correlated_tags($tag_id);
if ($automatic_related_tags == false) $automatic_related_tags = array();
$related_tags = array_merge($manual_related_tags,$automatic_related_tags);
return array_slice( object_array_unique($related_tags) , 0 , $limitnum );
}
/**
* Returns the correlated tags of a tag
* The correlated tags are retrieved from the tag_correlation table, which is a caching table.
*
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @return mixed an array of tag objects
*/
function correlated_tags($tag_name_or_id) {
$tag_id = tag_id_from_string($tag_name_or_id);
if (!$tag_correlation = get_record('tag_correlation','tagid',$tag_id)) {
return array();
}
$tags_id_csv_with_apos = stripcslashes($tag_correlation->correlatedtags);
return get_records_select('tag', "id IN ({$tags_id_csv_with_apos})", '', 'id, name, rawname, tagtype, flag');
}
/**
* Recalculates tag correlations of all the tags associated with an item
* This function could be called whenever the tags associations with an item changes
* ( for example when tag_an_item() or untag_an_item() is called )
*
* @param string $item_type name of the table where the item is stored. Ex: 'user'
* @param string $item_id id of the item
*/
function update_tag_correlations($item_type, $item_id) {
$item_tags = get_item_tags($item_type, $item_id);
foreach ($item_tags as $tag) {
cache_correlated_tags($tag->id);
}
}
/**
* Calculates and stores the correlated tags of a tag.
* The correlations are stored in the 'tag_correlation' table.
*
* Two tags are correlated if they appear together a lot.
* Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
*
* The rationale for the 'tag_correlation' table is performance.
* It works as a cache for a potentially heavy load query done at the 'tag_instance' table.
* So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
*
* @param string $tag_name_or_id is a single **normalized** tag name or the id of a tag
* @param number $min_correlation cutoff percentage (optional, default is 0.25)
* @param int $limitnum return a subset comprising this many records (optional, default is 10)
*/
function cache_correlated_tags($tag_name_or_id, $min_correlation=0.25, $limitnum=10) {
global $CFG;
$tag_id = tag_id_from_string($tag_name_or_id);
// query that counts how many times any tag appears together in items
// with the tag passed as argument ($tag_id)
$query =
" SELECT
tb.tagid , COUNT(*) nr
FROM
{$CFG->prefix}tag_instance ta
INNER JOIN
{$CFG->prefix}tag_instance tb
ON
ta.itemid = tb.itemid
WHERE
ta.tagid = {$tag_id}
GROUP BY
tb.tagid
ORDER BY
nr DESC";
$tag_correlations = get_records_sql($query, 0, $limitnum);
$tags_id_csv_with_apos = "'";
$cutoff = $tag_correlations[$tag_id]->nr * $min_correlation;
foreach($tag_correlations as $correlation) {
if($correlation->nr >= $cutoff && $correlation->tagid != $tag_id ){
$tags_id_csv_with_apos .= $correlation->tagid."','";
}
}
$tags_id_csv_with_apos = substr($tags_id_csv_with_apos,0,-2);
//saves correlation info in the caching table
$tag_correlation_obj = get_record('tag_correlation','tagid',$tag_id);
if ($tag_correlation_obj) {
$tag_correlation_obj->correlatedtags = addslashes($tags_id_csv_with_apos);
update_record('tag_correlation',$tag_correlation_obj);
}
else {
$tag_correlation_obj = new StdClass;
$tag_correlation_obj->tagid = $tag_id;
$tag_correlation_obj->correlatedtags = addslashes($tags_id_csv_with_apos);
insert_record('tag_correlation',$tag_correlation_obj);
}
}
/**
* This function cleans up the 'tag_instance' table
* It removes orphans in 'tag_instances' table
*
*/
function tag_instance_table_cleanup() {
global $CFG;
//get the itemtypes present in the 'tag_instance' table
$query = "
SELECT
DISTINCT(itemtype)
FROM
{$CFG->prefix}tag_instance
";
$items_types = get_records_sql($query);
// for each itemtype, remove tag_instances that are orphans
// That is: For a given tag_instance, if in the itemtype table there's no entry with id equal to itemid,
// then this tag_instance is an orphan and it will be removed.
foreach ($items_types as $type) {
$query = "
{$CFG->prefix}tag_instance.id
IN
( SELECT sq1.id
FROM
(SELECT sq2.*
FROM {$CFG->prefix}tag_instance sq2
LEFT JOIN {$CFG->prefix}{$type->itemtype} item
ON sq2.itemid = item.id
WHERE item.id IS NULL
AND sq2.itemtype = '{$type->itemtype}')
sq1
) ";
delete_records_select('tag_instance', $query);
}
// remove tag_instances that are orphans because tagid does not correspond to an
// existing tag
$query = "
{$CFG->prefix}tag_instance.id
IN
(SELECT sq1.id
FROM
(SELECT sq2.*
FROM {$CFG->prefix}tag_instance sq2
LEFT JOIN {$CFG->prefix}tag tg
ON sq2.tagid = tg.id
WHERE tg.id IS NULL )
sq1
)
";
delete_records_select('tag_instance', $query);
}
/**
* Function that normalizes a tag name
*
* Ex: tag_normalize('bANAana') -> returns 'banana'
* tag_normalize('lots of spaces') -> returns 'lots of spaces'
* tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
* tag_normalize('tag one, TAG TWO, TAG three, and anotheR tag')
* -> returns 'tag one,tag two,tag three,and another tag'
*
* @param string $tag_names_csv unnormalized CSV tag names
* @return string **normalized** CSV tag names
*/
function tag_normalize($tag_names_csv, $lowercase=true) {
$tags = explode(',', $tag_names_csv);
if (sizeof($tags) > 1) {
foreach ($tags as $key => $tag) {
$tags[$key] = tag_normalize($tag);
}
return implode(',' , $tags);
}
// only one tag was passed
else {
if ($lowercase){
$value = moodle_strtolower($tag_names_csv);
}
else {
$value = $tag_names_csv;
}
//$value = preg_replace('|[^\w ]|i', '', strtolower(trim($tag_names_csv)));
$value = preg_replace('|[\!\@\#\$\%\^\&\*\(\)\-\+\=\~\`\\"\'\_.\[\]\{\}\:\;\?\´\^\\\/\<\>\|]|i', '', trim($value));
//removes excess white spaces
$value = preg_replace('/\s\s+/', ' ', $value);
return $value;
}
}
function tag_flag_inappropriate($tag_names_or_ids_csv){
$tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
$tag_ids = explode(',', $tag_ids_csv);
foreach ($tag_ids as $id){
$tag = get_record('tag','id',$id, '', '', '', '', 'id,flag');
$tag->flag++;
$tag->timemodified = time();
update_record('tag', $tag);
}
}
function tag_flag_reset($tag_names_or_ids_csv){
global $CFG;
$tag_ids_csv = tag_id_from_string($tag_names_or_ids_csv);
$tag_ids_csv_with_apos = "'" . str_replace(',', "','", $tag_ids_csv) . "'";
$timemodified = time();
$query = "
UPDATE
{$CFG->prefix}tag tg
SET
tg.flag = 0,
tg.timemodified = {$timemodified}
WHERE
tg.id
IN
({$tag_ids_csv_with_apos})
";
execute_sql($query, false);
}
/**
* Function that returns comma separated HTML links to the tag pages of the tags passed
*
* @param array $tag_objects an array of tag objects
* @return string CSV, HTML links to tag pages
*/
function tag_links_csv($tag_objects) {
global $CFG;
$tag_links = '';
if (empty($tag_objects)) {
return '';
}
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
$can_manage_tags = has_capability('moodle/tag:manage', $systemcontext);
foreach ($tag_objects as $tag){
//highlight tags that have been flagged as inappropriate for those who can manage them
$tagname = tag_display_name($tag);
if ($tag->flag > 0 && $can_manage_tags) {
$tagname = '<span class="flagged-tag">' . $tagname . '</span>';
}
$tag_links .= ' <a href="'.$CFG->wwwroot.'/tag/index.php?id='.$tag->id.'">'.$tagname.'</a>,';
}
return rtrim($tag_links, ',');