File: lib.php

package info (click to toggle)
moodle 1.4.4.dfsg.1-3sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 57,876 kB
  • ctags: 29,496
  • sloc: php: 271,617; sql: 5,084; xml: 702; perl: 638; sh: 403; java: 283; makefile: 42; pascal: 21
file content (2208 lines) | stat: -rw-r--r-- 81,523 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
<?PHP  // $Id: lib.php,v 1.89.2.18 2005/02/18 01:15:15 stronk7 Exp $

/// Library of functions and constants for module glossary
/// (replace glossary with the name of your module and delete this line)

require_once("$CFG->dirroot/files/mimetypes.php");

define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);

define("GLOSSARY_NO_VIEW", -1);
define("GLOSSARY_STANDARD_VIEW", 0);
define("GLOSSARY_CATEGORY_VIEW", 1);
define("GLOSSARY_DATE_VIEW", 2);
define("GLOSSARY_AUTHOR_VIEW", 3);
define("GLOSSARY_ADDENTRY_VIEW", 4);
define("GLOSSARY_IMPORT_VIEW", 5);
define("GLOSSARY_EXPORT_VIEW", 6);
define("GLOSSARY_APPROVAL_VIEW", 7);

//Check for global configure default variables

if (!isset($CFG->glossary_studentspost)) {
    set_config("glossary_studentspost", 1);  // Students can post entries.
}

if (!isset($CFG->glossary_dupentries)) {
    set_config("glossary_dupentries", 0);  // Duplicate entries are not allowed.
}

if (!isset($CFG->glossary_allowcomments)) {
    set_config("glossary_allowcomments", 0);  // Comments are not allowed.
}

if (!isset($CFG->glossary_linkbydefault)) {
    set_config("glossary_linkbydefault", 1);  // Linking entries is enabled.
}

if (!isset($CFG->glossary_defaultapproval)) {
    set_config("glossary_defaultapproval", 1);  // Entries are approved.
}

if (!isset($CFG->glossary_entbypage)) {
    set_config("glossary_entbypage", 10);  // 10 entries are showed.
}

/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////

function glossary_add_instance($glossary) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will create a new instance and return the id number
/// of the new instance.

    if (!isset($glossary->userating) || !$glossary->userating) {
        $glossary->assessed = 0;
    }

    if (!empty($glossary->ratingtime)) {
        $glossary->assesstimestart  = make_timestamp($glossary->startyear, $glossary->startmonth, $glossary->startday, 
                                                  $glossary->starthour, $glossary->startminute, 0);
        $glossary->assesstimefinish = make_timestamp($glossary->finishyear, $glossary->finishmonth, $glossary->finishday, 
                                                  $glossary->finishhour, $glossary->finishminute, 0);
    } else {
        $glossary->assesstimestart  = 0;
        $glossary->assesstimefinish = 0;
    }

    if ( !isset($glossary->globalglossary) ) {
        $glossary->globalglossary = 0;
    } elseif ( !isadmin() ) {
        $glossary->globalglossary = 0;
    }

    $glossary->timecreated = time();
    $glossary->timemodified = $glossary->timecreated;

    //Check displayformat is a valid one
    $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
    if (!in_array($glossary->displayformat, $formats)) {
        error("This format doesn't exist!");
    }  

    return insert_record("glossary", $glossary);
}


function glossary_update_instance($glossary) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will update an existing instance with new data.
global $CFG;
    if ( !isadmin() ) {
        unset($glossary->globalglossary);
    }
    if (empty($glossary->globalglossary)) {
        $glossary->globalglossary = 0;
    }

    $glossary->timemodified = time();
    $glossary->id = $glossary->instance;

    if (!isset($glossary->userating) || !$glossary->userating) {
        $glossary->assessed = 0;
    }

    if (!empty($glossary->ratingtime)) {
        $glossary->assesstimestart  = make_timestamp($glossary->startyear, $glossary->startmonth, $glossary->startday, 
                                                  $glossary->starthour, $glossary->startminute, 0);
        $glossary->assesstimefinish = make_timestamp($glossary->finishyear, $glossary->finishmonth, $glossary->finishday, 
                                                  $glossary->finishhour, $glossary->finishminute, 0);
    } else {
        $glossary->assesstimestart  = 0;
        $glossary->assesstimefinish = 0;
    }

    //Check displayformat is a valid one
    $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
    if (!in_array($glossary->displayformat, $formats)) {
        error("This format doesn't exist!");
    }

    $return = update_record("glossary", $glossary);
	if ($return and $glossary->defaultapproval) {
        execute_sql("update {$CFG->prefix}glossary_entries SET approved = 1 where approved != 1 and glossaryid = " . $glossary->id,false);
    }

    return $return;
}


function glossary_delete_instance($id) {
/// Given an ID of an instance of this module,
/// this function will permanently delete the instance
/// and any data that depends on it.

    if (! $glossary = get_record("glossary", "id", "$id")) {
        return false;
    }

    $result = true;

    # Delete any dependent records here #

    if (! delete_records("glossary", "id", "$glossary->id")) {
        $result = false;
    } else {
        if ($categories = get_records("glossary_categories","glossaryid",$glossary->id)) {
            $cats = "";
            foreach ( $categories as $cat ) {
                $cats .= "$cat->id,";
            }
            $cats = substr($cats,0,-1);
            if ($cats) {
                delete_records_select("glossary_entries_categories", "categoryid in ($cats)");
                delete_records("glossary_categories", "glossaryid", $glossary->id);
            }
        }
        if ( $entries = get_records("glossary_entries", "glossaryid", $glossary->id) ) {
            $ents = "";
            foreach ( $entries as $entry ) {
                if ( $entry->sourceglossaryid ) {
                    $entry->glossaryid = $entry->sourceglossaryid;
                    $entry->sourceglossaryid = 0;
                    update_record("glossary_entries",$entry);
                } else {
                    $ents .= "$entry->id,";
                }
            }
            $ents = substr($ents,0,-1);
            if ($ents) {
                delete_records_select("glossary_comments", "entryid in ($ents)");
                delete_records_select("glossary_alias", "entryid in ($ents)");
                delete_records_select("glossary_ratings", "entryid in ($ents)");
            }
        }
        glossary_delete_attachments($glossary);
        delete_records("glossary_entries", "glossaryid", "$glossary->id");
    }

    return $result;
}

function glossary_user_outline($course, $user, $mod, $glossary) {
/// Return a small object with summary information about what a
/// user has done with a given particular instance of this module
/// Used for user activity reports.
/// $return->time = the time they did it
/// $return->info = a short text description

    if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
        $result->info = count($entries) . ' ' . get_string("entries", "glossary");

        $lastentry = array_pop($entries);
        $result->time = $lastentry->timemodified;
        return $result;
    }
    return NULL;
}

function glossary_get_user_entries($glossaryid, $userid) {
/// Get all the entries for a user in a glossary
    global $CFG;

    return get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
                              FROM {$CFG->prefix}glossary g, 
                                   {$CFG->prefix}glossary_entries e, 
                                   {$CFG->prefix}user u 
                             WHERE g.id = '$glossaryid' 
                               AND e.glossaryid = g.id 
                               AND e.userid = '$userid' 
                               AND e.userid = u.id
                          ORDER BY e.timemodified ASC");
}

function glossary_user_complete($course, $user, $mod, $glossary) {
/// Print a detailed representation of what a  user has done with
/// a given particular instance of this module, for user activity reports.
    global $CFG;

    if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
        echo '<table width="95%" border="0"><tr><td>';
        foreach ($entries as $entry) {
            $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
            glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
            echo '<p>';
        }
        echo '</td></tr></table>';
    }
}

function glossary_print_recent_activity($course, $isteacher, $timestart) {
/// Given a course and a time, this module should find recent activity
/// that has occurred in glossary activities and print it out.
/// Return true if there was output, or false is there was none.

    global $CFG, $THEME;

    if (!$logs = get_records_select("log", "time > '$timestart' AND ".
                                           "course = '$course->id' AND ".
                                           "module = 'glossary' AND ".
                                           "(action = 'add entry' OR ".
                                           " action  = 'approve entry')", "time ASC")) {
        return false;
    }

    $entries = array();

    foreach ($logs as $log) {
        //Create a temp valid module structure (course,id)
        $tempmod->course = $log->course;        
        $entry           = get_record("glossary_entries","id",$log->info);
        $tempmod->id = $entry->glossaryid;
        //Obtain the visible property from the instance        
        $modvisible = instance_is_visible($log->module,$tempmod);

        //Only if the mod is visible
        if ($modvisible and $entry->approved) {
            $entries[$log->info] = glossary_log_info($log);
            $entries[$log->info]->time = $log->time;
            $entries[$log->info]->url  = $log->url;
        }
    }

    $content = false;
    if ($entries) {
        $strftimerecent = get_string("strftimerecent");
        $content = true;
        print_headline(get_string("newentries", "glossary").":");
        foreach ($entries as $entry) {
            $date = userdate($entry->timemodified, $strftimerecent);
            
            $user = get_record("user","id",$entry->userid);
            $fullname = fullname($user, $isteacher);
            echo "<p><font size=1>$date - $fullname<br>";
            echo "\"<a href=\"$CFG->wwwroot/mod/glossary/view.php?g=$entry->glossaryid&mode=entry&hook=$entry->id\">";
            echo "$entry->concept";
            echo "</a>\"</font></p>";
        }
    }

    return $content;
}

function glossary_log_info($log) {
    global $CFG;

    return get_record_sql("SELECT e.*, u.firstname, u.lastname
                             FROM {$CFG->prefix}glossary_entries e,
                                  {$CFG->prefix}user u
                            WHERE e.id = '$log->info'
                              AND u.id = '$log->userid'");
}

function glossary_cron () {
/// Function to be run periodically according to the moodle cron
/// This function searches for things that need to be done, such
/// as sending out mail, toggling flags etc ...

    global $CFG;

    return true;
}

function glossary_grades($glossaryid) {
/// Must return an array of grades for a given instance of this module,
/// indexed by user.  It also returns a maximum allowed grade.
    if (!$glossary = get_record("glossary", "id", $glossaryid)) {
        return false;
    }
    if (!$glossary->assessed) {
        return false;
    }
    $scalemenu = make_grades_menu($glossary->scale);

    $currentuser = 0;
    $ratingsuser = array();

    if ($ratings = glossary_get_user_grades($glossaryid)) {
        foreach ($ratings as $rating) {     // Ordered by user
            if ($currentuser and $rating->userid != $currentuser) {
                if (!empty($ratingsuser)) {
                    if ($glossary->scale < 0) {
                        $return->grades[$currentuser] = glossary_get_ratings_mean(0, $scalemenu, $ratingsuser);
                        $return->grades[$currentuser] .= "<br />".glossary_get_ratings_summary(0, $scalemenu, $ratingsuser);
                    } else {
                        $total = 0;
                        $count = 0;
                        foreach ($ratingsuser as $ra) {
                            $total += $ra;
                            $count ++;
                        }
                        $return->grades[$currentuser] = (string) format_float($total/$count, 2);
                        if ( count($ratingsuser) > 1 ) {
                            $return->grades[$currentuser] .= " (" . count($ratingsuser) . ")";
                        }
                    }
                } else {
                    $return->grades[$currentuser] = "";
                }
                $ratingsuser = array();
            }
            $ratingsuser[] = $rating->rating;
            $currentuser = $rating->userid;
        }
        if (!empty($ratingsuser)) {
            if ($glossary->scale < 0) {
                $return->grades[$currentuser] = glossary_get_ratings_mean(0, $scalemenu, $ratingsuser);
                $return->grades[$currentuser] .= "<br />".glossary_get_ratings_summary(0, $scalemenu, $ratingsuser);
            } else {
                $total = 0;
                $count = 0;
                foreach ($ratingsuser as $ra) {
                    $total += $ra;
                    $count ++;
                }
                $return->grades[$currentuser] = (string) format_float((float)$total/(float)$count, 2);
                
                if ( count($ratingsuser) > 1 ) {
                    $return->grades[$currentuser] .= " (" . count($ratingsuser) . ")";
                }
            }
        } else {
            $return->grades[$currentuser] = "";
        }
    } else {
        $return->grades = array();
    }

    if ($glossary->scale < 0) {
        $return->maxgrade = "";
    } else {
        $return->maxgrade = $glossary->scale;
    }
    return $return;
}

function glossary_get_participants($glossaryid) {
//Returns the users with data in one glossary
//(users with records in glossary_entries, students)

    global $CFG;

    //Get students
    $students = get_records_sql("SELECT DISTINCT u.*
                                 FROM {$CFG->prefix}user u,
                                      {$CFG->prefix}glossary_entries g
                                 WHERE g.glossaryid = '$glossaryid' and
                                       u.id = g.userid");

    //Return students array (it contains an array of unique users)
    return ($students);
}

function glossary_scale_used ($glossaryid,$scaleid) {
//This function returns if a scale is being used by one glossary
   
    $return = false;

    $rec = get_record("glossary","id","$glossaryid","scale","-$scaleid");

    if (!empty($rec)  && !empty($scaleid)) {
        $return = true;               
    }                            
    
    return $return;
}

//////////////////////////////////////////////////////////////////////////////////////
/// Any other glossary functions go here.  Each of them must have a name that
/// starts with glossary_

//This function return an array of valid glossary_formats records
//Everytime it's called, every existing format is checked, new formats
//are included if detected and old formats are deleted and any glossary
//using an invalid format is updated to the default (dictionary).
function glossary_get_available_formats() {

    global $CFG;

    //Get available formats (plugin) and insert (if necessary) them into glossary_formats
    $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
    $pluginformats = array();
    foreach ($formats as $format) {
        //If the format file exists
        if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
            include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
            //If the function exists
            if (function_exists('glossary_show_entry_'.$format)) {
                //Acummulate it as a valid format
                $pluginformats[] = $format;
                //If the format doesn't exist in the table
                if (!$rec = get_record('glossary_formats','name',$format)) {
                    //Insert the record in glossary_formats
                    $gf->name = $format;
                    $gf->popupformatname = $format;
                    $gf->visible = 1;
                    insert_record("glossary_formats",$gf);
                }
            }
        }
    }

    //Delete non_existent formats from glossary_formats table
    $formats = get_records("glossary_formats");
    foreach ($formats as $format) {
        $todelete = false;
        //If the format in DB isn't a valid previously detected format then delete the record
        if (!in_array($format->name,$pluginformats)) {
            $todelete = true;
        }

        if ($todelete) {
            //Delete the format
            delete_records('glossary_formats','name',$format->name);
            //Reasign existing glossaries to default (dictionary) format
            if ($glossaries = get_records('glossary','displayformat',$format->name)) {
                foreach($glossaries as $glossary) {
                    set_field('glossary','displayformat','dictionary','id',$glossary->id);
                }
            }
        }
    }

    //Now everything is ready in glossary_formats table
    $formats = get_records("glossary_formats");

    return $formats;
}

function glossary_debug($debug,$text,$br=1) {
    if ( $debug ) {
        echo '<font color=red>' . $text . '</font>';
        if ( $br ) {
            echo '<br>';
        }
    }
}

function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
    global $CFG;
    if ($pivot) {
       $pivot .= ",";
    }

    return get_records_sql("SELECT $pivot id,userid,concept,definition,format
                            FROM {$CFG->prefix}glossary_entries
                            WHERE glossaryid = '$glossaryid'
                            AND id IN ($entrylist)");
}

function glossary_get_entries_search($concept, $courseid) {
    global $CFG;

    $conceptupper = strtoupper(trim($concept));

    return get_records_sql("SELECT e.*, g.name as glossaryname
                              FROM {$CFG->prefix}glossary_entries e, 
                                   {$CFG->prefix}glossary g
                             WHERE e.glossaryid = g.id 
                               AND (    (e.casesensitive != 0 and UPPER(concept) = '$conceptupper')
                                     OR (e.casesensitive = 0 and concept = '$concept'))
                               AND (g.course = '$courseid' OR g.globalglossary = 1)
                               AND e.usedynalink != 0 
                               AND g.usedynalink != 0");
}

function glossary_get_entries_sorted($glossary, $where="", $orderby="", $pivot = "") {
global $CFG;
    if ($where) {
       $where = " and $where";
    }
    if ($orderby) {
       $orderby = " ORDER BY $orderby";
    }
    if ($pivot) {
       $pivot .= ",";
    }
    return      get_records_sql("SELECT $pivot *
                                 FROM {$CFG->prefix}glossary_entries 
                                 WHERE (glossaryid = $glossary->id or sourceglossaryid = $glossary->id) $where $orderby");
}

function glossary_get_entries_by_category($glossary, $hook, $where="", $orderby="", $pivot = "") {
global $CFG;
    if ($where) {
       $where = " and $where";
    }
    if ($orderby) {
       $orderby = " ORDER BY $orderby";
    }
    if ($pivot) {
       $pivot .= ",";
    }
    return      get_records_sql("SELECT $pivot ge.*
                                 FROM {$CFG->prefix}glossary_entries ge, {$CFG->prefix}glossary_entries_categories c
                                 WHERE (ge.id = c.entryidid and c.categoryid = $hook) and
                                             (ge.glossaryid = $glossary->id or ge.sourceglossaryid = $glossary->id) $where $orderby");
}

function glossary_print_entry($course, $cm, $glossary, $entry, $mode="",$hook="",$printicons = 1, $displayformat  = -1, $ratings = NULL, $printview = false) {
    global $THEME, $USER, $CFG;
    $return = false;
    if ( $displayformat < 0 ) {
        $displayformat = $glossary->displayformat;
    }
    if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
        $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
        if ($printview) {
            $functionname = 'glossary_print_entry_'.$displayformat;
        } else {
            $functionname = 'glossary_show_entry_'.$displayformat;
        }

        if (file_exists($formatfile)) {
            include_once($formatfile);
            if (function_exists($functionname)) {
                $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons,$ratings);
            } else if ($printview) {
                //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
                $return = glossary_print_entry_default($entry);
            }
        }
    }
    return $return;
}
 //Default (old) print format used if custom function doesn't exist in format
function glossary_print_entry_default ($entry) {
    echo '<b>'. strip_tags($entry->concept) . ': </b>';
    $options->para = false;
    $definition = format_text('<nolink>' . strip_tags($entry->definition) . '</nolink>', $entry->format,$options);
    echo ($definition);
    echo '<br /><br />';
}

function  glossary_print_entry_concept($entry) {
    $options->para = false;
    $text = format_text('<nolink>' . $entry->concept . '</nolink>', FORMAT_MOODLE, $options);
    if (!empty($entry->highlight)) {
        $text = highlight($entry->highlight, $text);
    }
    echo $text;
}

function glossary_print_entry_definition($entry) {

    $definition = $entry->definition;

    $tags = array();
    $urls = array();
    $addrs = array();

    //Calculate all the strings to be no-linked
    //First, the concept
    $term = preg_quote(trim($entry->concept),"/");
    $pat = '/('.$term.')/is';
    $doNolinks[] = $pat;
    //Now the aliases
    if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
        foreach ($aliases as $alias) {
            $term = preg_quote(trim($alias->alias),"/");
            $pat = '/('.$term.')/is';
            $doNolinks[] = $pat;
        }
    }

    //Extract all tags from definition
    preg_match_all('/(<.*?>)/is',$definition,$list_of_tags);

    //Save them into tags array to use them later
    foreach (array_unique($list_of_tags[0]) as $key=>$value) {
        $tags['<@'.$key.'@>'] = $value;
    }

    //Take off every tag from definition
    if ( $tags ) {
        $definition = str_replace($tags,array_keys($tags),$definition);
    }

    //Extract all URLS with protocol (http://domain.com) from definition
    preg_match_all('/([[:space:]]|^|\(|\[)([[:alnum:]]+):\/\/([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_urls);

    //Save them into urls array to use them later
    foreach (array_unique($list_of_urls[0]) as $key=>$value) {
        $urls['<*'.$key.'*>'] = $value;
    }

    //Take off every url from definition
    if ( $urls ) {
        $definition = str_replace($urls,array_keys($urls),$definition);
    }

    //Extract all WEB ADDRESSES (www.domain.com) from definition
    preg_match_all('/([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_addresses);

    //Save them into addrs array to use them later
    foreach (array_unique($list_of_addresses[0]) as $key=>$value) {
        $addrs['<+'.$key.'+>'] = $value;
    }

    //Take off every addr from definition
    if ( $addrs ) {
        $definition = str_replace($addrs,array_keys($addrs),$definition);
    }

    //Put doNolinks (concept + aliases) enclosed by <nolink> tag
    $definition= preg_replace($doNolinks,'<nolink>$1</nolink>',$definition);
        
    //Restore addrs
    if ( $addrs ) {
        $definition = str_replace(array_keys($addrs),$addrs,$definition);
    }

    //Restore urls
    if ( $urls ) {
        $definition = str_replace(array_keys($urls),$urls,$definition);
    }

    //Restore tags
    if ( $tags ) {
        $definition = str_replace(array_keys($tags),$tags,$definition);
    }

    $options->para = false;
    $text = format_text($definition, $entry->format,$options);
    if (!empty($entry->highlight)) {
        $text = highlight($entry->highlight, $text);
    }
    if (isset($entry->footer)) {   // Unparsed footer info
        $text .= $entry->footer;
    }
    echo $text;
}

function  glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode="",$hook="", $type = 'print') {
    $return = '';
    if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
        foreach ($aliases as $alias) {
            if (trim($alias->alias)) {
                if ($return == '') {
                    $return = '<select style="font-size:8pt">';
                }
                $return .= "<option>$alias->alias</option>";
            }
        }
        if ($return != '') {
            $return .= '</select>';
        }
    } 
    if ($type == 'print') {
        echo $return;
    } else {
        return $return;
    }
}

function glossary_print_entry_icons($course, $cm, $glossary, $entry,$mode="",$hook="", $type = 'print') {
    global $THEME, $USER, $CFG;

    $output = false;   //To decide if we must really return text in "return". Activate when needed only!
    $importedentry = ($entry->sourceglossaryid == $glossary->id);
    $isteacher = isteacher($course->id);
    $ismainglossary = $glossary->mainglossary;
	
    $return = "<font size=1>";
    if (!$entry->approved) {
        $output = true;
        $return .= get_string("entryishidden","glossary");
    }
    $return .= glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook,'html');

    $return .= "</font> ";

    
    if ( (!empty($USER->id) && $glossary->allowcomments && !isguest()) || $isteacher) {
        $output = true;
        $return .= " <a title=\"" . get_string("addcomment","glossary") . "\" href=\"comment.php?id=$cm->id&eid=$entry->id\"><img src=\"comment.gif\" height=11 width=11 border=0></a> ";
    }

    if ($isteacher or (!empty($USER->id) and $glossary->studentcanpost and $entry->userid == $USER->id)) {
        // only teachers can export entries so check it out
        if ($isteacher and !$ismainglossary and !$importedentry) {
            $mainglossary = get_record("glossary","mainglossary",1,"course",$course->id);
            if ( $mainglossary ) {  // if there is a main glossary defined, allow to export the current entry
                $output = true;
                $return .= " <a title=\"" . get_string("exporttomainglossary","glossary") . "\" href=\"exportentry.php?id=$cm->id&entry=$entry->id&mode=$mode&hook=$hook\"><img src=\"export.gif\" height=11 width=11 border=0></a> ";

            }
        }

        if ( $entry->sourceglossaryid ) {
            $icon = "minus.gif";   // graphical metaphor (minus) for deleting an imported entry
        } else {
            $icon = "$CFG->pixpath/t/delete.gif";
        }

        //Decide if an entry is editable:
        // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
        // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
        $ineditperiod = ((time() - $entry->timecreated <  $CFG->maxeditingtime) || $glossary->editalways);
        if ( !$importedentry and ($isteacher or ($entry->userid == $USER->id and $ineditperiod))) {
            $output = true;
            $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=$hook\"><img src=\"";
            $return .= $icon;
            $return .= "\" height=11 width=11 border=0></a> ";
            
            $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?id=$cm->id&e=$entry->id&mode=$mode&hook=$hook\"><img src=\"$CFG->pixpath/t/edit.gif\" height=11 width=11 border=0></a>";
        } elseif ( $importedentry ) {
            $return .= " <font size=-1>" . get_string("exportedentry","glossary") . "</font>";
        }
    }
    $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)

    //If we haven't calculated any REAL thing, delete result ($return)
    if (!$output) {
        $return = '';
    }
    //Print or get
    if ($type == 'print') {
        echo $return;
    } else {
        return $return;
    }
}

function glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook, $type = 'print') {
    $return = '';

    $count = count_records("glossary_comments","entryid",$entry->id);
    if ($count) {
        $return = "<font size=1>";
        $return .= "<a href=\"comments.php?id=$cm->id&eid=$entry->id\">$count ";
        if ($count == 1) {
            $return .= get_string("comment", "glossary");
        } else {
            $return .= get_string("comments", "glossary");
        }
        $return .= "</a>";
        $return .= "</font>";
    }

    if ($type == 'print') {
        echo $return;
    } else {
        return $return;
    }
}

function  glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook,$printicons,$ratings,$aliases=true) {

    if ($aliases) {
        $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,"html");
    }
    $icons   = "";
    $return   = "";
    if ( $printicons ) {
        $icons   = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,"html");
    }
    if ($aliases || $icons || $ratings) {
        echo '<table border="0" width="100%" align="center">';
        if ( $aliases ) {
            echo '<tr><td align="center"  valign="top"><font size=1>' .
                  get_string("aliases","glossary") . ': ' . $aliases . '</td></tr>';
        }
        if ($icons) {
            echo '<tr><td align=right valign=top>'.  $icons . '</td></tr>';
        }
        if ($ratings) {
            echo '<tr><td align=right valign=top>';
            $return = glossary_print_entry_ratings($course, $entry, $ratings);
            echo '</td></tr>';
        }
        echo '</table>';
    }
    return $return;
}

function glossary_print_entry_attachment($entry,$format=NULL,$align="right",$insidetable=true) {
///   valid format values: html  : Return the HTML link for the attachment as an icon
///                        text  : Return the HTML link for tha attachment as text
///                        blank : Print the output to the screen
    if ($entry->attachment) {
          $glossary = get_record("glossary","id",$entry->glossaryid);		  
          $entry->course = $glossary->course; //used inside print_attachment
          if ($insidetable) {
              echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap>\n";
          }
          echo glossary_print_attachments($entry,$format,$align);
          if ($insidetable) {
              echo "</td></tr></table>\n";
          }
    }
}

function  glossary_print_entry_approval($cm, $entry, $mode,$align="right",$insidetable=true) {
    if ( $mode == 'approval' and !$entry->approved ) {
        if ($insidetable) {
            echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\">\n";
        }
        echo "<a title=\"" . get_string("approve","glossary"). "\" href=\"approve.php?id=$cm->id&eid=$entry->id&mode=$mode\"><img align=\"$align\" src=\"check.gif\" border=0 width=\"34\" height=\"34\"></a>\n";
        if ($insidetable) {
            echo "</td></tr></table>\n";
        }
    }
}

function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
// It returns all entries from all glossaries that matches the specified criteria 
//    within a given $course. It performs an $extended search if necessary.
// It restrict the search to only one $glossary if the $glossary parameter is set.

    global $CFG;
    if ( !$glossary ) {
        if ( $glossaries = get_records("glossary", "course", $course->id) ) {
            $glos = "";
            foreach ( $glossaries as $glossary ) {
                $glos .= "$glossary->id,";
            }
            $glos = substr($ents,0,-1);
        }
    } else {
        $glos = $glossary->id;
    }
    
    if (!isteacher($glossary->course)) {
        $glossarymodule = get_record("modules", "name", "glossary");
        $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
        $onlyvisibletable = ", {$CFG->prefix}course_modules cm";
    } else {

        $onlyvisible = "";
        $onlyvisibletable = "";
    }

    /// Some differences in syntax for entrygreSQL
    switch ($CFG->dbtype) {
    case 'postgres7':
        $LIKE = "ILIKE";   // case-insensitive
        $NOTLIKE = "NOT ILIKE";   // case-insensitive
        $REGEXP = "~*";
        $NOTREGEXP = "!~*";
    break;
    case 'mysql':
    default:
        $LIKE = "LIKE";
        $NOTLIKE = "NOT LIKE";
        $REGEXP = "REGEXP";
        $NOTREGEXP = "NOT REGEXP";
    break;
    }    

    $conceptsearch = "";
    $definitionsearch = "";


    foreach ($searchterms as $searchterm) {
        if ($conceptsearch) {
            $conceptsearch.= " OR ";
        }
        if ($definitionsearch) {
            $definitionsearch.= " OR ";
        }

        if (substr($searchterm,0,1) == "+") {
            $searchterm = substr($searchterm,1);
            $conceptsearch.= " e.concept $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
            $definitionsearch .= " e.definition $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
        } else if (substr($searchterm,0,1) == "-") {
            $searchterm = substr($searchterm,1);
            $conceptsearch .= " e.concept $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
            $definitionsearch .= " e.definition $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
        } else {
            $conceptsearch .= " e.concept $LIKE '%$searchterm%' ";
            $definitionsearch .= " e.definition $LIKE '%$searchterm%' ";
        }
    }

    if ( !$extended ) {
        $definitionsearch = "0";
    }

    $selectsql = "{$CFG->prefix}glossary_entries e,
                  {$CFG->prefix}glossary g $onlyvisibletable
             WHERE ($conceptsearch OR $definitionsearch)
               AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
               AND g.id IN ($glos) AND e.approved != 0";

    return get_records_sql("SELECT e.* 
                            FROM $selectsql ORDER BY e.concept ASC");
}

function glossary_search_entries($searchterms, $glossary, $extended) {
    $course = get_record("course","id",$glossary->course);
    return glossary_search($course,$searchterms,$extended,$glossary);
}

function glossary_file_area_name($entry) {
    global $CFG;
//  Creates a directory file name, suitable for make_upload_directory()

    // I'm doing this workaround for make it works for delete_instance also 
    //  (when called from delete_instance, glossary is already deleted so
    //   getting the course from mdl_glossary does not work)
    $module = get_record("modules","name","glossary");
    $cm = get_record("course_modules","module",$module->id,"instance",$entry->glossaryid);
    return "$cm->course/$CFG->moddata/glossary/$entry->glossaryid/$entry->id";
}

function glossary_file_area($entry) {
    return make_upload_directory( glossary_file_area_name($entry) );
}

function glossary_main_file_area($glossary) {
    $modarea = glossary_mod_file_area($glossary);
    return "$modarea/$glossary->id";
}

function glossary_mod_file_area($glossary) {
    global $CFG;
    
    return make_upload_directory( "$glossary->course/$CFG->moddata/glossary" );
}

function glossary_delete_old_attachments($entry, $exception="") {
// Deletes all the user files in the attachments area for a entry
// EXCEPT for any file named $exception

    if ($basedir = glossary_file_area($entry)) {
        if ($files = get_directory_list($basedir)) {
            foreach ($files as $file) {
                if ($file != $exception) {
                    unlink("$basedir/$file");
//                    notify("Existing file '$file' has been deleted!");
                }
            }
        }
        if (!$exception) {  // Delete directory as well, if empty
            rmdir("$basedir");
        }
    }
}
function glossary_delete_attachments($glossary) {
// Deletes all the user files in the attachments area for the glossary
    if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
        $deleted = 0;
        foreach ($entries as $entry) {
            if ( $entry->attachment ) {
                if ($basedir = glossary_file_area($entry)) {
                    if ($files = get_directory_list($basedir)) {
                        foreach ($files as $file) {
                            unlink("$basedir/$file");
                        }
                    }
                    rmdir("$basedir");
                    $deleted++;
                }
            }            
        }
        if ( $deleted ) {
            $attachmentdir = glossary_main_file_area($glossary);
            $glossarydir = glossary_mod_file_area($glossary);
            
            rmdir("$attachmentdir");
            if (!$files = get_directory_list($glossarydir) ) {
                rmdir( "$glossarydir" );
            }
        }        
    }
}

function glossary_copy_attachments($entry, $newentry) {
/// Given a entry object that is being copied to glossaryid,
/// this function checks that entry
/// for attachments, and if any are found, these are
/// copied to the new glossary directory.

    global $CFG;

    $return = true;

    if ($entries = get_records_select("glossary_entries", "id = '$entry->id' AND attachment <> ''")) {
        foreach ($entries as $curentry) {
            $oldentry->id = $entry->id;
            $oldentry->course = $entry->course;
            $oldentry->glossaryid = $curentry->glossaryid;
            $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
            if (is_dir($oldentrydir)) {

                $newentrydir = glossary_file_area($newentry);
                if (! copy("$oldentrydir/$newentry->attachment", "$newentrydir/$newentry->attachment")) {
                    $return = false;
                }
            }
        }
     }
    return $return;
}

function glossary_move_attachments($entry, $glossaryid) {
/// Given a entry object that is being moved to glossaryid,
/// this function checks that entry
/// for attachments, and if any are found, these are
/// moved to the new glossary directory.

    global $CFG;

    $return = true;

    if ($entries = get_records_select("glossary_entries", "glossaryid = '$entry->id' AND attachment <> ''")) {
        foreach ($entries as $entry) {
            $oldentry->course = $entry->course;
            $oldentry->glossaryid = $entry->glossaryid;
            $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
            if (is_dir($oldentrydir)) {
                $newentry = $oldentry;
                $newentry->glossaryid = $glossaryid;
                $newentrydir = "$CFG->dataroot/".glossary_file_area_name($newentry);
                if (! @rename($oldentrydir, $newentrydir)) {
                    $return = false;
                }
            }
        }
    }
    return $return;
}

function glossary_add_attachment($entry, $newfile) {
// $entry is a full entry record, including course and glossary
// $newfile is a full upload array from $_FILES
// If successful, this function returns the name of the file

    global $CFG;

    if (empty($newfile['name'])) {
        return "";
    }

    $newfile_name = clean_filename($newfile['name']);

    if (valid_uploaded_file($newfile)) {
        if (! $newfile_name) {
            notify("This file had a wierd filename and couldn't be uploaded");

        } else if (! $dir = glossary_file_area($entry)) {
            notify("Attachment could not be stored");
            $newfile_name = "";

        } else {
            if (move_uploaded_file($newfile['tmp_name'], "$dir/$newfile_name")) {
                chmod("$dir/$newfile_name", $CFG->directorypermissions);
                glossary_delete_old_attachments($entry, $newfile_name);
            } else {
                notify("An error happened while saving the file on the server");
                $newfile_name = "";
            }
        }
    } else {
        $newfile_name = "";
    }

    return $newfile_name;
}

function glossary_print_attachments($entry, $return=NULL, $align="left") {
// if return=html, then return a html string.
// if return=text, then return a text-only string.
// otherwise, print HTML for non-images, and return image HTML
//     if attachment is an image, $align set its aligment.
    global $CFG;
    
    $newentry = $entry;
    if ( $newentry->sourceglossaryid ) {
        $newentry->glossaryid = $newentry->sourceglossaryid;
    }

    $filearea = glossary_file_area_name($newentry);

    $imagereturn = "";
    $output = "";

    if ($basedir = glossary_file_area($newentry)) {
        if ($files = get_directory_list($basedir)) {
            $strattachment = get_string("attachment", "glossary");
            $strpopupwindow = get_string("popupwindow");
            foreach ($files as $file) {
                $icon = mimeinfo("icon", $file);
                if ($CFG->slasharguments) {
                    $ffurl = "file.php/$filearea/$file";
                } else {
                    $ffurl = "file.php?file=/$filearea/$file";
                }
                $image = "<img border=0 src=\"$CFG->pixpath/f/$icon\" height=16 width=16 alt=\"$strpopupwindow\">";

                if ($return == "html") {
                    $output .= "<a target=_image href=\"$CFG->wwwroot/$ffurl\">$image</a> ";
                    $output .= "<a target=_image href=\"$CFG->wwwroot/$ffurl\">$file</a><br />";
                } else if ($return == "text") {
                    $output .= "$strattachment $file:\n$CFG->wwwroot/$ffurl\n";

                } else {
                    if ($icon == "image.gif") {    // Image attachments don't get printed as links
                        $imagereturn .= "<img src=\"$CFG->wwwroot/$ffurl\" align=\"$align\">";
                    } else {
                        link_to_popup_window("/$ffurl", "attachment", $image, 500, 500, $strattachment);
                        echo "<a target=_image href=\"$CFG->wwwroot/$ffurl\">$file</a>";
                        echo "<br />";
                    }
                }
            }
        }
    }

    if ($return) {
        return $output;
    }

    return $imagereturn;
}

function glossary_print_tabbed_table_start($data, $currenttab, $tTHEME = NULL) {

if ( !$tTHEME ) {
     global $THEME;
     $tTHEME = $THEME;
}

$tablecolor           = $tTHEME->TabTableBGColor;
$currenttabcolor      = $tTHEME->ActiveTabColor;
$tabcolor             = $tTHEME->InactiveTabColor;
$inactivefontcolor    = $tTHEME->InactiveFontColor;

$tablewidth           = $tTHEME->TabTableWidth;
$tabsperrow           = $tTHEME->TabsPerRow;
$tabseparation        = $tTHEME->TabSeparation;

$tabs                 = count($data);
$tabwidth             = (int) (100 / $tabsperrow);

$currentrow           = ( $currenttab - ( $currenttab % $tabsperrow) ) / $tabsperrow;

$numrows              = (int) ( $tabs / $tabsperrow ) + 1;

?>
  <center>
  <table border="0" cellpadding="0" cellspacing="0" width="<?php p($tablewidth) ?>">
    <tr>
      <td width="100%">

      <table border="0" cellpadding="0" cellspacing="0" width="100%">

<?php
$tabproccessed = 0;
for ($row = 0; $row < $numrows; $row++) {
     echo "<tr>\n";
     if ( $row != $currentrow ) {
          for ($col = 0; $col < $tabsperrow; $col++) {
               if ( $tabproccessed < $tabs ) {
                    if ( $col == 0 ) {
                        echo "<td width=\"$tabseparation\" align=\"center\">&nbsp;</td>";
                    }
                    if ($tabproccessed == $currenttab) {
                         $currentcolor = $currenttabcolor;
                         $currentstyle = 'generaltabselected';
                    } else {
                         $currentcolor = $tabcolor;
                         $currentstyle = 'generaltab';
                    }
                    echo "<td class=\"$currentstyle\" width=\"$tabwidth%\" bgcolor=\"$currentcolor\" align=\"center\"><b>";
                    if ($tabproccessed != $currenttab and $data[$tabproccessed]->link) {
                        echo "<a href=\"" . $data[$tabproccessed]->link . "\">";
                    }

                    if ( !$data[$tabproccessed]->link ) {
                        echo "<font color=\"$inactivefontcolor\">";
                    }
                    echo $data[$tabproccessed]->caption;
                    if ( !$data[$tabproccessed]->link ) {
                        echo "</font>";
                    }

                    if ($tabproccessed != $currenttab and $data[$tabproccessed]->link) {
                        echo "</a>";
                    }
                    echo "</b></td>";
                    
                    if ( $col < $tabsperrow ) {
                        echo "<td width=\"$tabseparation\" align=\"center\">&nbsp;</td>";
                    }
               } else {
                    $currentcolor = "";
               }
               $tabproccessed++;
          }
     } else {
          $firsttabincurrentrow = $tabproccessed;
          $tabproccessed += $tabsperrow;
     }
     echo "</tr><tr><td colspan=" . (2* $tabsperrow) . " ></td></tr>\n";
}
     echo "<tr>\n";
          $tabproccessed = $firsttabincurrentrow;
          for ($col = 0; $col < $tabsperrow; $col++) {
               if ( $tabproccessed < $tabs ) {
                    if ( $col == 0 ) {
                        echo "<td width=\"$tabseparation\" align=\"center\">&nbsp;</td>";
                    }
                    if ($tabproccessed == $currenttab) {
                         $currentcolor = $currenttabcolor;
                         $currentstyle = 'generaltabselected';
                    } else {
                         $currentcolor = $tabcolor;
                         $currentstyle = 'generaltab';
                    }

                    if (!isset($data[$tabproccessed]->link)) {
                        $data[$tabproccessed]->link = NULL;
                    }
                    echo "<td class=\"$currentstyle\" width=\"$tabwidth%\" bgcolor=\"$currentcolor\" align=\"center\"><b>";
                    if ($tabproccessed != $currenttab and $data[$tabproccessed]->link) {
                        echo "<a href=\"" . $data[$tabproccessed]->link . "\">";
                    }

                    if ( !$data[$tabproccessed]->link ) {
                        echo "<font color=\"$inactivefontcolor\">";
                    }
                    echo $data[$tabproccessed]->caption;
                    if ( !$data[$tabproccessed]->link ) {
                        echo "</font>";
                    }

                    if ($tabproccessed != $currenttab and $data[$tabproccessed]->link) {
                        echo "</a>";
                    }
                    echo "</b></td>";

                    if ($col < $tabsperrow) {
                         echo "<td width=\"$tabseparation\" align=\"center\">&nbsp;</td>";
                    }
               } else {
                    if ($numrows > 1) {
                         $currentcolor = $tabcolor;
                    } else {
                         $currentcolor = "";
                    }
                    echo "<td colspan = " . (2 * ($tabsperrow - $col)) . " bgcolor=\"$currentcolor\" align=\"center\">";
                    echo "</td>";

                    $col = $tabsperrow;
               }
               $tabproccessed++;
          }
     echo "</tr>\n";
     ?>

      </table>
      </td>
    </tr>
    <tr>
      <td width="100%" bgcolor="<?php p($tablecolor) ?>"><hr></td>
    </tr>
    <tr>
      <td width="100%" bgcolor="<?php p($tablecolor) ?>">
          <center>
<?php
}

function glossary_print_tabbed_table_end() {
     echo "</center><p></td></tr></table></center>";
}

function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
    if ($glossary->showalphabet) {
        echo '<center>' . get_string("explainalphabet","glossary") . '<p>';
    }
    glossary_print_special_links($cm, $glossary, $mode, $hook);

    glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);

    glossary_print_all_links($cm, $glossary, $mode, $hook);
	 
    glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
}

function glossary_print_addentry_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
    echo '<center>' . get_string("explainaddentry","glossary") . '<p>';
}

function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
    echo '<center>' . get_string("explainimport","glossary") . '<p>';
}

function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
    echo '<center>' . get_string("explainexport","glossary") . '<p>';
}

function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
    if ( $mode != 'date' ) {
        if ($glossary->showalphabet) {
            echo '<center>' . get_string("explainalphabet","glossary") . '<p>';
        }

        glossary_print_special_links($cm, $glossary, $mode, $hook);

        glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);

        glossary_print_all_links($cm, $glossary, $mode, $hook);
    } else {
        glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
    }
}

function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
    if ($glossary->showalphabet) {
        echo '<center>' . get_string("explainalphabet","glossary") . '<br />';
    }

    glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
    glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
    glossary_print_all_links($cm, $glossary, $mode, $hook);
//    echo "<br />";
}

function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
global $CFG, $THEME;
     echo '<table border=0 width=100%>';
     echo '<tr>';

     echo '<td align=center width=20%>';
     if ( isteacher($glossary->course) ) {
             $options['id'] = $cm->id;
             $options['mode'] = 'cat';
             $options['hook'] = $hook;
             echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
     }
     echo '</td>';

     echo '<td align=center width=60%>';
     echo '<b>';

     $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
     $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");

     $categories = get_records("glossary_categories", "glossaryid", $glossary->id, "name ASC");
     $selected = '';
     if ( $categories ) {
          foreach ($categories as $currentcategory) {
                 $url = $currentcategory->id;
                 if ( $category ) {
                     if ($currentcategory->id == $category->id) {
                         $selected = $url;
                     }
                 }
                 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
          }
     }
     if ( !$selected ) {
         $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
     }

     if ( $category ) {
        echo format_text($category->name);
     } else {
        if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {

            echo get_string("entrieswithoutcategory","glossary");
            $selected = GLOSSARY_SHOW_NOT_CATEGORISED;

        } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {

            echo get_string("allcategories","glossary");
            $selected = GLOSSARY_SHOW_ALL_CATEGORIES;

        }
     }
     echo '</b></td>';
     echo '<td align=center width=20%>';

     echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=cat&hook=", $menu, "catmenu", $selected, "",
                      "", "", false);

     echo '</td>';
     echo '</tr>';

     echo '</table>';
}

function glossary_print_all_links($cm, $glossary, $mode, $hook) {
global $CFG;  
     if ( $glossary->showall) {
         $strallentries       = get_string("allentries", "glossary");
         if ( $hook == 'ALL' ) {
              echo "<b>$strallentries</b>";
         } else {
              $strexplainall = strip_tags(get_string("explainall","glossary"));
              echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=ALL\">$strallentries</a>";
         }
     }
}

function glossary_print_special_links($cm, $glossary, $mode, $hook) {
global $CFG;
     if ( $glossary->showspecial) {
         $strspecial          = get_string("special", "glossary");
         if ( $hook == 'SPECIAL' ) {
              echo "<b>$strspecial</b> | ";
         } else {
              $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
              echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=SPECIAL\">$strspecial</a> | ";
         }
     }
}

function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
global $CFG;
     if ( $glossary->showalphabet) {
          $alphabet = explode(",", get_string("alphabet"));
          $letters_by_line = 14;
          for ($i = 0; $i < count($alphabet); $i++) {
              if ( $hook == $alphabet[$i] and $hook) {
                   echo "<b>$alphabet[$i]</b>";
              } else {
                   echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=$alphabet[$i]&sortkey=$sortkey&sortorder=$sortorder\">$alphabet[$i]</a>";
              }
              if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
                   echo ' | ';
              } else {
                   echo '<br>';
              }
          }
     }
}

function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
global $CFG;

    $asc    = get_string("ascending","glossary");
    $desc   = get_string("descending","glossary");
    $bopen  = '<b>';
    $bclose = '</b>';
    
     $neworder = '';
     if ( $sortorder ) {
         if ( $sortorder == 'asc' ) {
             $neworder = '&sortorder=desc';
             $newordertitle = $desc;
         } else {
             $neworder = '&sortorder=asc';
             $newordertitle = $asc;
         }
         $icon = " <img src=\"$sortorder.gif\" border=0 width=16 height=16>";
     } else {
         if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
               $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
             $icon = "";
             $newordertitle = $asc;
         } else {
             $newordertitle = $desc;
             $neworder = '&sortorder=desc';
             $icon = ' <img src="asc.gif" border=0 width=16 height=16>';
         }
     }
     $ficon     = '';
     $fneworder = '';
     $fbtag     = '';
     $fendbtag  = '';

     $sicon     = '';
     $sneworder = '';

     $sbtag      = '';
     $fbtag      = '';
     $fendbtag      = '';
     $sendbtag      = '';

     $sendbtag  = '';

     if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
         $ficon       = $icon;
         $fneworder   = $neworder;
         $fordertitle = $newordertitle;
         $sordertitle = $asc;
         $fbtag       = $bopen;
         $fendbtag    = $bclose;
     } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
         $sicon = $icon;
         $sneworder   = $neworder;
         $fordertitle = $asc;
         $sordertitle = $newordertitle;
         $sbtag       = $bopen;
         $sendbtag    = $bclose;
     } else {
         $fordertitle = $asc;
         $sordertitle = $asc;
     }

     if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
         $forder = 'CREATION';
         $sorder =  'UPDATE';
         $fsort  = get_string("sortbycreation", "glossary");
         $ssort  = get_string("sortbylastupdate", "glossary");

         $sort        = get_string("sortchronogically", "glossary");
     } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
         $forder = 'FIRSTNAME';
         $sorder =  'LASTNAME';
         $fsort  = get_string("firstname");
         $ssort  = get_string("lastname");

         $sort        = get_string("sortby", "glossary");
     }

     echo "<br>$sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$sorder$sneworder&mode=$mode\">$ssort$sicon</a>$sendbtag | ".
                          "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$forder$fneworder&mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
}

function glossary_sort_entries ( $entry0, $entry1 ) {
    if ( strtolower(ltrim($entry0->concept)) < strtolower(ltrim($entry1->concept)) ) {
        return -1;
    } elseif ( strtolower(ltrim($entry0->concept)) > strtolower(ltrim($entry1->concept)) ) {
        return 1;
    } else {
        return 0;
    }
}

function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
    global $THEME, $CFG, $USER;

    $colour = $THEME->cellheading2;

    $user = get_record("user", "id", $comment->userid);
    $strby = get_string("writtenby","glossary");
    $fullname = fullname($user, isteacher($course->id));

    echo '<table align="center" border="0" width="70%" cellpadding="3" cellspacing="0" class="forumpost">';
    echo "<tr>";
    echo "<tr><td bgcolor=\"$THEME->cellcontent2\" class=\"forumpostpicture\" width=\"35\" valign=\"top\">";
    print_user_picture($user->id, $course->id, $user->picture);
    echo "</td>";
    echo "<td bgcolor=\"$THEME->cellheading\" class=\"forumpostheader\" width=\"100%\">";
    echo "<p>";
    echo "<font size=2><a href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></font><br />";
    echo "<font size=1>".get_string("lastedited").": ".userdate($comment->timemodified)."</font>";
    echo "</p></td></tr>";

    echo "<tr><td bgcolor=\"$THEME->cellcontent2\" class=\"forumpostside\" width=\"10\">";
    echo "&nbsp;";
    echo "</td><td bgcolor=\"$THEME->cellcontent\" class=\"forumpostmessage\">\n";

    echo format_text($comment->comment, $comment->format);

    echo "<div align=right><p align=right>";
    $ineditperiod = ((time() - $comment->timemodified <  $CFG->maxeditingtime) || $glossary->editalways);
    if ( ($glossary->allowcomments &&  $ineditperiod && $USER->id == $comment->userid)  || isteacher($course->id) ) {
        echo "<a href=\"comment.php?id=$cm->id&eid=$entry->id&cid=$comment->id&action=edit\"><img  
               alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" height=11 width=11 border=0></a> ";
    }
    if ( ($glossary->allowcomments && $USER->id == $comment->userid) || isteacher($course->id) ) {
        echo "<a href=\"comment.php?id=$cm->id&eid=$entry->id&cid=$comment->id&action=delete\"><img  
               alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" height=11 width=11 border=0></a>";
    }
    
    echo "</p>";
    echo "</div>";
    echo "</td></tr>\n</table>\n\n";

}

function  glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
    
    global $USER;

    $ratingsmenuused = false;
    if (!empty($ratings) and !empty($USER->id)) {
        $useratings = true;
        if ($ratings->assesstimestart and $ratings->assesstimefinish) {
            if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
                $useratings = false;
            }
        }
        if ($useratings) {
            if (isteacher($course->id)) {
                glossary_print_ratings_mean($entry->id, $ratings->scale);
                if ($USER->id != $entry->userid) {
                     glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
                     $ratingsmenuused = true;
                }
            } else if ($USER->id == $entry->userid) {
                glossary_print_ratings_mean($entry->id, $ratings->scale);
            } else if (!empty($ratings->allow) ) {
                glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
                $ratingsmenuused = true;
            }
        }
    }
    return $ratingsmenuused;
}

function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
    global $THEME, $USER,$CFG;

    $colour = $THEME->cellheading2;

    echo "\n<center><table width=95% border=0><tr>";
    echo "<td width=100%\">";
    if ( $entries ) {
        foreach ( $entries as $entry ) {
            if (! $glossary = get_record("glossary", "id", $entry->glossaryid)) {
                error("Glossary ID was incorrect or no longer exists");
            }
            if (! $course = get_record("course", "id", $glossary->course)) {
                error("Glossary is misconfigured - don't know what course it's from");
            }
            if (!$cm = get_coursemodule_from_instance("glossary", $entry->glossaryid, $glossary->course) ) {
                error("Glossary is misconfigured - don't know what course module it is ");
            }

            //If displayformat is present, override glossary->displayformat
            if ($displayformat < 0) {
                $dp = $glossary->displayformat;
            } else {
                $dp = $displayformat;
            }

            //Get popupformatname
            $format = get_record('glossary_formats','name',$dp);
            $displayformat = $format->popupformatname;

            //Check displayformat variable and set to default if necessary
            if (!$displayformat) {
                $displayformat = 'dictionary';
            }

            $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
            $functionname = 'glossary_show_entry_'.$displayformat;

            if (file_exists($formatfile)) {
                include_once($formatfile);
                if (function_exists($functionname)) {
                    $functionname($course, $cm, $glossary, $entry,'','','','');
                }
            }
        }
    }
    echo "</td>";
    echo "</tr></table></center>";
}

function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
global $CFG;
    glossary_check_moddata_dir($glossary);

    if (!$h = glossary_open_xml($glossary)) {
        error("An error occurred while opening a file to write to.");
    }

    $status = fwrite ($h,glossary_start_tag("INFO",1,true));
        fwrite ($h,glossary_full_tag("NAME",2,false,$glossary->name));
        fwrite ($h,glossary_full_tag("INTRO",2,false,$glossary->intro));
        fwrite ($h,glossary_full_tag("STUDENTCANPOST",2,false,$glossary->studentcanpost));
        fwrite ($h,glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries));
        fwrite ($h,glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat));
        fwrite ($h,glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial));
        fwrite ($h,glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet));
        fwrite ($h,glossary_full_tag("SHOWALL",2,false,$glossary->showall));
        fwrite ($h,glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments));
        fwrite ($h,glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink));
        fwrite ($h,glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval));
        fwrite ($h,glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary));
        fwrite ($h,glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage));

        if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
            $status = fwrite ($h,glossary_start_tag("ENTRIES",2,true));
            foreach ($entries as $entry) {
                $permissiongranted = 1;
                if ( $hook ) {
                    switch ( $hook ) {
                    case "ALL":
                    case "SPECIAL":
                    break;
                    default:
                        $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
                    break;
                    }
                }
                if ( $hook ) {
                    switch ( $hook ) {
                    case GLOSSARY_SHOW_ALL_CATEGORIES:
                    break;
                    case GLOSSARY_SHOW_NOT_CATEGORISED:
                        $permissiongranted = !record_exists("glossary_entries_categories","entryid",$entry->id);
                    break;
                    default:
                        $permissiongranted = record_exists("glossary_entries_categories","entryid",$entry->id, "categoryid",$hook);
                    break;
                    }
                }
                if ( $entry->approved and $permissiongranted ) {
                    $status = fwrite($h,glossary_start_tag("ENTRY",3,true));
                    fwrite($h,glossary_full_tag("CONCEPT",4,false,trim($entry->concept)));
                    fwrite($h,glossary_full_tag("DEFINITION",4,false,$entry->definition));
                    fwrite($h,glossary_full_tag("FORMAT",4,false,$entry->format));
                    fwrite($h,glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink));
                    fwrite($h,glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive));
                    fwrite($h,glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch));
                    fwrite($h,glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry));

                    if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
                        $status = fwrite ($h,glossary_start_tag("ALIASES",4,true));
                        foreach ($aliases as $alias) {
                            $status = fwrite ($h,glossary_start_tag("ALIAS",5,true));
                                fwrite($h,glossary_full_tag("NAME",6,false,trim($alias->alias)));
                            $status = fwrite($h,glossary_end_tag("ALIAS",5,true));
                        }
                        $status = fwrite($h,glossary_end_tag("ALIASES",4,true));
                    }
                    if ( $catentries = get_records("glossary_entries_categories","entryid",$entry->id) ) {
                        $status = fwrite ($h,glossary_start_tag("CATEGORIES",4,true));
                        foreach ($catentries as $catentry) {
                            $category = get_record("glossary_categories","id",$catentry->categoryid);

                            $status = fwrite ($h,glossary_start_tag("CATEGORY",5,true));
                                fwrite($h,glossary_full_tag("NAME",6,false,$category->name));
                                fwrite($h,glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink));
                            $status = fwrite($h,glossary_end_tag("CATEGORY",5,true));
                        }
                        $status = fwrite($h,glossary_end_tag("CATEGORIES",4,true));
                    }

                    $status =fwrite($h,glossary_end_tag("ENTRY",3,true));
                }
            }
            $status =fwrite ($h,glossary_end_tag("ENTRIES",2,true));

        }


    $status =fwrite ($h,glossary_end_tag("INFO",1,true));

    $h = glossary_close_xml($h);
}
// Functions designed by Eloy Lafuente
//
//Function to create, open and write header of the xml file
function glossary_open_xml($glossary) {

        global $CFG;
        
        $status = true;

        //Open for writing

        $glossaryname = clean_filename(strip_tags($glossary->name)); 
        $pathname = make_upload_directory("$glossary->course/glossary/$glossaryname");
        $filename = "$pathname/glossary.xml";

        if (!$h = fopen($filename,"w")) {
            notify("Error opening '$filename'");
            return false;
        }

        //Writes the header
        $status = fwrite ($h,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        if ($status) {
            $status = fwrite ($h,glossary_start_tag("GLOSSARY",0,true));
        }
        if ($status) {
            return $h;
        } else {
            return false;
        }
}

function glossary_read_imported_file($file) {
require_once "../../lib/xmlize.php";
    $h = fopen($file,"r");
    $line = '';
    if ($h) {
        while ( !feof($h) ) {
           $char = fread($h,1024);
           $line .= $char;
        }
        fclose($h);
	}
    return xmlize($line, 0);
}
//Close the file
function glossary_close_xml($h) {
        $status = fwrite ($h,glossary_end_tag("GLOSSARY",0,true));
        return fclose($h);
}

//Return the xml start tag 
function glossary_start_tag($tag,$level=0,$endline=false) {
        if ($endline) {
           $endchar = "\n";
        } else {
           $endchar = "";
        }
        return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
}
    
//Return the xml end tag 
function glossary_end_tag($tag,$level=0,$endline=true) {
        if ($endline) {
           $endchar = "\n";
        } else {
           $endchar = "";
        }
        return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
}
    
//Return the start tag, the contents and the end tag
function glossary_full_tag($tag,$level=0,$endline=true,$content,$to_utf=true) {
        $st = glossary_start_tag($tag,$level,$endline);
        $co="";
        if ($to_utf) {
            $co = preg_replace("/\r\n|\r/", "\n", utf8_encode(htmlspecialchars($content)));
        } else {
            $co = preg_replace("/\r\n|\r/", "\n", htmlspecialchars($content));
        }
        $et = glossary_end_tag($tag,0,true);
        return $st.$co.$et;
}

    //Function to check and create the needed moddata dir to
    //save all the mod backup files. We always name it moddata
    //to be able to restore it, but in restore we check for
    //$CFG->moddata !!
function glossary_check_moddata_dir($glossary) {
  
    global $CFG;

    $status = glossary_check_dir_exists($CFG->dataroot."/$glossary->course",true);
    if ( $status ) {
        $status = glossary_check_dir_exists($CFG->dataroot."/$glossary->course/glossary",true);
        if ( $status ) {
            $status = glossary_check_dir_exists($CFG->dataroot."/$glossary->course/glossary/". clean_filename($glossary->name),true);
        }
    }
    return $status;
}

//Function to check if a directory exists
//and, optionally, create it
function glossary_check_dir_exists($dir,$create=false) {

    global $CFG; 

    $status = true;
    if(!is_dir($dir)) {
        if (!$create) {
            $status = false;
        } else {
            umask(0000);
            $status = mkdir ($dir,$CFG->directorypermissions);
        }
    }
    return $status;
}
/*
* Adding grading functions 
*/

function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
/// Returns a list of ratings for a particular entry - sorted.
    global $CFG;
    return get_records_sql("SELECT u.*, r.rating, r.time 
                              FROM {$CFG->prefix}glossary_ratings r, 
                                   {$CFG->prefix}user u
                             WHERE r.entryid = '$entryid' 
                               AND r.userid = u.id 
                             ORDER BY $sort");
}

function glossary_get_user_grades($glossaryid) {
/// Get all user grades for a glossary
    global $CFG;

    return get_records_sql("SELECT r.id, e.userid, r.rating
                              FROM {$CFG->prefix}glossary_entries e, 
                                   {$CFG->prefix}glossary_ratings r
                             WHERE e.glossaryid = '$glossaryid' 
                               AND r.entryid = e.id
                             ORDER by e.userid ");
}

function glossary_count_unrated_entries($glossaryid, $userid) {
// How many unrated entries are in the given glossary for a given user?
    global $CFG;
    if ($entries = get_record_sql("SELECT count(*) as num
                                   FROM {$CFG->prefix}glossary_entries
                                  WHERE glossaryid = '$glossaryid' 
                                    AND userid <> '$userid' ")) {

        if ($rated = get_record_sql("SELECT count(*) as num 
                                       FROM {$CFG->prefix}glossary_entries e, 
                                            {$CFG->prefix}glossary_ratings r
                                      WHERE e.glossaryid = '$glossaryid'
                                        AND e.id = r.entryid 
                                        AND r.userid = '$userid'")) {
            $difference = $entries->num - $rated->num;
            if ($difference > 0) {
                return $difference;
            } else {
                return 0;    // Just in case there was a counting error
            }
        } else {
            return $entries->num;
        }
    } else {
        return 0;
    }
}

function glossary_print_ratings_mean($entryid, $scale) {
/// Print the multiple ratings on a entry given to the current user by others.
/// Scale is an array of ratings

    static $strrate;

    $mean = glossary_get_ratings_mean($entryid, $scale);
    
    if ($mean !== "") {

        if (empty($strratings)) {
            $strratings = get_string("ratings", "glossary");
        }

        echo "<font size=-1>$strratings: ";
        link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
        echo "</font>";
    }
}


function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
/// Return the mean rating of a entry given to the current user by others.
/// Scale is an array of possible ratings in the scale
/// Ratings is an optional simple array of actual ratings (just integers)

    if (!$ratings) {
        $ratings = array();
        if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
            foreach ($rates as $rate) {
                $ratings[] = $rate->rating;
            }
        }
    }

    $count = count($ratings);

    if ($count == 0) {
        return "";

    } else if ($count == 1) {
        return $scale[$ratings[0]];

    } else {
        $total = 0;
        foreach ($ratings as $rating) {
            $total += $rating;
        }
        $mean = round( ((float)$total/(float)$count) + 0.001);  // Little fudge factor so that 0.5 goes UP
    
        if (isset($scale[$mean])) {
            return $scale[$mean]." ($count)";
        } else {
            return "$mean ($count)";    // Should never happen, hopefully
        }
    }
}

function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
/// Return a summary of entry ratings given to the current user by others.
/// Scale is an array of possible ratings in the scale
/// Ratings is an optional simple array of actual ratings (just integers)

    if (!$ratings) {
        $ratings = array();
        if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
            foreach ($rates as $rate) {
                $rating[] = $rate->rating;
            }
        }
    }


    if (!$count = count($ratings)) {
        return "";
    }


    foreach ($scale as $key => $scaleitem) {
        $sumrating[$key] = 0;
    }

    foreach ($ratings as $rating) {
        $sumrating[$rating]++;
    }

    $summary = "";
    foreach ($scale as $key => $scaleitem) {
        $summary = $sumrating[$key].$summary;
        if ($key > 1) {
            $summary = "/$summary";
        }
    }
    return $summary;
}

function glossary_print_rating_menu($entryid, $userid, $scale) {
/// Print the menu of ratings as part of a larger form.  
/// If the entry has already been - set that value.
/// Scale is an array of ratings

    static $strrate;

    if (!$rating = get_record("glossary_ratings", "userid", $userid, "entryid", $entryid)) {
        $rating->rating = -999;
    }

    if (empty($strrate)) {
        $strrate = get_string("rate", "glossary");
    }

    choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
}


function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
// Returns the html code to represent any pagging bar. Paramenters are:
//
//  Mandatory:
//     $totalcount: total number of records to be displayed
//     $page: page currently selected (0 based)
//     $perpage: number of records per page
//     $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
//  Optional:
//     $maxpageallowed: maximum number of page allowed.
//     $maxdisplay: maximum number of page links to show in the bar
//     $separator: string to be used between pages in the bar
//     $specialtext: string to be showed as an special link
//     $specialvalue: value (page) to be used in the special link
//     $previousandnext: to decide if we want the previous and next links
//
// The function dinamically show the first and last pages, and "scroll" over pages.
// Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
// could replace the general one. ;-)

    $code = '';

    $showspecial = false;
    $specialselected = false;

    //Check if we have to show the special link
    if (!empty($specialtext)) {
        $showspecial = true;
    }
    //Check if we are with the special link selected
    if ($showspecial && $page == $specialvalue) {
        $specialselected = true;
    } 

    //If there are results (more than 1 page)
    if ($totalcount > $perpage) {
        $code .= "<center>";
        $code .= "<p>".get_string("page").":";

        $maxpage = (int)(($totalcount-1)/$perpage);

        //Lower and upper limit of page
        if ($page < 0) {
            $page = 0;
        }
        if ($page > $maxpageallowed) {
            $page = $maxpageallowed;
        }
        if ($page > $maxpage) {
            $page = $maxpage;
        }

        //Calculate the window of pages
        $pagefrom = $page - ((int)($maxdisplay / 2));
        if ($pagefrom < 0) {
            $pagefrom = 0;
        }
        $pageto = $pagefrom + $maxdisplay - 1;
        if ($pageto > $maxpageallowed) {
            $pageto = $maxpageallowed;
        }
        if ($pageto > $maxpage) {
            $pageto = $maxpage;
        }

        //Some movements can be necessary if don't see enought pages
        if ($pageto - $pagefrom < $maxdisplay - 1) {
            if ($pageto - $maxdisplay + 1 > 0) {
                $pagefrom = $pageto - $maxdisplay + 1;
            }
        }

        //Calculate first and last if necessary
        $firstpagecode = '';
        $lastpagecode = '';
        if ($pagefrom > 0) {
            $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
            if ($pagefrom > 1) {
                $firstpagecode .= "$separator...";
            }
        }
        if ($pageto < $maxpage) {
            if ($pageto < $maxpage -1) {
                $lastpagecode = "$separator...";
            }
            $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
        }

        //Previous
        if ($page > 0 && $previousandnext) {
            $pagenum = $page - 1;
            $code .= "&nbsp;(<a  href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
        }

        //Add first
        $code .= $firstpagecode;

        $pagenum = $pagefrom;

        //List of maxdisplay pages
        while ($pagenum <= $pageto) {
            $pagetoshow = $pagenum +1;
            if ($pagenum == $page && !$specialselected) {
                $code .= "$separator$pagetoshow";
            } else {
                $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
            }
            $pagenum++;
        }

        //Add last
        $code .= $lastpagecode;

        //Next
        if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
            $pagenum = $page + 1;
            $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
        }

        //Add special
        if ($showspecial) {
            $code .= '<br />';
            if ($specialselected) {
                $code .= $specialtext;
            } else {
                $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
            }
        }

        //End html
        $code .= "</p>";
        $code .= "</center>";
    }

    return $code;
}

?>