moodle-mod_hotpot /locallib.php

Language PHP Lines 2024
MD5 Hash 314aabfc644e9b57b97bf0274a86a537
Repository https://github.com/KieranRBriggs/moodle-mod_hotpot.git View Raw File
   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
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Library of internal classes and functions for module hotpot
 *
 * All the hotpot specific functions, needed to implement the module
 * logic, should go to here. Instead of having bunch of function named
 * hotpot_something() taking the hotpot instance as the first
 * parameter, we use a class hotpot that provides all methods.
 *
 * @package   mod-hotpot
 * @copyright 2010 Gordon Bateson <gordon.bateson@gmail.com>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

require_once(dirname(__FILE__).'/lib.php');     // we extend this library here
require_once($CFG->libdir . '/gradelib.php');   // we use some rounding and comparing routines here

/**
 * Full-featured hotpot API
 *
 * This wraps the hotpot database record with a set of methods that are called
 * from the module itself. The class should be initialized right after you get
 * $hotpot, $cm and $course records at the begining of the script.
 */
class hotpot {

    /**
     * internal codes to indicate what text is to be used
     * for the name and introduction of a HotPot instance
     */
    const TEXTSOURCE_FILE           = 0; // was TEXTSOURCE_QUIZ
    const TEXTSOURCE_FILENAME       = 1;
    const TEXTSOURCE_FILEPATH       = 2;
    const TEXTSOURCE_SPECIFIC       = 3;

    /**
     * database codes to indicate what navigation aids are used
     * when the quiz apears in the browser
     */
    const NAVIGATION_NONE           = 0; // was 6
    const NAVIGATION_MOODLE         = 1; // was NAVIGATION_BAR
    const NAVIGATION_FRAME          = 2;
    const NAVIGATION_EMBED          = 3; // was NAVIGATION_IFRAME
    const NAVIGATION_ORIGINAL       = 4;
    const NAVIGATION_TOPBAR         = 5; // was NAVIGATION_GIVEUP but that was replaced by stopbutton

    /**
     * database codes to indicate the grading method for a HotPot instance
     */
    const GRADEMETHOD_HIGHEST       = 1;
    const GRADEMETHOD_AVERAGE       = 2;
    const GRADEMETHOD_FIRST         = 3;
    const GRADEMETHOD_LAST          = 4;

    /**
     * database codes to indicate the source/config location for a HotPot instance
     */
    const LOCATION_COURSEFILES      = 0;
    const LOCATION_SITEFILES        = 1;
    const LOCATION_WWW              = 2;

    /**
     * bit-masks used to extract bits from the hotpot "title" setting
     */
    const TITLE_SOURCE              = 0x03; // 1st - 2nd bits
    const TITLE_UNITNAME            = 0x04; // 3rd bit
    const TITLE_SORTORDER           = 0x08; // 4th bit

    /**
     * database codes for the following time fields
     *  - timelimit : the maximum length of one attempt
     *  - delay3 : the delay after end of quiz before control returns to Moodle
     */
    const TIME_SPECIFIC             = 0;
    const TIME_TEMPLATE             = -1;
    const TIME_AFTEROK              = -2;
    const TIME_DISABLE              = -3;

    const CONTINUE_RESUMEQUIZ       = 1;
    const CONTINUE_RESTARTQUIZ      = 2;
    const CONTINUE_RESTARTUNIT      = 3;
    const CONTINUE_ABANDONUNIT      = 4;

    const STATUS_INPROGRESS         = 1;
    const STATUS_TIMEDOUT           = 2;
    const STATUS_ABANDONED          = 3;
    const STATUS_COMPLETED          = 4;
    const STATUS_PAUSED             = 5;

    const FEEDBACK_NONE             = 0;
    const FEEDBACK_WEBPAGE          = 1;
    const FEEDBACK_FORMMAIL         = 2;
    const FEEDBACK_MOODLEFORUM      = 3;
    const FEEDBACK_MOODLEMESSAGING  = 4;

    const STOPBUTTON_NONE           = 0;
    const STOPBUTTON_LANGPACK       = 1;
    const STOPBUTTON_SPECIFIC       = 2;

    const ACTIVITY_NONE             = 0;
    const ACTIVITY_COURSE_ANY       = -1;
    const ACTIVITY_SECTION_ANY      = -2;
    const ACTIVITY_COURSE_HOTPOT    = -3;
    const ACTIVITY_SECTION_HOTPOT   = -4;

    const ENTRYOPTIONS_TITLE        = 0x01;
    const ENTRYOPTIONS_GRADING      = 0x02;
    const ENTRYOPTIONS_DATES        = 0x04;
    const ENTRYOPTIONS_ATTEMPTS     = 0x08;

    const EXITOPTIONS_TITLE         = 0x01;
    const EXITOPTIONS_ENCOURAGEMENT = 0x02;
    const EXITOPTIONS_ATTEMPTSCORE  = 0x04;
    const EXITOPTIONS_HOTPOTGRADE   = 0x08;
    const EXITOPTIONS_RETRY         = 0x10;
    const EXITOPTIONS_INDEX         = 0x20;
    const EXITOPTIONS_COURSE        = 0x40;
    const EXITOPTIONS_GRADES        = 0x80;

    const BODYSTYLES_BACKGROUND     = 0x01;
    const BODYSTYLES_COLOR          = 0x02;
    const BODYSTYLES_FONT           = 0x04;
    const BODYSTYLES_MARGIN         = 0x08;

    /**
     * three sets of 6 bits define the times at which a quiz may be reviewed
     * e.g. 0x3f = 0011 1111 (i.e. right most 6 bits)
     */
    const REVIEW_DURINGATTEMPT = 0x0003f; // 1st set of 6 bits : during attempt
    const REVIEW_AFTERATTEMPT  = 0x00fc0; // 2nd set of 6 bits : after attempt (but before quiz closes)
    const REVIEW_AFTERCLOSE    = 0x3f000; // 3rd set of 6 bits : after the quiz closes

    /**
     * within each group of 6 bits we determine what should be shown
     * e.g. 0x1041 = 00-0001 0000-01 00-0001 (i.e. 3 sets of 6 bits)
     */
    const REVIEW_RESPONSES = 0x1041; // 1*0x1041 : 1st bit of each 6-bit set : Show student responses
    const REVIEW_ANSWERS   = 0x2082; // 2*0x1041 : 2nd bit of each 6-bit set : Show correct answers
    const REVIEW_SCORES    = 0x4104; // 3*0x1041 : 3rd bit of each 6-bit set : Show scores
    const REVIEW_FEEDBACK  = 0x8208; // 4*0x1041 : 4th bit of each 6-bit set : Show feedback

    /** @var stdclass course module record */
    public $cm;

    /** @var stdclass course record */
    public $course;

    /** @var stdclass context object */
    public $context;

    /** @var int hotpot instance identifier */
    public $id;

    /** @var string hotpot activity name */
    public $name;

    /** @var string url or path of the source file for this HotPot instance */
    public $sourcefile;

    /** @var string the type of the source file for this HotPot instance */
    public $sourcetype;

    /** @var int the file itemid of the sourcefile for this HotPot instance */
    public $sourcelocation;

    /** @var string url or path of the config file for this HotPot instance */
    public $configfile;

    /** @var int the location of the configfile for this HotPot instance */
    public $configlocation;

    /** @var xxx */
    public $entrycm;

    /** @var xxx */
    public $entrygrade;

    /** @var xxx */
    public $entrypage;

    /** @var xxx */
    public $entrytext;

    /** @var xxx */
    public $entryformat;

    /** @var xxx */
    public $entryoptions;

    /** @var xxx */
    public $exitpage;

    /** @var xxx */
    public $exittext;

    /** @var xxx */
    public $exitformat;

    /** @var xxx */
    public $exitoptions;

    /** @var xxx */
    public $exitcm;

    /** @var xxx */
    public $exitgrade;

    /** @var string the output format to be used when generating browser content */
    public $outputformat;

    /** @var int navigation aids to be used when this HotPot instance appears in the browser */
    public $navigation;

    /** @var int defines what will be displayed as the title in the browser */
    public $title;

    /** @var int indicates what kind of of stop button, if any, will be displayed */
    public $stopbutton;

    /** @var string the string to be displayed on the stop button */
    public $stoptext;

    /** @var boolean flag to indicate quiz content should be run processed by Moodle filters */
    public $usefilters;

    /** @var boolean flag to indicate quiz content should be linked to Moodle glossaries */
    public $useglossary;

    /** @var string name, if any, of mediaplayer filter to be used to replace media players  */
    public $usemediafilter;

    /** @var int what kind of popup, if any, should be shown for student feedback */
    public $studentfeedback;

    /** @var string url, if any, to which student feedback will be sent */
    public $studentfeedbackurl;

    /** @var int time after which this HotPot becomes available */
    public $timeopen;

    /** @var int time after which this HotPot is no longer available */
    public $timeclose;

    /** @var int the time limit for a single attempt at this HotPot */
    public $timelimit;

    /** @var int minimum time delay, in seconds, between first and second attempt */
    public $delay1;

    /** @var int minimum time delay, in seconds, between attempts after the second attempt */
    public $delay2;

    /** @var int delay, in seconds, between finishing a quiz and returning control to Moodle */
    public $delay3;

    /** @var string optional password required to access this HotPot instance */
    public $password;

    /** @var string optional IP mask to limit access this HotPot instance */
    public $subnet;

    /** @var xxx */
    public $reviewoptions;

    /** @var int 0-100 to show maximum number of attempts allowed at this HotPot instance */
    public $attemptlimit;

    /** @var int code denoting the grading method for this HotPot instance */
    public $grademethod;

    /** @var int 0-100 to show maximum grade for this HotPot instance */
    public $gradeweighting;

    /** @var boolean if true, every click of "hint", "clue" or "check" will be stored in the Moodle database */
    public $clickreporting;

    /** @var boolean if true, the raw xml returned form the attempt will be stored in the Moodle database  */
    public $discarddetails;

    /** @var int timestamp of when the module was modified */
    public $timemodified;

    /** @var int timestamp of when the module was created */
    public $timecreated;

    /** @var int timestamp of when this object was created */
    public $time;

    /** @var object representing the source file */
    public $source;

    /** @var object representing the config file */
    public $config;

    /** @var object representing a record from the hotpot_attempt table */
    public $attempt;

    /** @var array cache of all attempts by current user at this HotPot activity */
    public $attempts;

    /** @var object representing the grade_grade this HotPot activity */
    public $gradeitem;

    /** @var boolean cache for hotpot:attempt capability */
    public $canattempt;

    /** @var boolean cache for hotpot:deleteallattempts capability */
    public $candeleteallattempts;

    /** @var boolean cache for hotpot:deletemyattempts capability */
    public $candeletemyattempts;

    /** @var boolean cache for hotpot:manage capability */
    public $canmanage;

    /** @var boolean cache for hotpot:preview capability */
    public $canpreview;

    /** @var boolean cache for hotpot:reviewallattempts capability */
    public $canreviewallattempts;

    /** @var boolean cache for hotpot:reviewmyattempts capability */
    public $canreviewmyattempts;

    /** @var boolean cache for hotpot:view capability */
    public $canview;

    /** @var boolean cache of swithc to show if user can start this hotpot */
    public $canstart;

    /**
     * Initializes the hotpot API instance using the data from DB
     *
     * Makes deep copy of all passed records properties. Replaces integer $course attribute
     * with a full database record (course should not be stored in instances table anyway).
     *
     * The method is "protected" to prevent it being called directly. To create a new
     * instance of this class please use the self::create() method (see below).
     *
     * @param stdclass $dbrecord HotPot instance data from the {hotpot} table
     * @param stdclass $cm       Course module record as returned by {@link get_coursemodule_from_id()}
     * @param stdclass $course   Course record from {course} table
     * @param stdclass $context  The context of the hotpot instance
     * @param stdclass $attempt  attempt data from the {hotpot_attempts} table
     */
    private function __construct(stdclass $dbrecord, stdclass $cm, stdclass $course, stdclass $context=null, stdclass $attempt=null) {
        foreach ($dbrecord as $field => $value) {
            if (property_exists('hotpot', $field)) {
                $this->$field = $value;
            }
        }
        $this->cm = $cm;
        $this->course = $course;
        if (is_null($context)) {
            $this->context = hotpot_get_context(CONTEXT_MODULE, $this->cm->id);
        } else {
            $this->context = $context;
        }
        if (is_null($attempt)) {
            // do nothing
        } else {
            $this->attempt = $attempt;
        }
        $this->time = time();
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Static methods                                                             //
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * Creates a new HotPot object
     *
     * @param stdclass $dbrecord a row from the hotpot table
     * @param stdclass $cm a row from the course_modules table
     * @param stdclass $course a row from the course table
     * @return hotpot the new hotpot object
     */
    static public function create(stdclass $dbrecord, stdclass $cm, stdclass $course, stdclass $context=null, stdclass $attempt=null) {
        return new hotpot($dbrecord, $cm, $course, $context, $attempt);
    }

    /**
     * set_user_editing
     */
    static public function set_user_editing() {
        global $USER;
        $editmode = optional_param('editmode', null, PARAM_BOOL);
        if (! is_null($editmode)) {
            $USER->editing = $editmode;
        }
    }

    /**
     * Returns the localized list of navigation settings for a HotPot instance
     *
     * @return array
     */
    public static function available_navigations_list() {
        return array (
            self::NAVIGATION_MOODLE   => get_string('navigation_moodle', 'hotpot'),
            self::NAVIGATION_TOPBAR   => get_string('navigation_topbar', 'hotpot'),
            self::NAVIGATION_FRAME    => get_string('navigation_frame', 'hotpot'),
            self::NAVIGATION_EMBED    => get_string('navigation_embed', 'hotpot'),
            self::NAVIGATION_ORIGINAL => get_string('navigation_original', 'hotpot'),
            self::NAVIGATION_NONE     => get_string('navigation_none', 'hotpot')
        );
    }

    /**
     * Returns the localized list of feedback settings for a HotPot instance
     *
     * @return array
     */
    public static function available_feedbacks_list() {
        global $CFG;
        $list = array (
            self::FEEDBACK_NONE        => get_string('none'),
            self::FEEDBACK_WEBPAGE     => get_string('feedbackwebpage',  'hotpot'),
            self::FEEDBACK_FORMMAIL    => get_string('feedbackformmail', 'hotpot'),
            self::FEEDBACK_MOODLEFORUM => get_string('feedbackmoodleforum', 'hotpot')
        );
        if ($CFG->messaging) {
            $list[self::FEEDBACK_MOODLEMESSAGING] = get_string('feedbackmoodlemessaging', 'hotpot');
        }
        return $list;
    }

    /**
     * Returns the list of media players for the HotPot module
     *
     * @return array
     */
    public static function available_mediafilters_list() {
        $plugins = get_list_of_plugins('mod/hotpot/mediafilter'); // sorted

        if (in_array('moodle', $plugins)) {
            // make 'moodle' the first element in the plugins array
            unset($plugins[array_search('moodle', $plugins)]);
            array_unshift($plugins, 'moodle');
        }

        // define element type for list of mediafilters (select, radio, checkbox)
        $options = array('' => get_string('none'));
        foreach ($plugins as $plugin) {
            $options[$plugin] = get_string('mediafilter_'.$plugin, 'hotpot');
        }
        return $options;
    }

    /**
     * Returns the localized list of output format setings for a given HotPot sourcetype
     *
     * @return array
     */
    public static function available_outputformats_list($sourcetype) {

        $outputformats = array(
            '0' => get_string('outputformat_best', 'hotpot')
        );
        if ($sourcetype) {
            $classes = self::get_classes('hotpotattempt', 'renderer.php', 'mod_', '_renderer');
            foreach ($classes as $class) {
                // use call_user_func() to prevent syntax error in PHP 5.2.x
                $sourcetypes = call_user_func(array($class, 'sourcetypes'));
                if (in_array($sourcetype, $sourcetypes)) {
                    // strip prefix, "mod_hotpot_attempt_", and suffix, "_renderer"
                    $outputformat = substr($class, 19, -9);
                    $outputformats[$outputformat] = get_string('outputformat_'.$outputformat, 'hotpot');
                }
            }
            // remove "best" if there is only one compatible output format
            // if (count($outputformats)==2) {
            //     unset($outputformats[0]);
            // }
        }
        return $outputformats;
    }

    /**
     * Returns the localized list of attempt limit settings for a HotPot instance
     *
     * @return array
     */
    public static function available_attemptlimits_list() {
        $options = array(
            0 => get_string('attemptsunlimited', 'hotpot'),
        );
        for ($i=1; $i<=10; $i++) {
            $options[$i] = "$i";
        }
        return $options;
    }

    /**
     * Returns the localized list of grade method settings for a HotPot instance
     *
     * @return array
     */
    public static function available_grademethods_list() {
        return array (
            self::GRADEMETHOD_HIGHEST => get_string('highestscore', 'hotpot'),
            self::GRADEMETHOD_AVERAGE => get_string('averagescore', 'hotpot'),
            self::GRADEMETHOD_FIRST   => get_string('firstattempt', 'hotpot'),
            self::GRADEMETHOD_LAST    => get_string('lastattempt', 'hotpot'),
        );
    }

    /**
     * Returns the localized list of status settings for a HotPot attempt
     *
     * @return array
     */
    public static function available_statuses_list() {
        return array (
            self::STATUS_INPROGRESS => get_string('inprogress', 'hotpot'),
            self::STATUS_TIMEDOUT   => get_string('timedout', 'hotpot'),
            self::STATUS_ABANDONED  => get_string('abandoned', 'hotpot'),
            self::STATUS_COMPLETED  => get_string('completed', 'hotpot')
        );
    }

    /**
     * Returns the localized list of grade method settings for a HotPot instance
     *
     * @return array
     */
    public static function available_namesources_list() {
        return array (
            self::TEXTSOURCE_FILE     => get_string('textsourcefile', 'hotpot'),
            self::TEXTSOURCE_FILENAME => get_string('textsourcefilename', 'hotpot'),
            self::TEXTSOURCE_FILEPATH => get_string('textsourcefilepath', 'hotpot'),
            self::TEXTSOURCE_SPECIFIC => get_string('textsourcespecific', 'hotpot')
        );
    }

    /**
     * Returns the localized list of grade method settings for a HotPot instance
     *
     * @return array
     */
    public static function available_titles_list() {
        return array (
            self::TEXTSOURCE_SPECIFIC => get_string('hotpotname', 'hotpot'),
            self::TEXTSOURCE_FILE     => get_string('textsourcefile', 'hotpot'),
            self::TEXTSOURCE_FILENAME => get_string('textsourcefilename', 'hotpot'),
            self::TEXTSOURCE_FILEPATH => get_string('textsourcefilepath', 'hotpot')
        );
    }

    /**
     * Returns the localized list of maximum grade settings for a HotPot instance
     *
     * @return array
     */
    public static function available_gradeweightings_list() {
        $options = array();
        for ($i=100; $i>=1; $i--) {
            $options[$i] = $i;
        }
        $options[0] = get_string('nograde');
        return $options;
    }

    /**
     * Detects the type of the source file
     *
     * @param stored_file $sourcefile the file that has just been uploaded and stored
     * @return string the type of the source file (e.g. hp_6_jcloze_xml)
     */
    public static function get_sourcetype($sourcefile) {
        // include all the hotpot_source classes
        $classes = self::get_classes('hotpotsource');

        // loop through the classes checking to see if this file is recognized
        // use call_user_func() to prevent syntax error in PHP 5.2.x
        foreach ($classes as $class) {
            if (call_user_func(array($class, 'is_quizfile'), $sourcefile)) {
                return call_user_func(array($class, 'get_type'), $class);
            }
        }

        // file is not a recognized quiz type :-(
        return '';
    }

    /**
     * Returns a js module object for the HotPot module
     *
     * @param array $requires
     *    e.g. array('base', 'dom', 'event-delegate', 'event-key')
     * @return array $strings
     *    e.g. array(
     *        array('timesup', 'quiz'),
     *        array('functiondisabledbysecuremode', 'quiz'),
     *        array('flagged', 'question')
     *    )
     */
    public static function get_js_module(array $requires = null, array $strings = null) {
        return array(
            'name' => 'mod_hotpot',
            'fullpath' => '/mod/hotpot/module.js',
            'requires' => $requires,
            'strings' => $strings,
        );
    }

    /**
     * get_version_info
     *
     * @param xxx $info
     * @return xxx
     */
    public static function get_version_info($info)  {
        global $CFG;

        static $module = null;
        if (is_null($module)) {
            $module = new stdClass();
            require($CFG->dirroot.'/mod/hotpot/version.php');
        }

        if (isset($module->$info)) {
            return $module->$info;
        } else {
            return "no $info found";
        }
    }

   /**
    * load_mediafilter_filter
    *
    * @param xxx $classname
    */
   public static function load_mediafilter_filter($classname)  {
        global $CFG;
        $path = $CFG->dirroot.'/mod/hotpot/mediafilter/'.$classname.'/class.php';

        // check the filter exists
        if (! file_exists($path)) {
            debugging('hotpot mediafilter class is not accessible: '.$classname, DEBUG_DEVELOPER);
            return false;
        }

        return require_once($path);
    }

    /**
     * sourcefile_options
     *
     * @param xxx $context
     * @return xxx
     */
    public static function sourcefile_options() {
        return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1);
    }

    /**
     * text_editors_options
     *
     * @param xxx $context
     * @return xxx
     */
    public static function text_editors_options($context)  {
        return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => EDITOR_UNLIMITED_FILES,
                     'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
    }

    /**
     * text_page_types
     *
     * @return xxx
     */
    public static function text_page_types() {
        return array('entry', 'exit');
    }

    /**
     * text_page_options
     *
     * @param xxx $type
     * @return xxx
     */
    public static function text_page_options($type)  {
        if ($type=='entry') {
            return array(
                'title'         => self::ENTRYOPTIONS_TITLE,
                'grading'       => self::ENTRYOPTIONS_GRADING,
                'dates'         => self::ENTRYOPTIONS_DATES,
                'attempts'      => self::ENTRYOPTIONS_ATTEMPTS
            );
        }
        if ($type=='exit') {
            return array(
                'title'         => self::ENTRYOPTIONS_TITLE,
                'encouragement' => self::EXITOPTIONS_ENCOURAGEMENT,
                'attemptscore'  => self::EXITOPTIONS_ATTEMPTSCORE,
                'hotpotgrade'   => self::EXITOPTIONS_HOTPOTGRADE,
                'retry'         => self::EXITOPTIONS_RETRY,
                'index'         => self::EXITOPTIONS_INDEX,
                'course'        => self::EXITOPTIONS_COURSE,
                'grades'        => self::EXITOPTIONS_GRADES
            );
        }
        return array();
    }

    /**
     * user_preferences_fields
     *
     * @return array of user_preferences used by the HotPot module
     */
    public static function user_preferences_fieldnames() {
        return array(
            // fields used only when adding a new HotPot
            'namesource','entrytextsource','exittextsource','quizchain',

            // source/config files
            'sourcefile','sourcelocation','configfile','configlocation',

            // entry/exit pages
            'entrypage','entryformat','entryoptions',
            'exitpage','exitformat','exitoptions',
            'entrycm','entrygrade','exitcm','exitgrade',

            // display
            'outputformat','navigation','title','stopbutton','stoptext',
            'usefilters','useglossary','usemediafilter','studentfeedback','studentfeedbackurl',

            // access restrictions
            'timeopen','timeclose','timelimit','delay1','delay2','delay3',
            'password','subnet','reviewoptions','attemptlimit',

            // grading and reporting
            'grademethod','gradeweighting','clickreporting','discarddetails'
        );
    }

    /**
     * string_ids
     *
     * @param xxx $field_value
     * @return xxx
     */
    public static function string_ids($field_value, $max_field_length=255)  {
        $ids = array();

        $strings = explode(',', $field_value);
        foreach($strings as $str) {
            if ($id = self::string_id($str)) {
                $ids[] = $id;
            }
        }
        $ids = implode(',', $ids);

        // we have to make sure that the list of $ids is no longer
        // than the maximum allowable length for this field
        if (strlen($ids) > $max_field_length) {

            // truncate $ids just before last comma in allowable field length
            // Note: largest possible id is something like 9223372036854775808
            //       so we must leave space for that in the $ids string
            $ids = substr($ids, 0, $max_field_length - 20);
            $ids = substr($ids, 0, strrpos($ids, ','));

            // create single $str(ing) containing all $strings not included in $ids
            $str = implode(',', array_slice($strings, substr_count($ids, ',') + 1));

            // append the id of the string containing all the strings not yet in $ids
            if ($id = self::string_id($str)) {
                $ids .= ','.$id;
            }
        }

        // return comma separated list of string $ids
        return $ids;
    }

    /**
     * string_id
     *
     * @param xxx $str
     * @return xxx
     */
    public static function string_id($str)  {
        global $DB;

        if (! isset($str) || ! is_string($str) || trim($str)=='') {
            // invalid input string
            return false;
        }

        // create md5 key
        $md5key = md5($str);

        if ($id = $DB->get_field('hotpot_strings', 'id', array('md5key'=>$md5key))) {
            // string already exists
            return $id;
        }

        // create a new string record
        $record = (object)array('string'=>$str, 'md5key'=>$md5key);
        if (! $id = $DB->insert_record('hotpot_strings', $record)) {
            print_error('error_insertrecord', 'hotpot', '', 'hotpot_strings');
        }

        // new string was successfully added
        return $id;
    }

    /**
     * get_strings
     *
     * @param xxx $ids
     * @return xxx
     */
    public static function get_strings($ids)  {
        global $DB;

        // convert $ids to an array, if necessary
        if (is_string($ids)) {
            $ids = explode(',', $ids);
            $ids = array_filter($ids);
        }

        // return strings, if any
        if (empty($ids)) {
            return array();
        } else {
            list($filter, $params) = $DB->get_in_or_equal($ids);
            return $DB->get_records_select('hotpot_strings', "id $filter", $params, '', 'id,string');
        }
    }

    /**
     * get_question_text
     *
     * @param xxx $question
     * @return xxx
     */
    static public function get_question_text($question)   {
        global $DB;

        if (empty($question->text)) {
            // JMatch, JMix and JQuiz
            return $question->name;
        } else {
            // JCloze and JCross
            return $DB->get_field('hotpot_strings', 'string', array('id' => $question->text));
        }
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Hotpot API                                                                 //
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @return moodle_url of this hotpot's view page
     */
    public function view_url($cm=null) {
        if (is_null($cm)) {
            $cm = $this->cm;
        }
        return new moodle_url('/mod/'.$cm->modname.'/view.php', array('id' => $cm->id));
    }

    /**
     * @return moodle_url of this hotpot's view page
     */
    public function report_url($mode='', $cm=null) {
        if (is_null($cm)) {
            $cm = $this->cm;
        }
        $params = array('id' => $cm->id);
        if ($mode) {
            $params['mode'] = $mode;
        }
        return new moodle_url('/mod/hotpot/report.php', $params);
    }

    /**
     * @return moodle_url of this hotpot's attempt page
     */
    public function attempt_url($framename='', $cm=null) {
        if (is_null($cm)) {
            $cm = $this->cm;
        }
        $params = array('id' => $cm->id);
        if ($framename) {
            $params['framename'] = $framename;
        }
        return new moodle_url('/mod/hotpot/attempt.php', $params);
    }

    /**
     * @return moodle_url of this hotpot's attempt page
     */
    public function submit_url($attempt=null) {
        if (is_null($attempt)) {
            $attempt = $this->attempt;
        }
        return new moodle_url('/mod/hotpot/submit.php', array('id' => $attempt->id));
    }

    /**
     * @return moodle_url of the review page for an attempt at this hotpot
     */
    public function review_url($attempt=null) {
        if (is_null($attempt)) {
            $attempt = $this->attempt;
        }
        return new moodle_url('/mod/hotpot/review.php', array('id' => $attempt->id));
    }

    /**
     * @return moodle_url of this course's hotpot index page
     */
    public function index_url($course=null) {
        if (is_null($course)) {
            $course = $this->course;
        }
        return new moodle_url('/mod/hotpot/index.php', array('id' => $course->id));
    }

    /**
     * @return moodle_url of this hotpot's course page
     */
    public function course_url($course=null) {
        if (is_null($course)) {
            $course = $this->course;
        }
        $params = array('id' => $course->id);
        $sectionnum = 0;
        if (isset($course->coursedisplay) && defined('COURSE_DISPLAY_MULTIPAGE')) {
            // Moodle >= 2.3
            if ($course->coursedisplay==COURSE_DISPLAY_MULTIPAGE) {
                $courseid = $course->id;
                $sectionid = $this->cm->section;
                if ($modinfo = get_fast_modinfo($this->course)) {
                    $sections = $modinfo->get_section_info_all();
                    foreach ($sections as $section) {
                        if ($section->id==$sectionid) {
                            $sectionnum = $section->section;
                            break;
                        }
                    }
                }
                unset($modinfo, $sections, $section);
            }
        }
        if ($sectionnum) {
            $params['section'] = $sectionnum;
        }
        return new moodle_url('/course/view.php', $params);
    }

    /**
     * @return moodle_url of this hotpot's course grade page
     */
    public function grades_url($course=null) {
        if (is_null($course)) {
            $course = $this->course;
        }
        return new moodle_url('/grade/index.php', array('id' => $course->id));
    }

    /**
     * @return source object representing the source file for this HotPot
     */
    public function get_source() {
        global $CFG, $DB;
        if (empty($this->source)) {
            // get sourcetype e.g. hp_6_jcloze_xml
            $sourcefile = $this->get_sourcefile();
            if (! $sourcetype = clean_param($this->sourcetype, PARAM_SAFEDIR)) {
                if ($sourcetype = hotpot::get_sourcetype($sourcefile)) {
                    $DB->set_field('hotpot', 'sourcetype', $sourcetype, array('id' => $this->id));
                    $this->sourcetype = $sourcetype;
                } else {
                    throw new moodle_exception('missingsourcetype', 'hotpot');
                }
            }

            $dir = str_replace('_', '/', $sourcetype);
            require_once($CFG->dirroot.'/mod/hotpot/source/'.$dir.'/class.php');

            $classname = 'hotpot_source_'.$sourcetype;
            $this->source = new $classname($sourcefile, $this);
        }
        return $this->source;
    }

    /**
     * Returns the localized description of the grade method
     *
     * @return string
     */
    public function format_grademethod() {
        $options = $this->available_grademethods_list();
        if (array_key_exists($this->grademethod, $options)) {
            return $options[$this->grademethod];
        } else {
            return $this->grademethod; // shouldn't happen
        }
    }

    /**
     * Returns the localized description of the attempt status
     *
     * @return string
     */
    public static function format_status($status) {
        $options = self::available_statuses_list();
        if (array_key_exists($status, $options)) {
            return $options[$status];
        } else {
            return $status; // shouldn't happen
        }
    }

    /**
     * Returns a formatted version of the $time
     *
     * @param in $time the time to format
     * @param string $format time format string
     * @param string $notime return value if $time==0
     * @return string
     */
    public static function format_time($time, $format=null, $notime='&nbsp;') {
        if ($time>0) {
            return format_time($time, $format);
        } else {
            return $notime;
        }
    }

    /**
     * Returns a formatted version of an (attempt) $record's score
     *
     * @param object $record from the Moodle database
     * @param string $noscore return value if $record->score is not set
     * @return string
     */
    function format_score($record, $default='&nbsp;') {
        if (isset($record->score)) {
            return $record->score;
        } else {
            return $default;
        }
    }

    /**
     * Returns the stored_file object for this HotPot's source file
     *
     * @return stored_file
     */
    public function get_sourcefile() {
        global $CFG, $DB;
        $fs = get_file_storage();

        $filename = basename($this->sourcefile);
        $filepath = dirname($this->sourcefile);

        // require leading and trailing slash on $filepath
        if (substr($filepath, 0, 1)=='/' && substr($filepath, -1)=='/') {
            // do nothing - $filepath is valid
        } else {
            // fix filepath - shouldn't happen !!
            // maybe leftover from a messy upgrade
            if ($filepath=='.' || $filepath=='') {
                $filepath = '/';
            } else {
                $filepath = '/'.ltrim($filepath, '/');
                $filepath = rtrim($filepath, '/').'/';
            }
            $this->sourcefile = $filepath.$filename;
            $DB->set_field('hotpot', 'sourcefile', $this->sourcefile, array('id' => $this->id));
        }

        if ($file = $fs->get_file($this->context->id, 'mod_hotpot', 'sourcefile', 0, $filepath, $filename)) {
            return $file;
        }

        // the source file is missing, probably this HotPot
        // has recently been upgraded/imported from Moodle 1.9
        // so we are going to try to create the missing stored file

        $file_record = array(
            'contextid'=>$this->context->id, 'component'=>'mod_hotpot', 'filearea'=>'sourcefile',
            'sortorder'=>1, 'itemid'=>0, 'filepath'=>$filepath, 'filename'=>$filename
        );

        $coursecontext  = hotpot_get_context(CONTEXT_COURSE, $this->course->id);
        $filehash = sha1('/'.$coursecontext->id.'/course/legacy/0'.$filepath.$filename);

        if ($file = $fs->get_file_by_hash($filehash)) {
            // file exists in legacy course files
            if ($file = $fs->create_file_from_storedfile($file_record, $file)) {
                return $file;
            }
        }

        $oldfilepath = $CFG->dataroot.'/'.$this->course->id.$filepath.$filename;
        if (file_exists($oldfilepath)) {
            // file exists on server's filesystem
            if ($file = $fs->create_file_from_pathname($file_record, $oldfilepath)) {
                return $file;
            }
        }

        // source file not found - shouldn't happen !!
        throw new moodle_exception('sourcefilenotfound', 'hotpot', '', $this->sourcefile);
    }

    /**
     * Returns the output format to be used for an attempt at this HotPot
     * If the outputformat is not given, the "best" outupt format is returned
     * which is the one with the same name as "sourcetype" for this HotPot
     *
     * @return string $subtype
     */
    public function get_outputformat() {
        if (empty($this->outputformat)) {
            return $this->get_source()->get_best_outputformat();
        } else {
            return clean_param($this->outputformat, PARAM_SAFEDIR);
        }
    }

    /**
     * can_attempt
     *
     * @return xxx
     */
    function can_attempt() {
        if (is_null($this->canattempt)) {
            $this->canattempt = has_capability('mod/hotpot:attempt', $this->context);
        }
        return $this->canattempt;
    }

    /**
     * can_deleteattempts
     *
     * @return xxx
     */
    function can_deleteattempts() {
        return $this->can_deletemyattempts() || $this->can_deleteallattempts();
    }

    /**
     * can_deleteallattempts
     *
     * @return xxx
     */
    function can_deleteallattempts() {
        if (is_null($this->candeleteallattempts)) {
            $this->candeleteallattempts = has_capability('mod/hotpot:deleteallattempts', $this->context);
        }
        return $this->candeleteallattempts;
    }

    /**
     * can_deletemyattempts
     *
     * @return xxx
     */
    function can_deletemyattempts() {
        if (is_null($this->candeletemyattempts)) {
            $this->candeletemyattempts = has_capability('mod/hotpot:deletemyattempts', $this->context);
        }
        return $this->candeletemyattempts;
    }

    /**
     * can_manage
     *
     * @return xxx
     */
    function can_manage() {
        if (is_null($this->canmanage)) {
            $this->canmanage = has_capability('mod/hotpot:manage', $this->context);
        }
        return $this->canmanage;
    }

    /**
     * can_preview
     *
     * @return xxx
     */
    function can_preview() {
        if (is_null($this->canpreview)) {
            $this->canpreview = has_capability('mod/hotpot:preview', $this->context);
        }
        return $this->canpreview;
    }

    /**
     * can_reviewallattempts
     *
     * @return xxx
     */
    function can_reviewattempts() {
        return $this->can_reviewmyattempts() || $this->can_reviewallattempts();
    }

    /**
     * can_reviewallattempts
     *
     * @return xxx
     */
    function can_reviewallattempts() {
        if (is_null($this->canreviewallattempts)) {
            $this->canreviewallattempts = has_capability('mod/hotpot:reviewallattempts', $this->context);
        }
        return $this->canreviewallattempts;
    }

    /**
     * can_reviewmyattempts
     *
     * @return xxx
     */
    function can_reviewmyattempts() {
        if (is_null($this->canreviewmyattempts)) {
            $this->canreviewmyattempts = has_capability('mod/hotpot:reviewmyattempts', $this->context);
        }
        return $this->canreviewmyattempts;
    }

    /**
     * can_view
     *
     * @return xxx
     */
     function can_view() {
        if (is_null($this->canview)) {
            $this->canview = has_capability('mod/hotpot:view', $this->context);
        }
        return $this->canview;
     }

    /**
     * can_start
     *
     * @param xxx $canstart (optional, default=null)
     * @return xxx
     */
    function can_start($canstart=null)  {
        if (is_null($canstart)) {
            if (is_null($this->canstart)) {
                // set automatically
                if (! $this->can_attempt()) {
                    $this->canstart = false;
                } else if ($this->require_isopen()) {
                    $this->canstart = false;
                } else if ($this->require_notclosed()) {
                    $this->canstart = false;
                } else if ($this->require_entrycm()) {
                    $this->canstart = false;
                } else if ($this->require_delay('delay1')) {
                    $this->canstart = false;
                } else if ($this->require_delay('delay2')) {
                    $this->canstart = false;
                } else if ($this->require_moreattempts(true)) {
                    $this->canstart = false;
                } else { // no errors so far
                    $this->canstart = true;
                }
            }
            // get
            return $this->canstart;
        } else {
            // set manually
            $this->canstart = $canstart;
        }
    }

    /**
     * Returns the subtype to be used to get a renderer for an attempt at this HotPot
     *
     * @return string $subtype
     */
    public function get_attempt_renderer_subtype() {
        return 'attempt_'.$this->get_outputformat();
    }

    /**
     * set_preferred_pagelayout
     *
     * @param xxx $PAGE
     */
    public function set_preferred_pagelayout($PAGE)  {
        // page layouts are defined in theme/xxx/config.php

        switch ($this->navigation) {

            case self::NAVIGATION_ORIGINAL:
            case self::NAVIGATION_NONE:
                // $PAGE->set_pagelayout('popup');
                $PAGE->set_pagelayout('embedded');
                break;

            case self::NAVIGATION_FRAME:
            case self::NAVIGATION_EMBED:
                $framename = optional_param('framename', '', PARAM_ALPHA);
                if ($framename=='top') {
                    $PAGE->set_pagelayout('frametop');
                }
                if ($framename=='main') {
                    $PAGE->set_pagelayout('embedded');
                }
                break;

            case self::NAVIGATION_TOPBAR:
                $PAGE->set_pagelayout('login'); // no nav menu
                break;
        }
    }

    /**
     * to_stdclass
     *
     * @return xxx
     */
    public function to_stdclass() {
        $stdclass = new stdclass();
        $vars = get_object_vars($this);
        foreach ($vars as $name => $value) {
            if (is_object($this->$name) || is_array($this->$name)) {
                continue;
            }
            $stdclass->$name = $value;
        }
        // extra fields required for grades
        if (isset($this->course) && is_object($this->course)) {
            $stdclass->course = $this->course->id;
        }
        if (isset($this->cm) && is_object($this->cm)) {
            $stdclass->cmidnumber = $this->cm->id;
        }
        $stdclass->modname = 'hotpot';
        return $stdclass;
    }

    /**
     * Returns the subtype to be used to get a report renderer for this HotPot
     *
     * @return string $mode
     * @return string $subtype
     */
    public function get_report_renderer_subtype($mode) {
        if ($mode=='') {
            $mode = 'overview';
        }
        return 'report_'.$mode;
    }

    ////////////////////////////////////////////////////////////////////////////////
    // Internal methods (implementation details)                                  //
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * This function will "include" all the files matching $classfilename for a given a plugin type
     * (e.g. hotpotsource), and return a list of classes that were included
     *
     * @param string $plugintype one of the plugintypes specified in mod/hotpot/db/subplugins.php
     */
    static public function get_classes($plugintype, $classfilename='class.php', $prefix='', $suffix='') {
        global $CFG;

        // initialize array to hold class names
        $classes = array();

        // get list of all subplugins
        $subplugins = array();
        include($CFG->dirroot.'/mod/hotpot/db/subplugins.php');

        // extract the $plugintype we are interested in
        $types = array();
        if (isset($subplugins[$plugintype])) {
            $types[$plugintype] = $subplugins[$plugintype];
        }
        unset($subplugins);

        // we are not interested in these directories
        $ignored = array('CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'phpunit');

        // get all the subplugins for this $plugintype
        while (list($type, $dir) = each($types)) {
            $fulldir = $CFG->dirroot.'/'.$dir;
            if (is_dir($fulldir) && file_exists($fulldir.'/'.$classfilename)) {

                // include the class
                require_once($fulldir.'/'.$classfilename);

                // extract class name, e.g. hotpot_source_hp_6_jcloze_xml
                // from $subdir, e.g. mod/hotpot/file/h6/6/jcloze/xml
                // by removing leading "mod/" and converting all "/" to "_"
                $classes[] = $prefix.str_replace('/', '_', substr($dir, 4)).$suffix;

                // get subplugins in this $dir
                $items = new DirectoryIterator($fulldir);
                foreach ($items as $item) {
                    if (substr($item, 0, 1)=='.' || in_array($item, $ignored)) {
                        continue;
                    }
                    if ($item->isDir()) {
                        $types[$type.$item] = $dir.'/'.$item;
                    }
                }
            }
        }
        sort($classes);
        return $classes;
    }

    /**
     * get_report_modes
     *
     * @return xxx
     */
    function get_report_modes() {
        $modes = array('overview', 'scores', 'responses', 'analysis');
        if ($this->clickreporting) {
            $modes[] = 'clicktrail';
        }
        return $modes;
    }

    ////////////////////////////////////////////////////////////////////////////////
    // methods to access database records connected to this HotPot                //
    ////////////////////////////////////////////////////////////////////////////////

    /*
     * create an db record for an attempt at this HotPot activity
     *
     * @return int the id of the newly created attempt record
     */
    function create_attempt() {
        global $DB, $USER;
        if (empty($this->attempt)) {

            // get max attempt number so far
            $sql = "SELECT MAX(attempt) FROM {hotpot_attempts} WHERE hotpotid=? AND userid=?";
            if ($max_attempt = $DB->get_field_sql($sql, array($this->id, $USER->id))) {
                $max_attempt ++;
            } else {
                $max_attempt = 1;
            }

            // create attempt record
            $this->attempt = new stdClass();
            $this->attempt->hotpotid       = $this->id;
            $this->attempt->userid         = $USER->id;
            $this->attempt->starttime      = 0;
            $this->attempt->endtime        = 0;
            $this->attempt->score          = 0;
            $this->attempt->penalties      = 0;
            $this->attempt->attempt        = $max_attempt;
            $this->attempt->timestart      = $this->time;
            $this->attempt->timefinish     = 0;
            $this->attempt->status         = self::STATUS_INPROGRESS;
            $this->attempt->clickreportid  = 0;
            $this->attempt->timemodified   = $this->time;

            // insert attempt record into database
            if (! $this->attempt->id = $DB->insert_record('hotpot_attempts', $this->attempt)) {
                throw new moodle_exception('error_insertrecord', 'hotpot', '', 'hotpot_attempts');
            }

            // set previous "in progress" attempt(s) to adandoned
            $select = 'hotpotid=? AND userid=? AND attempt<=? AND status=?';
            $params = array($this->id, $USER->id, $max_attempt, self::STATUS_INPROGRESS);
            if ($attempts = $DB->get_records_select('hotpot_attempts', $select, $params)) {
                foreach ($attempts as $attempt) {
                    $attempt->timemodified = $this->time;
                    $attempt->status = self::STATUS_ABANDONED;
                    $DB->update_record('hotpot_attempts', $attempt);
                }
            }

        }
        return $this->attempt->id;
    }

    /**
     * count_distinct_clickreportids
     *
     * @return xxx
     */
    public function count_distinct_clickreportids() {
        $clickreportids = array();
        if ($this->get_attempts()) {
            foreach ($this->attempts as $attempt) {
                $clickreportids[$attempt->clickreportid] = true;
            }
        }
        return count($clickreportids);
    }

    /**
     * get_attempts
     *
     * @param array $selected ids of attempts to be deleted (optional, default=null)
     * @param int $userid (optional, default=0)
     * @return xxx
     */
    public function get_attempts($selected=null, $userid=0)  {
        global $DB, $USER;

        if (is_null($selected)) {
            if (is_null($this->attempts)) {
                $conditions = array('hotpotid' => $this->id, 'userid' => $USER->id);
                $this->attempts = $DB->get_records('hotpot_attempts', $conditions, 'timemodified DESC');
            }
        } else {
            $ids = array();
            foreach ($selected as $id => $flag) {
                if ($flag) {
                    $ids[] = $id;
                }
            }
            if (count($ids)) {
                list($filter, $params) = $DB->get_in_or_equal($ids);
                $select = "id $filter AND hotpotid=?";
                $params[] = $this->id;
                if ($userid) {
                    $select .= " AND userid=?";
                    $params[] = $userid;
                }
                $this->attempts = $DB->get_records_select('hotpot_attempts', $select, $params, 'timemodified DESC');
            }
        }

        if (empty($this->attempts)) {
            return 0;
        } else {
            return count($this->attempts);
        }
    }

    /**
     * delete_attempts
     *
     * @param xxx $selected
     */
    public function delete_attempts($selected, $onlymyattempts=true) {
        global $DB, $USER;

        if ($this->can_deleteallattempts()) {
            $userid = 0; // i.e. any user
        } else if ($this->can_deletemyattempts()) {
            $userid = $USER->id;
            $onlymyattempts = true;
        } else {
            return; // user is not allowed to delete attempts
        }

        if ($onlymyattempts) {
            // get attempts for this user only
            $this->get_attempts();
        } else {
            // get attempts for any users
            $this->get_attempts($selected, $userid);
        }

        if (empty($selected) || ! $this->attempts) {
            return; // nothing to do
        }

        $ids = array();
        $userids = array();
        foreach ($selected as $id => $delete) {
            if ($delete && array_key_exists($id, $this->attempts)) {
                $userid = $this->attempts[$id]->userid;
                if ($this->can_deleteallattempts() || ($this->can_deletemyattempts() && $userid==$USER->id)) {
                    $ids[] = $id;
                    $userids[$userid] = true;
                    unset($this->attempts[$id]);
                }
            }
        }

        if (count($ids)) {
            $DB->delete_records_list('hotpot_attempts',  'id',        $ids);
            $DB->delete_records_list('hotpot_details',   'attemptid', $ids);
            $DB->delete_records_list('hotpot_responses', 'attemptid', $ids);

            $userids = array_keys($userids);
            $stdclass = $this->to_stdclass();

            foreach ($userids as $userid) {
                hotpot_update_grades($stdclass, $userid);
            }
        }
    }

    /**
     * require_access
     *
     * @return xxx
     */
    function require_access()  {
        if (! $error = $this->require_subnet()) {
            if (! $error = $this->require_password()) {
                $error = false;
            }
        }
        return $error;
    }

    /**
     * require_subnet
     *
     * @return xxx
     */
    function require_subnet()  {
        if (! $this->subnet) {
            return false;
        }
        if (address_in_subnet(getremoteaddr(), $this->subnet)) {
            return false;
        }
        // user's IP address is missing or does not match required subnet mask
        return get_string('subnetwrong', 'quiz');
    }

    /**
     * require_password
     *
     * @return xxx
     */
    function require_password()  {
        global $SESSION;
        $error = '';

        // does this hotpot require a password?
        if ($this->password) {

            // has password not already been given?
            if (empty($SESSION->hotpot_passwordchecked[$this->id])) {

                // get password, if any, that was entered
                // (strcmp returns 0 if strings are identical)
                $password = optional_param('hotpotpassword', '', PARAM_RAW);
                if (strcmp($this->password, $password)) {

                    // password is missing or invalid

                    if ($this->entrypage) {
                        $url = $this->view_url();
                    } else {
                        $url = $this->attempt_url();
                    }
                    $error = get_string('requirepasswordmessage', 'quiz');
                    $error .= html_writer::start_tag('form', array('id'=>'hotpotpasswordform', 'method'=>'post', 'action'=>$url));
                    $error .= html_writer::start_tag('fieldset');
                    $error .= html_writer::tag('b', get_string('password')).' ';
                    $error .= html_writer::empty_tag('input', array('name'=>'hotpotpassword', 'type'=>'password', 'value'=>$password)).' ';
                    $error .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('ok')));
                    if ($password) {
                        // previously entered password was invalid
                        $error .= html_writer::empty_tag('br');
                        $error .= get_string('passworderror', 'quiz');
                    }
                    $error .= html_writer::end_tag('fieldset');
                    $error .= html_writer::end_tag('form')."\n";
                } else {
                    // newly entered password was correct
                    if (empty($SESSION->hotpot_passwordchecked)) {
                        $SESSION->hotpot_passwordchecked = array();
                    }
                    $SESSION->hotpot_passwordchecked[$this->id] = true;
                }
            }
        }
        if ($error) {
            return $error;
        } else {
            return false;
        }
    }

    /**
     * require_isopen
     *
     * @return xxx
     */
    public function require_isopen() {
        if ($this->timeopen && $this->timeopen > $this->time) {
            // unit/quiz is not yet open
            return get_string('notavailable', 'hotpot', userdate($this->timeopen));
        }
        return false;
    }

    /**
     * require_notclosed
     *
     * @return xxx
     */
    public function require_notclosed() {
        if ($this->timeclose && $this->timeclose < $this->time) {
            // unit/quiz is already closed
            return get_string('closed', 'hotpot', userdate($this->timeclose));
        }
        return false;
    }

    /**
     * require_entrycm
     *
     * @return xxx
     */
    public function require_entrycm() {
        global $CFG, $DB, $USER;
        require_once($CFG->dirroot.'/lib/gradelib.php');

        if (! $cm = $this->get_cm('entry')) {
            return false;
        }

        // set up url to view this activity
        $href = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id' => $cm->id));

        if ($this->entrygrade) {
            if ($grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $USER->id)) {
                $grade = 0;
                if (isset($grades->items[0]) && $grades->items[0]->grademax > 0) {
                    // this activity has a grade item
                    if (isset($grades->items[0]->grades[$USER->id])) {
                        $grade = $grades->items[0]->grades[$USER->id]->grade;
                    } else {
                        $grade = 0;
                    }
                    if ($grade < $this->entrygrade) {
                        // either this user has not attempted the entry activity
                        // or their grade so far on the entry activity is too low
                        $a = (object)array(
                            'usergrade' => intval($grade),
                            'entrygrade' => $this->entrygrade,
                            'entryactivity' => html_writer::tag('a', format_string(urldecode($cm->name)), array('href' => $href))
                        );
                        return get_string('entrygradewarning', 'hotpot', $a);
                    }
                }
            }
        } else {
            // no grade, so test for "completion"
            switch ($cm->modname) {
                case 'resource':
                    $table = 'log';
                    $select = 'cmid=? AND userid=? AND action=?';
                    $params = array($cm->id, $this->userid, 'view');
                    break;
                case 'lesson':
                    $table = 'lesson_grades';
                    $select = 'userid=? AND lessonid==? AND completed>?';
                    $params = array($this->userid, $cm->instance, 0);
                    break;
                default:
                    $table = '';
                    $select = '';
                    $params = array();
            }
            if ($table && $select && ! $DB->record_exists_select($table, $select, $params)) {
                // user has not viewed or completed this activity yet
                $a = html_writer::tag('a', format_string(urldecode($cm->name)), array('href' => $href->out()));
                return get_string('entrycompletionwarning', 'hotpot', $a);
            }
        }

        return false;
    }

    /**
     * require_exitgrade
     *
     * @return xxx
     */
    function require_exitgrade() {
        if ($this->exitcm==0 || $this->exitgrade==0 || empty($this->attempt)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * require_delay
     *
     * @param xxx $delay
     * @return xxx
     */
    public function require_delay($delay)  {
        if (! $this->$delay) {
            return false;
        }

        if (! $countattempts = $this->get_attempts()) {
            return false;
        }

        // check to see if we require a delay or not
        switch ($delay) {
            case 'delay1': $require_delay = ($countattempts==1); break;
            case 'delay2': $require_delay = ($countattempts>=2); break;
            default: $require_delay = false;
        }

        if (! $require_delay) {
            return false;
        }

        // get most recent attempt
        $lastattempt = reset($this->attempts);

        $nextattempttime = $lastattempt->timemodified + ($this->$delay);
        if ($this->time >= $nextattempttime) {
            // $delay has expired, so let them through
            return false;
        } else {
            // $delay has not expired yet
            $time = html_writer::tag('strong', userdate($nextattempttime));
            return get_string('temporaryblocked', 'quiz').' '.$time;
        }

    }

    /**
     * require_moreattempts
     *
     * @param xxx $shorterror (optional, default=false)
     * @return xxx
     */
    public function require_moreattempts($shorterror=false)  {
        if (! $this->attemptlimit) {
            return false;
        }

        if (! $countattempts = $this->get_attempts()) {
            return false;
        }

        if ($this->attemptlimit > $countattempts) {
            return false;
        }

        // maximum number of unit/quiz attempts reached
        if ($shorterror) {
            return get_string('nomoreattempts', 'hotpot');
        } else {
            $attemptlimitstr = hotpot_textlib('moodle_strtolower', get_string('attemptlimit', 'hotpot'));
            $msg = html_writer::tag('b', format_string($this->name))." ($attemptlimitstr = $this->attemptlimit)";
            return html_writer::tag('p', get_string('nomoreattempts', 'hotpot')).html_writer::tag('p', $msg);
        }
    }

    /**
     * get_cm
     *
     * @param xxx $type
     * @return xxx
     */
    public function get_cm($type)  {
        // gets the next, previous or specific Moodle activity

        // get entry/exit cm id
        $cm_field = $type.'cm';
        $cmid = $this->$cm_field;

        if ($cmid==self::ACTIVITY_NONE) {
            return false;
        }

        if (! $modinfo = get_fast_modinfo($this->course)) {
            return false; // no modinfo - shouldn't happen !!
        }

        if (method_exists($modinfo, 'get_cm')) {
            if (! $modinfo->get_cm($this->cm->id)) {
                return false; // target cm not found - shouldn't happen !!
            }
        } else {
            if (! isset($modinfo->cms[$this->cm->id])) {
                return false; // target cm not found - shouldn't happen !!
            }
        }

        // set default search values
        $id = 0;
        $modname = '';
        $sectionnum = -1;

        // restrict search values
        if ($cmid>0) {
            $id = $cmid;
        } else {
            if ($cmid==self::ACTIVITY_COURSE_HOTPOT || $cmid==self::ACTIVITY_SECTION_HOTPOT) {
                $modname = 'hotpot';
            }
            if ($cmid==self::ACTIVITY_SECTION_ANY || $cmid==self::ACTIVITY_SECTION_HOTPOT) {
                $sectionnum = $modinfo->get_cm($this->cm->id)->sectionnum;
            }
        }

        // get cm ids (reverse order if necessary)
        $cmids = array_keys($modinfo->cms);
        if ($type=='entry') {
            $cmids = array_reverse($cmids);
        }

        // search for next, previous or specific course module
        $found = false;
        foreach ($cmids as $cmid) {
            if (method_exists($modinfo, 'get_cm')) {
                $cm = $modinfo->get_cm($cmid);
            } else {
                $cm = $modinfo->cms[$cmid];
            }
            if ($id && $cm->id!=$id) {
                continue; // wrong activity
            }
            if ($sectionnum>=0) {
                if ($type=='entry') {
                    if ($cm->sectionnum>$sectionnum) {
                        continue; // later section
                    }
                    if ($cm->sectionnum<$sectionnum) {
                        return false; // previous section
                    }
                } else { // exit (=next)
                    if ($cm->sectionnum<$sectionnum) {
                        continue; // earlier section
                    }
                    if ($cm->sectionnum>$sectionnum) {
                        return false; // later section
                    }
                }
            }
            if ($modname && $cm->modname!=$modname) {
                continue; // wrong module
            }
            if ($cm->modname=='label') {
                continue; // skip labels
            }
            if ($found || $cm->id==$id) {
                if (coursemodule_visible_for_user($cm)) {
                    return $cm;
                }
                if ($cm->id==$id) {
                    // required cm is not visible to this user
                    return false;
                }
            }
            if ($cm->id==$this->cm->id) {
                $found = true;
            }
        }

        // next cm not found
        return false;
    }

    /**
     * get_attempt
     *
     * @return xxx
     */
    public function get_attempt() {
        return $this->attempt;
    }

    /**
     * get_gradeitem
     *
     * @return xxx
     */
    public function get_gradeitem() {
        global $CFG, $USER;
        require_once($CFG->dirroot.'/lib/gradelib.php');

        if (is_null($this->gradeitem)) {
            $this->gradeitem = false;
            if ($grades = grade_get_grades($this->course->id, 'mod', 'hotpot', $this->id, $USER->id)) {
                if (isset($grades->items[0]) && $grades->items[0]->grademax > 0) {
                    // this activity has a grade item
                    if (isset($grades->items[0]->grades[$USER->id])) {
                        $this->gradeitem = $grades->items[0]->grades[$USER->id];
                        // grade->grade is the adjusted grade, for a true percent
                        // we need to shift and scale according to grademin and grademax
                        $percent = $this->gradeitem->grade;
                        if ($grades->items[0]->grademax > 0) {
                            $percent = (($percent - $grades->items[0]->grademin) / $grades->items[0]->grademax);
                        }
                        $this->gradeitem->percent = round($percent * 100);
                    }
                }
            }
        }
        return $this->gradeitem;
    }
}
Back to Top