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 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
|
<?php // $Id: datalib.php,v 1.298.2.11 2006/10/08 19:44:34 skodak Exp $
/**
* Library of functions for database manipulation.
*
* Other main libraries:
* - weblib.php - functions that produce web output
* - moodlelib.php - general-purpose Moodle functions
* @author Martin Dougiamas and many others
* @version $Id: datalib.php,v 1.298.2.11 2006/10/08 19:44:34 skodak Exp $
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
/// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
$empty_rs_cache = array(); // Keeps copies of the recordsets used in one invocation
/// FUNCTIONS FOR DATABASE HANDLING ////////////////////////////////
/**
* Execute a given sql command string
*
* Completely general function - it just runs some SQL and reports success.
*
* @uses $db
* @param string $command The sql string you wish to be executed.
* @param bool $feedback Set this argument to true if the results generated should be printed. Default is true.
* @return string
*/
function execute_sql($command, $feedback=true) {
/// Completely general function - it just runs some SQL and reports success.
global $db, $CFG;
$olddebug = $db->debug;
if (!$feedback) {
$db->debug = false;
}
$empty_rs_cache = array(); // Clear out the cache, just in case changes were made to table structures
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
$result = $db->Execute($command);
$db->debug = $olddebug;
if ($result) {
if ($feedback) {
notify(get_string('success'), 'notifysuccess');
}
return true;
} else {
if ($feedback) {
echo '<p><font color="red"><strong>'. get_string('error') .'</strong></font></p>';
}
if (!empty($CFG->dblogerror)) {
$debug=array_shift(debug_backtrace());
error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $command");
}
return false;
}
}
/**
* on DBs that support it, switch to transaction mode and begin a transaction
* you'll need to ensure you call commit_sql() or your changes *will* be lost
* this is _very_ useful for massive updates
*/
function begin_sql() {
/// Completely general function - it just runs some SQL and reports success.
global $CFG;
if ($CFG->dbtype === 'postgres7') {
return execute_sql('BEGIN', false);
}
return true;
}
/**
* on DBs that support it, commit the transaction
*/
function rollback_sql() {
/// Completely general function - it just runs some SQL and reports success.
global $CFG;
if ($CFG->dbtype === 'postgres7') {
return execute_sql('ROLLBACK', false);
}
return true;
}
/**
* returns db specific uppercase function
*/
function db_uppercase() {
global $CFG;
switch (strtolower($CFG->dbtype)) {
case "postgres7":
return "upper";
case "mysql":
default:
return "ucase";
}
}
/**
* returns db specific lowercase function
*/
function db_lowercase() {
global $CFG;
switch (strtolower($CFG->dbtype)) {
case "postgres7":
return "lower";
case "mysql":
default:
return "lcase";
}
}
/**
* on DBs that support it, commit the transaction
*/
function commit_sql() {
/// Completely general function - it just runs some SQL and reports success.
global $CFG;
if ($CFG->dbtype === 'postgres7') {
return execute_sql('COMMIT', false);
}
return true;
}
/**
* Run an arbitrary sequence of semicolon-delimited SQL commands
*
* Assumes that the input text (file or string) consists of
* a number of SQL statements ENDING WITH SEMICOLONS. The
* semicolons MUST be the last character in a line.
* Lines that are blank or that start with "#" or "--" (postgres) are ignored.
* Only tested with mysql dump files (mysqldump -p -d moodle)
*
* @uses $CFG
* @param string $sqlfile The path where a file with sql commands can be found on the server.
* @param string $sqlstring If no path is supplied then a string with semicolon delimited sql
* commands can be supplied in this argument.
* @return bool Returns true if databse was modified successfully.
*/
function modify_database($sqlfile='', $sqlstring='') {
global $CFG;
$success = true; // Let's be optimistic
if (!empty($sqlfile)) {
if (!is_readable($sqlfile)) {
$success = false;
echo '<p>Tried to modify database, but "'. $sqlfile .'" doesn\'t exist!</p>';
return $success;
} else {
$lines = file($sqlfile);
}
} else {
$sqlstring = trim($sqlstring);
if ($sqlstring{strlen($sqlstring)-1} != ";") {
$sqlstring .= ";"; // add it in if it's not there.
}
$lines[] = $sqlstring;
}
$command = '';
foreach ($lines as $line) {
$line = rtrim($line);
$length = strlen($line);
if ($length and $line[0] <> '#' and $line[0].$line[1] <> '--') {
if (substr($line, $length-1, 1) == ';') {
$line = substr($line, 0, $length-1); // strip ;
$command .= $line;
$command = str_replace('prefix_', $CFG->prefix, $command); // Table prefixes
if (! execute_sql($command)) {
$success = false;
}
$command = '';
} else {
$command .= $line;
}
}
}
return $success;
}
/// FUNCTIONS TO MODIFY TABLES ////////////////////////////////////////////
/**
* Add a new field to a table, or modify an existing one (if oldfield is defined).
* Warning: Please be careful on primary keys, as this function will eat auto_increments
* @uses $CFG
* @uses $db
* @param string $table ?
* @param string $oldfield ?
* @param string $field ?
* @param string $type ?
* @param string $size ?
* @param string $signed ?
* @param string $default ?
* @param string $null ?
* @todo Finish documenting this function
*/
function table_column($table, $oldfield, $field, $type='integer', $size='10',
$signed='unsigned', $default='0', $null='not null', $after='') {
global $CFG, $db, $empty_rs_cache;
if (!empty($empty_rs_cache[$table])) { // Clear the recordset cache because it's out of date
unset($empty_rs_cache[$table]);
}
switch (strtolower($CFG->dbtype)) {
case 'mysql':
case 'mysqlt':
switch (strtolower($type)) {
case 'text':
$type = 'TEXT';
$signed = '';
break;
case 'integer':
$type = 'INTEGER('. $size .')';
break;
case 'varchar':
$type = 'VARCHAR('. $size .')';
$signed = '';
break;
case 'char':
$type = 'CHAR('. $size .')';
$signed = '';
break;
}
if (!empty($oldfield)) {
$operation = 'CHANGE '. $oldfield .' '. $field;
} else {
$operation = 'ADD '. $field;
}
$default = 'DEFAULT \''. $default .'\'';
if (!empty($after)) {
$after = 'AFTER `'. $after .'`';
}
return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' '. $operation .' '. $type .' '. $signed .' '. $default .' '. $null .' '. $after);
case 'postgres7': // From Petri Asikainen
//Check db-version
$dbinfo = $db->ServerInfo();
$dbver = substr($dbinfo['version'],0,3);
//to prevent conflicts with reserved words
$realfield = '"'. $field .'"';
$field = '"'. $field .'_alter_column_tmp"';
$oldfield = '"'. $oldfield .'"';
switch (strtolower($type)) {
case 'tinyint':
case 'integer':
if ($size <= 4) {
$type = 'INT2';
}
if ($size <= 10) {
$type = 'INT';
}
if ($size > 10) {
$type = 'INT8';
}
break;
case 'varchar':
$type = 'VARCHAR('. $size .')';
break;
case 'char':
$type = 'CHAR('. $size .')';
$signed = '';
break;
}
$default = '\''. $default .'\'';
//After is not implemented in postgesql
//if (!empty($after)) {
// $after = "AFTER '$after'";
//}
//Use transactions
execute_sql('BEGIN');
//Always use temporary column
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
//Add default values
execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default);
if ($dbver >= '7.3') {
// modifying 'not null' is posible before 7.3
//update default values to table
if (strtoupper($null) == 'NOT NULL') {
execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default .' WHERE '. $field .' IS NULL');
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
} else {
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' DROP NOT NULL');
}
}
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET DEFAULT '. $default);
if ( $oldfield != '""' ) {
// We are changing the type of a column. This may require doing some casts...
$casting = '';
$oldtype = column_type($table, $oldfield);
$newtype = column_type($table, $field);
// Do we need a cast?
if($newtype == 'N' && $oldtype == 'C') {
$casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS REAL)';
}
else if($newtype == 'I' && $oldtype == 'C') {
$casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS INTEGER)';
}
else {
$casting = $oldfield;
}
// Run the update query, casting as necessary
execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .' = '. $casting);
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' DROP COLUMN '. $oldfield);
}
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $field .' TO '. $realfield);
return execute_sql('COMMIT');
default:
switch (strtolower($type)) {
case 'integer':
$type = 'INTEGER';
break;
case 'varchar':
$type = 'VARCHAR';
break;
}
$default = 'DEFAULT \''. $default .'\'';
if (!empty($after)) {
$after = 'AFTER '. $after;
}
if (!empty($oldfield)) {
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $oldfield .' '. $field);
} else {
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
}
execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $default);
}
}
/**
* Get the data type of a table column, using an ADOdb MetaType() call.
*
* @uses $CFG
* @uses $db
* @param string $table The name of the database table
* @param string $column The name of the field in the table
* @return string Field type or false if error
*/
function column_type($table, $column) {
global $CFG, $db;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
if(!$rs = $db->Execute('SELECT '.$column.' FROM '.$CFG->prefix.$table.' LIMIT 0')) {
return false;
}
$field = $rs->FetchField(0);
return $rs->MetaType($field->type);
}
/// GENERIC FUNCTIONS TO CHECK AND COUNT RECORDS ////////////////////////////////////////
/**
* Test whether a record exists in a table where all the given fields match the given values.
*
* The record to test is specified by giving up to three fields that must
* equal the corresponding values.
*
* @uses $CFG
* @param string $table The table to check.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return bool true if a matching record exists, else false.
*/
function record_exists($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
global $CFG;
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
return record_exists_sql('SELECT * FROM '. $CFG->prefix . $table .' '. $select .' LIMIT 1');
}
/**
* Test whether a SQL SELECT statement returns any records.
*
* This function returns true if the SQL statement executes
* without any errors and returns at least one record.
*
* @param string $sql The SQL statement to execute.
* @return bool true if the SQL executes without errors and returns at least one record.
*/
function record_exists_sql($sql) {
$rs = get_recordset_sql($sql);
if ($rs && $rs->RecordCount() > 0) {
return true;
} else {
return false;
}
}
/**
* Count the records in a table where all the given fields match the given values.
*
* @uses $CFG
* @param string $table The table to query.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return int The count of records returned from the specified criteria.
*/
function count_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
global $CFG;
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
return count_records_sql('SELECT COUNT(*) FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Count the records in a table which match a particular WHERE clause.
*
* @uses $CFG
* @param string $table The database table to be checked against.
* @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
* @param string $countitem The count string to be used in the SQL call. Default is COUNT(*).
* @return int The count of records returned from the specified criteria.
*/
function count_records_select($table, $select='', $countitem='COUNT(*)') {
global $CFG;
if ($select) {
$select = 'WHERE '.$select;
}
return count_records_sql('SELECT '. $countitem .' FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Get the result of a SQL SELECT COUNT(...) query.
*
* Given a query that counts rows, return that count. (In fact,
* given any query, return the first field of the first record
* returned. However, this method should only be used for the
* intended purpose.) If an error occurrs, 0 is returned.
*
* @uses $CFG
* @uses $db
* @param string $sql The SQL string you wish to be executed.
* @return int the count. If an error occurrs, 0 is returned.
*/
function count_records_sql($sql) {
$rs = get_recordset_sql($sql);
if ($rs) {
return $rs->fields[0];
} else {
return 0;
}
}
/// GENERIC FUNCTIONS TO GET, INSERT, OR UPDATE DATA ///////////////////////////////////
/**
* Get a single record as an object
*
* @uses $CFG
* @param string $table The table to select from.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return mixed a fieldset object containing the first mathcing record, or false if none found.
*/
function get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*') {
global $CFG;
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
return get_record_sql('SELECT '.$fields.' FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Get a single record as an object using an SQL statement
*
* The SQL statement should normally only return one record. In debug mode
* you will get a warning if more record is returned (unless you
* set $expectmultiple to true). In non-debug mode, it just returns
* the first record.
*
* @uses $CFG
* @uses $db
* @param string $sql The SQL string you wish to be executed, should normally only return one record.
* @param bool $expectmultiple If the SQL cannot be written to conviniently return just one record,
* set this to true to hide the debug message.
* @param bool $nolimit sometimes appending ' LIMIT 1' to the SQL causes an error. Set this to true
* to stop your SQL being modified. This argument should probably be deprecated.
* @return Found record as object. False if not found or error
*/
function get_record_sql($sql, $expectmultiple=false, $nolimit=false) {
global $CFG;
if ($nolimit) {
$limit = '';
} else if ($expectmultiple) {
$limit = ' LIMIT 1';
} else if (isset($CFG->debug) && $CFG->debug > 7) {
// Debugging mode - don't use a limit of 1, but do change the SQL, because sometimes that
// causes errors, and in non-debug mode you don't see the error message and it is
// impossible to know what's wrong.
$limit = ' LIMIT 100';
} else {
$limit = ' LIMIT 1';
}
if (!$rs = get_recordset_sql($sql . $limit)) {
return false;
}
$recordcount = $rs->RecordCount();
if ($recordcount == 0) { // Found no records
return false;
} else if ($recordcount == 1) { // Found one record
return (object)$rs->fields;
} else { // Error: found more than one record
notify('Error: Turn off debugging to hide this error.');
notify($sql . $limit);
if ($records = $rs->GetAssoc(true)) {
notify('Found more than one record in get_record_sql !');
print_object($records);
} else {
notify('Very strange error in get_record_sql !');
print_object($rs);
}
print_continue("$CFG->wwwroot/$CFG->admin/config.php");
}
}
/**
* Gets one record from a table, as an object
*
* @uses $CFG
* @param string $table The database table to be checked against.
* @param string $select A fragment of SQL to be used in a where clause in the SQL call.
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return object|false Returns an array of found records (as objects) or false if no records or error occured.
*/
function get_record_select($table, $select='', $fields='*') {
global $CFG;
if ($select) {
$select = 'WHERE '. $select;
}
return get_record_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Get a number of records as an ADODB RecordSet.
*
* Selects records from the table $table.
*
* If specified, only records where the field $field has value $value are retured.
*
* If specified, the results will be sorted as specified by $sort. This
* is added to the SQL as "ORDER BY $sort". Example values of $sort
* mightbe "time ASC" or "time DESC".
*
* If $fields is specified, only those fields are returned.
*
* This function is internal to datalib, and should NEVER should be called directly
* from general Moodle scripts. Use get_record, get_records etc.
*
* If you only want some of the records, specify $limitfrom and $limitnum.
* The query will skip the first $limitfrom records (according to the sort
* order) and then return the next $limitnum records. If either of $limitfrom
* or $limitnum is specified, both must be present.
*
* The return value is an ADODB RecordSet object
* @link http://phplens.com/adodb/reference.functions.adorecordset.html
* if the query succeeds. If an error occurrs, false is returned.
*
* @param string $table the table to query.
* @param string $field a field to check (optional).
* @param string $value the value the field must have (requred if field1 is given, else optional).
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an ADODB RecordSet object, or false if an error occured.
*/
function get_recordset($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
if ($field) {
$select = "$field = '$value'";
} else {
$select = '';
}
return get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
}
/**
* Get a number of records as an ADODB RecordSet.
*
* If given, $select is used as the SELECT parameter in the SQL query,
* otherwise all records from the table are returned.
*
* Other arguments and the return type as for @see function get_recordset.
*
* @uses $CFG
* @param string $table the table to query.
* @param string $select A fragment of SQL to be used in a where clause in the SQL call.
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an ADODB RecordSet object, or false if an error occured.
*/
function get_recordset_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
global $CFG;
if ($select) {
$select = ' WHERE '. $select;
}
if ($limitfrom !== '') {
$limit = sql_paging_limit($limitfrom, $limitnum);
} else {
$limit = '';
}
if ($sort) {
$sort = ' ORDER BY '. $sort;
}
return get_recordset_sql('SELECT '. $fields .' FROM '. $CFG->prefix . $table . $select . $sort .' '. $limit);
}
/**
* Get a number of records as an ADODB RecordSet.
*
* Only records where $field takes one of the values $values are returned.
* $values should be a comma-separated list of values, for example "4,5,6,10"
* or "'foo','bar','baz'".
*
* Other arguments and the return type as for @see function get_recordset.
*
* @param string $table the table to query.
* @param string $field a field to check (optional).
* @param string $values comma separated list of values the field must have (requred if field is given, else optional).
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an ADODB RecordSet object, or false if an error occured.
*/
function get_recordset_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
if ($field) {
$select = "$field IN ($values)";
} else {
$select = '';
}
return get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
}
/**
* Get a number of records as an ADODB RecordSet. $sql must be a complete SQL query.
* This function is internal to datalib, and should NEVER should be called directly
* from general Moodle scripts. Use get_record, get_records etc.
*
* The return type is as for @see function get_recordset.
*
* @uses $CFG
* @uses $db
* @param string $sql the SQL select query to execute.
* @return mixed an ADODB RecordSet object, or false if an error occured.
*/
function get_recordset_sql($sql) {
global $CFG, $db;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
if (!$rs = $db->Execute($sql)) {
if (isset($CFG->debug) and $CFG->debug > 7) {
notify($db->ErrorMsg() .'<br /><br />'. $sql);
}
if (!empty($CFG->dblogerror)) {
$debug=array_shift(debug_backtrace());
error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
}
return false;
}
return $rs;
}
/**
* Utility function used by the following 4 methods.
*
* @param object an ADODB RecordSet object.
* @return mixed mixed an array of objects, or false if an error occured or the RecordSet was empty.
*/
function recordset_to_array($rs) {
if ($rs && $rs->RecordCount() > 0) {
if ($records = $rs->GetAssoc(true)) {
foreach ($records as $key => $record) {
$objects[$key] = (object) $record;
}
return $objects;
} else {
return false;
}
} else {
return false;
}
}
/**
* Get a number of records as an array of objects.
*
* If the query succeeds and returns at least one record, the
* return value is an array of objects, one object for each
* record found. The array key is the value from the first
* column of the result set. The object associated with that key
* has a member variable for each column of the results.
*
* @param string $table the table to query.
* @param string $field a field to check (optional).
* @param string $value the value the field must have (requred if field1 is given, else optional).
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
$rs = get_recordset($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
return recordset_to_array($rs);
}
/**
* Get a number of records as an array of objects.
*
* Return value as for @see function get_records.
*
* @param string $table the table to query.
* @param string $select A fragment of SQL to be used in a where clause in the SQL call.
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
$rs = get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
return recordset_to_array($rs);
}
/**
* Get a number of records as an array of objects.
*
* Return value as for @see function get_records.
*
* @param string $table The database table to be checked against.
* @param string $field The field to search
* @param string $values Comma separated list of possible value
* @param string $sort Sort order (as valid SQL sort parameter)
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function get_records_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
$rs = get_recordset_list($table, $field, $values, $sort, $fields, $limitfrom, $limitnum);
return recordset_to_array($rs);
}
/**
* Get a number of records as an array of objects.
*
* Return value as for @see function get_records.
*
* @param string $sql the SQL select query to execute.
* @return mixed an array of objects, or false if no records were found or an error occured.
*/
function get_records_sql($sql) {
$rs = get_recordset_sql($sql);
return recordset_to_array($rs);
}
/**
* Utility function used by the following 3 methods.
*
* @param object an ADODB RecordSet object with two columns.
* @return mixed an associative array, or false if an error occured or the RecordSet was empty.
*/
function recordset_to_menu($rs) {
if ($rs && $rs->RecordCount() > 0) {
while (!$rs->EOF) {
$menu[$rs->fields[0]] = $rs->fields[1];
$rs->MoveNext();
}
return $menu;
} else {
return false;
}
}
/**
* Get the first two columns from a number of records as an associative array.
*
* Arguments as for @see function get_recordset.
*
* If no errors occur, and at least one records is found, the return value
* is an associative whose keys come from the first field of each record,
* and whose values are the corresponding second fields. If no records are found,
* or an error occurs, false is returned.
*
* @param string $table the table to query.
* @param string $field a field to check (optional).
* @param string $value the value the field must have (requred if field1 is given, else optional).
* @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
* @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
* @return mixed an associative array, or false if no records were found or an error occured.
*/
function get_records_menu($table, $field='', $value='', $sort='', $fields='*') {
$rs = get_recordset($table, $field, $value, $sort, $fields);
return recordset_to_menu($rs);
}
/**
* Get the first two columns from a number of records as an associative array.
*
* Arguments as for @see function get_recordset_select.
* Return value as for @see function get_records_menu.
*
* @param string $table The database table to be checked against.
* @param string $select A fragment of SQL to be used in a where clause in the SQL call.
* @param string $sort Sort order (optional) - a valid SQL order parameter
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return mixed an associative array, or false if no records were found or an error occured.
*/
function get_records_select_menu($table, $select='', $sort='', $fields='*') {
$rs = get_recordset_select($table, $select, $sort, $fields);
return recordset_to_menu($rs);
}
/**
* Get the first two columns from a number of records as an associative array.
*
* Arguments as for @see function get_recordset_sql.
* Return value as for @see function get_records_menu.
*
* @param string $sql The SQL string you wish to be executed.
* @return mixed an associative array, or false if no records were found or an error occured.
*/
function get_records_sql_menu($sql) {
$rs = get_recordset_sql($sql);
return recordset_to_menu($rs);
}
/**
* Get a single value from a table row where all the given fields match the given values.
*
* @param string $table the table to query.
* @param string $return the field to return the value of.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return mixed the specified value, or false if an error occured.
*/
function get_field($table, $return, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
global $CFG;
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
$rs = get_recordset_sql('SELECT ' . $return . ' FROM ' . $CFG->prefix . $table . ' ' . $select);
if ($rs && $rs->RecordCount() == 1) {
return $rs->fields[$return];
} else {
return false;
}
}
/**
* Get a single value from a table.
*
* @param string $sql an SQL statement expected to return a single value.
* @return mixed the specified value, or false if an error occured.
*/
function get_field_sql($sql) {
$rs = get_recordset_sql($sql);
if ($rs && $rs->RecordCount() == 1) {
return $rs->fields[0];
} else {
return false;
}
}
/**
* Get an array of data from one or more fields from a database
* use to get a column, or a series of distinct values
*
* @uses $CFG
* @uses $db
* @param string $sql The SQL string you wish to be executed.
* @return mixed|false Returns the value return from the SQL statment or false if an error occured.
* @todo Finish documenting this function
*/
function get_fieldset_sql($sql) {
global $db, $CFG;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
$rs = $db->Execute($sql);
if (!$rs) {
if (isset($CFG->debug) and $CFG->debug > 7) {
notify($db->ErrorMsg() .'<br /><br />'. $sql);
}
if (!empty($CFG->dblogerror)) {
$debug=array_shift(debug_backtrace());
error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
}
return false;
}
if ( $rs->RecordCount() > 0 ) {
$results = array();
while (!$rs->EOF) {
array_push($results, $rs->fields[0]);
$rs->MoveNext();
}
return $results;
} else {
return false;
}
}
/**
* Set a single field in every table row where all the given fields match the given values.
*
* @uses $CFG
* @uses $db
* @param string $table The database table to be checked against.
* @param string $newfield the field to set.
* @param string $newvalue the value to set the field to.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return mixed An ADODB RecordSet object with the results from the SQL call or false.
*/
function set_field($table, $newfield, $newvalue, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
global $db, $CFG;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
return $db->Execute('UPDATE '. $CFG->prefix . $table .' SET '. $newfield .' = \''. $newvalue .'\' '. $select);
}
/**
* Delete the records from a table where all the given fields match the given values.
*
* @uses $CFG
* @uses $db
* @param string $table the table to delete from.
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
* @return mixed An ADODB RecordSet object with the results from the SQL call or false.
*/
function delete_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
global $db, $CFG;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
$select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
return $db->Execute('DELETE FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Delete one or more records from a table
*
* @uses $CFG
* @uses $db
* @param string $table The database table to be checked against.
* @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
* @return object A PHP standard object with the results from the SQL call.
* @todo Verify return type.
*/
function delete_records_select($table, $select='') {
global $CFG, $db;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
if ($select) {
$select = 'WHERE '.$select;
}
return $db->Execute('DELETE FROM '. $CFG->prefix . $table .' '. $select);
}
/**
* Insert a record into a table and return the "id" field if required
*
* If the return ID isn't required, then this just reports success as true/false.
* $dataobject is an object containing needed data
*
* @uses $db
* @uses $CFG
* @param string $table The database table to be checked against.
* @param array $dataobject A data object with values for one or more fields in the record
* @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
* @param string $primarykey The primary key of the table we are inserting into (almost always "id")
*/
function insert_record($table, $dataobject, $returnid=true, $primarykey='id') {
global $db, $CFG, $empty_rs_cache;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
/// In Moodle we always use auto-numbering fields for the primary key
/// so let's unset it now before it causes any trouble later
unset($dataobject->{$primarykey});
/// Get an empty recordset. Cache for multiple inserts.
if (empty($empty_rs_cache[$table])) {
/// Execute a dummy query to get an empty recordset
if (!$empty_rs_cache[$table] = $db->Execute('SELECT * FROM '. $CFG->prefix . $table .' WHERE '. $primarykey .' = \'-1\'')) {
return false;
}
}
$rs = $empty_rs_cache[$table];
/// Postgres doesn't have the concept of primary key built in
/// and will return the OID which isn't what we want.
/// The efficient and transaction-safe strategy is to
/// move the sequence forward first, and make the insert
/// with an explicit id.
if ( $CFG->dbtype === 'postgres7' && $returnid == true ) {
if ($nextval = (int)get_field_sql("SELECT NEXTVAL('{$CFG->prefix}{$table}_{$primarykey}_seq')")) {
$dataobject->{$primarykey} = $nextval;
}
}
/// Get the correct SQL from adoDB
if (!$insertSQL = $db->GetInsertSQL($rs, (array)$dataobject, true)) {
return false;
}
/// Run the SQL statement
if (!$rs = $db->Execute($insertSQL)) {
if (isset($CFG->debug) and $CFG->debug > 7) {
notify($db->ErrorMsg() .'<br /><br />'.$insertSQL);
}
if (!empty($CFG->dblogerror)) {
$debug=array_shift(debug_backtrace());
error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $insertSQL");
}
return false;
}
/// If a return ID is not needed then just return true now
if (!$returnid) {
return true;
}
/// We already know the record PK if it's been passed explicitly,
/// or if we've retrieved it from a sequence (Postgres).
if (!empty($dataobject->{$primarykey})) {
return $dataobject->{$primarykey};
}
/// This only gets triggered with non-Postgres databases
/// however we have some postgres fallback in case we failed
/// to find the sequence.
$id = $db->Insert_ID();
if ($CFG->dbtype === 'postgres7') {
// try to get the primary key based on id
if ( ($rs = $db->Execute('SELECT '. $primarykey .' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id))
&& ($rs->RecordCount() == 1) ) {
trigger_error("Retrieved $primarykey from oid on table $table because we could not find the sequence.");
return (integer)$rs->fields[0];
}
trigger_error('Failed to retrieve primary key after insert: SELECT '. $primarykey .
' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id);
return false;
}
return (integer)$id;
}
/**
* Escape all dangerous characters in a data record
*
* $dataobject is an object containing needed data
* Run over each field exectuting addslashes() function
* to escape SQL unfriendly characters (e.g. quotes)
* Handy when writing back data read from the database
*
* @param $dataobject Object containing the database record
* @return object Same object with neccessary characters escaped
*/
function addslashes_object( $dataobject ) {
$a = get_object_vars( $dataobject);
foreach ($a as $key=>$value) {
$a[$key] = addslashes( $value );
}
return (object)$a;
}
/**
* Update a record in a table
*
* $dataobject is an object containing needed data
* Relies on $dataobject having a variable "id" to
* specify the record to update
*
* @uses $CFG
* @uses $db
* @param string $table The database table to be checked against.
* @param array $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
* @return bool
*/
function update_record($table, $dataobject) {
global $db, $CFG;
if (! isset($dataobject->id) ) {
return false;
}
// Determine all the fields in the table
if (!$columns = $db->MetaColumns($CFG->prefix . $table)) {
return false;
}
$data = (array)$dataobject;
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
// Pull out data matching these fields
foreach ($columns as $column) {
if ($column->name <> 'id' and isset($data[$column->name]) ) {
$ddd[$column->name] = $data[$column->name];
// PostgreSQL bytea support
if ($CFG->dbtype == 'postgres7' && $column->type == 'bytea') {
$ddd[$column->name] = $db->BlobEncode($ddd[$column->name]);
}
}
}
// Construct SQL queries
$numddd = count($ddd);
$count = 0;
$update = '';
foreach ($ddd as $key => $value) {
$count++;
$update .= $key .' = \''. $value .'\''; // All incoming data is already quoted
if ($count < $numddd) {
$update .= ', ';
}
}
if ($rs = $db->Execute('UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'')) {
return true;
} else {
if (isset($CFG->debug) and $CFG->debug > 7) {
notify($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE id = \''. $dataobject->id .'\'');
}
if (!empty($CFG->dblogerror)) {
$debug=array_shift(debug_backtrace());
error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'");
}
return false;
}
}
/// USER DATABASE ////////////////////////////////////////////////
/**
* Get the guest user information from the database
*
* @return object(user) An associative array with the details of the guest user account.
* @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
*/
function get_guest() {
return get_complete_user_data('username', 'guest');
}
/**
* Returns $user object of the main admin user
*
* @uses $CFG
* @return object(admin) An associative array representing the admin user.
* @todo Verify documentation of this function
*/
function get_admin () {
global $CFG;
if ( $admins = get_admins() ) {
foreach ($admins as $admin) {
return $admin; // ie the first one
}
} else {
return false;
}
}
/**
* Returns list of all admins
*
* @uses $CFG
* @return object
*/
function get_admins() {
global $CFG;
return get_records_sql("SELECT u.*, a.id as adminid
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_admins a
WHERE a.userid = u.id
ORDER BY a.id ASC");
}
/**
* Returns list of all creators
*
* @uses $CFG
* @return object
*/
function get_creators() {
global $CFG;
return get_records_sql("SELECT u.*
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_coursecreators a
WHERE a.userid = u.id
ORDER BY u.id ASC");
}
function get_courses_in_metacourse($metacourseid) {
global $CFG;
$sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
AND mc.child_course = c.id ORDER BY c.shortname";
return get_records_sql($sql);
}
function get_courses_notin_metacourse($metacourseid,$count=false) {
global $CFG;
if ($count) {
$sql = "SELECT COUNT(c.id)";
} else {
$sql = "SELECT c.id,c.shortname,c.fullname";
}
$alreadycourses = get_courses_in_metacourse($metacourseid);
$sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
return get_records_sql($sql);
}
/**
* Returns $user object of the main teacher for a course
*
* @uses $CFG
* @param int $courseid The course in question.
* @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
* @todo Finish documenting this function
*/
function get_teacher($courseid) {
global $CFG;
if ( $teachers = get_course_teachers($courseid, 't.authority ASC')) {
foreach ($teachers as $teacher) {
if ($teacher->authority) {
return $teacher; // the highest authority teacher
}
}
} else {
return false;
}
}
/**
* Searches logs to find all enrolments since a certain date
*
* used to print recent activity
*
* @uses $CFG
* @param int $courseid The course in question.
* @return object|false {@link $USER} records or false if error.
* @todo Finish documenting this function
*/
function get_recent_enrolments($courseid, $timestart) {
global $CFG;
return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_students s,
{$CFG->prefix}log l
WHERE l.time > '$timestart'
AND l.course = '$courseid'
AND l.module = 'course'
AND l.action = 'enrol'
AND l.info = u.id
AND u.id = s.userid
AND s.course = '$courseid'
ORDER BY l.time ASC");
}
/**
* Returns array of userinfo of all students in this course
* or on this site if courseid is id of site
*
* @uses $CFG
* @uses SITEID
* @param int $courseid The course in question.
* @param string $sort ?
* @param string $dir ?
* @param int $page ?
* @param int $recordsperpage ?
* @param string $firstinitial ?
* @param string $lastinitial ?
* @param ? $group ?
* @param string $search ?
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @param string $exceptions ?
* @return object
* @todo Finish documenting this function
*/
function get_course_students($courseid, $sort='s.timeaccess', $dir='', $page=0, $recordsperpage=99999,
$firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
global $CFG;
if ($courseid == SITEID and $CFG->allusersaresitestudents) {
// return users with confirmed, undeleted accounts who are not site teachers
// the following is a mess because of different conventions in the different user functions
$sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
$sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
$sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
$fields = str_replace('u.', '', $fields);
if ($sort) {
$sort = $sort .' '. $dir;
}
// Now we have to make sure site teachers are excluded
if ($teachers = get_records('user_teachers', 'course', SITEID)) {
foreach ($teachers as $teacher) {
$exceptions .= ','. $teacher->userid;
}
$exceptions = ltrim($exceptions, ',');
}
return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
$page, $recordsperpage, $fields ? $fields : '*');
}
$limit = sql_paging_limit($page, $recordsperpage);
$LIKE = sql_ilike();
$fullname = sql_fullname('u.firstname','u.lastname');
$groupmembers = '';
// make sure it works on the site course
$select = 's.course = \''. $courseid .'\' AND ';
if ($courseid == SITEID) {
$select = '';
}
$select .= 's.userid = u.id AND u.deleted = \'0\' ';
if (!$fields) {
$fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
'u.country, u.picture, u.idnumber, u.department, u.institution, '.
'u.emailstop, u.lang, u.timezone, s.timeaccess as lastaccess';
}
if ($search) {
$search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
}
if ($firstinitial) {
$select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
}
if ($lastinitial) {
$select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
}
if ($group === 0) { /// Need something here to get all students not in a group
return array();
} else if ($group !== NULL) {
$groupmembers = ', '. $CFG->prefix .'groups_members gm ';
$select .= ' AND u.id = gm.userid AND gm.groupid = \''. $group .'\'';
}
if (!empty($exceptions)) {
$select .= ' AND u.id NOT IN ('. $exceptions .')';
}
if ($sort) {
$sort = ' ORDER BY '. $sort .' ';
}
$students = get_records_sql("SELECT $fields
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_students s
$groupmembers
WHERE $select $search $sort $dir $limit");
if ($courseid != SITEID) {
return $students;
}
// We are here because we need the students for the site.
// These also include teachers on real courses minus those on the site
if ($teachers = get_records('user_teachers', 'course', SITEID)) {
foreach ($teachers as $teacher) {
$exceptions .= ','. $teacher->userid;
}
$exceptions = ltrim($exceptions, ',');
$select .= ' AND u.id NOT IN ('. $exceptions .')';
}
if (!$teachers = get_records_sql("SELECT $fields
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_teachers s
$groupmembers
WHERE $select $search $sort $dir $limit")) {
return $students;
}
if (!$students) {
return $teachers;
}
return $teachers + $students;
}
/**
* Counts the students in a given course (or site), or a subset of them
*
* @param object $course The course in question as a course object.
* @param string $search ?
* @param string $firstinitial ?
* @param string $lastinitial ?
* @param ? $group ?
* @param string $exceptions ?
* @return int
* @todo Finish documenting this function
*/
function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
return count($students);
}
return 0;
}
/**
* Returns list of all teachers in this course
*
* If $courseid matches the site id then this function
* returns a list of all teachers for the site.
*
* @uses $CFG
* @param int $courseid The course in question.
* @param string $sort ?
* @param string $exceptions ?
* @return object
* @todo Finish documenting this function
*/
function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
global $CFG;
if (!empty($exceptions)) {
$exceptions = ' AND u.id NOT IN ('. $exceptions .') ';
}
if (!empty($sort)) {
$sort = ' ORDER by '.$sort;
}
return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_teachers t
WHERE t.course = '$courseid' AND t.userid = u.id
AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
}
/**
* Returns all the users of a course: students and teachers
*
* @param int $courseid The course in question.
* @param string $sort ?
* @param string $exceptions ?
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return object
* @todo Finish documenting this function
*/
function get_course_users($courseid, $sort='timeaccess DESC', $exceptions='', $fields='') {
/// Using this method because the single SQL is too inefficient
// Note that this has the effect that teachers and students are
// sorted individually. Returns first all teachers, then all students
if (!$teachers = get_course_teachers($courseid, $sort, $exceptions)) {
$teachers = array();
}
if (!$students = get_course_students($courseid, $sort, '', 0, 99999, '', '', NULL, '', $fields, $exceptions)) {
$students = array();
}
return $teachers + $students;
}
/**
* Search through course users
*
* If $coursid specifies the site course then this function searches
* through all undeleted and confirmed users
*
* @uses $CFG
* @uses SITEID
* @param int $courseid The course in question.
* @param int $groupid The group in question.
* @param string $searchtext ?
* @param string $sort ?
* @param string $exceptions ?
* @return object
* @todo Finish documenting this function
*/
function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
global $CFG;
$LIKE = sql_ilike();
$fullname = sql_fullname('u.firstname', 'u.lastname');
if (!empty($exceptions)) {
$except = ' AND u.id NOT IN ('. $exceptions .') ';
} else {
$except = '';
}
if (!empty($sort)) {
$order = ' ORDER BY '. $sort;
} else {
$order = '';
}
$select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
if (!$courseid or $courseid == SITEID) {
return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
FROM {$CFG->prefix}user u
WHERE $select
AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
$except $order");
} else {
if ($groupid) {
return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
FROM {$CFG->prefix}user u,
{$CFG->prefix}groups_members g
WHERE $select AND g.groupid = '$groupid' AND g.userid = u.id
AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
$except $order");
} else {
if (!$teachers = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_teachers s
WHERE $select AND s.course = '$courseid' AND s.userid = u.id
AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
$except $order")) {
$teachers = array();
}
if (!$students = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
FROM {$CFG->prefix}user u,
{$CFG->prefix}user_students s
WHERE $select AND s.course = '$courseid' AND s.userid = u.id
AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
$except $order")) {
$students = array();
}
return $teachers + $students;
}
}
}
/**
* Returns a list of all site users
* Obsolete, just calls get_course_users(SITEID)
*
* @uses SITEID
* @deprecated Use {@link get_course_users()} instead.
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return object|false {@link $USER} records or false if error.
* @todo Finish documenting this function. The return type need to be better defined.
*/
function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
return get_course_users(SITEID, $sort, $exceptions, $fields);
}
/**
* Returns a subset of users
*
* @uses $CFG
* @param bool $get If false then only a count of the records is returned
* @param string $search A simple string to search for
* @param bool $confirmed A switch to allow/disallow unconfirmed users
* @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
* @param string $sort A SQL snippet for the sorting criteria to use
* @param string $firstinitial ?
* @param string $lastinitial ?
* @param string $page ?
* @param string $recordsperpage ?
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
* @todo Finish documenting this function. The return type needs to be better defined.
*/
function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
$firstinitial='', $lastinitial='', $page=0, $recordsperpage=99999, $fields='*') {
global $CFG;
$limit = sql_paging_limit($page, $recordsperpage);
$LIKE = sql_ilike();
$fullname = sql_fullname();
$select = 'username <> \'guest\' AND username <> \'changeme\' AND deleted = 0';
if (!empty($search)){
$search = trim($search);
$select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
}
if ($confirmed) {
$select .= ' AND confirmed = \'1\' ';
}
if ($exceptions) {
$select .= ' AND id NOT IN ('. $exceptions .') ';
}
if ($firstinitial) {
$select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
}
if ($lastinitial) {
$select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
}
if ($sort and $get) {
$sort = ' ORDER BY '. $sort .' ';
} else {
$sort = '';
}
if ($get) {
return get_records_select('user', $select .' '. $sort .' '. $limit, '', $fields);
} else {
return count_records_select('user', $select .' '. $sort .' '. $limit);
}
}
/**
* shortdesc (optional)
*
* longdesc
*
* @uses $CFG
* @param string $sort ?
* @param string $dir ?
* @param int $categoryid ?
* @param int $categoryid ?
* @param string $search ?
* @param string $firstinitial ?
* @param string $lastinitial ?
* @returnobject {@link $USER} records
* @todo Finish documenting this function
*/
function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=99999,
$search='', $firstinitial='', $lastinitial='') {
global $CFG;
$limit = sql_paging_limit($page, $recordsperpage);
$LIKE = sql_ilike();
$fullname = sql_fullname();
$select = "deleted <> '1' AND username <> 'changeme'";
if (!empty($search)) {
$search = trim($search);
$select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
}
if ($firstinitial) {
$select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
}
if ($lastinitial) {
$select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
}
if ($sort) {
$sort = ' ORDER BY '. $sort .' '. $dir;
}
/// warning: will return UNCONFIRMED USERS
return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed
FROM {$CFG->prefix}user
WHERE $select $sort $limit ");
}
/**
* Full list of users that have confirmed their accounts.
*
* @uses $CFG
* @return object
*/
function get_users_confirmed() {
global $CFG;
return get_records_sql("SELECT *
FROM {$CFG->prefix}user
WHERE confirmed = 1
AND deleted = 0
AND username <> 'guest'
AND username <> 'changeme'");
}
/**
* Full list of users that have not yet confirmed their accounts.
*
* @uses $CFG
* @param string $cutofftime ?
* @return object {@link $USER} records
* @todo Finish documenting this function
*/
function get_users_unconfirmed($cutofftime=2000000000) {
global $CFG;
return get_records_sql("SELECT *
FROM {$CFG->prefix}user
WHERE confirmed = 0
AND firstaccess > 0
AND firstaccess < '$cutofftime'");
}
/**
* Full list of bogus accounts that are probably not ever going to be used
*
* @uses $CFG
* @param string $cutofftime ?
* @return object {@link $USER} records
* @todo Finish documenting this function
*/
function get_users_not_fully_set_up($cutofftime=2000000000) {
global $CFG;
return get_records_sql("SELECT *
FROM {$CFG->prefix}user
WHERE confirmed = 1
AND lastaccess > 0
AND lastaccess < '$cutofftime'
AND deleted = 0
AND (lastname = '' OR firstname = '' OR email = '')");
}
/**
* shortdesc (optional)
*
* longdesc
*
* @uses $CFG
* @param string $cutofftime ?
* @return object {@link $USER} records
* @todo Finish documenting this function
*/
function get_users_longtimenosee($cutofftime) {
global $CFG;
return get_records_sql("SELECT DISTINCT *
FROM {$CFG->prefix}user_students
WHERE timeaccess > '0'
AND timeaccess < '$cutofftime' ");
}
/**
* Returns an array of group objects that the user is a member of
* in the given course. If userid isn't specified, then return a
* list of all groups in the course.
*
* @uses $CFG
* @param int $courseid The id of the course in question.
* @param int $userid The id of the user in question as found in the 'user' table 'id' field.
* @return object
*/
function get_groups($courseid, $userid=0) {
global $CFG;
if ($userid) {
$dbselect = ', '. $CFG->prefix .'groups_members m';
$userselect = 'AND m.groupid = g.id AND m.userid = \''. $userid .'\'';
} else {
$dbselect = '';
$userselect = '';
}
return get_records_sql("SELECT DISTINCT g.*
FROM {$CFG->prefix}groups g $dbselect
WHERE g.courseid = '$courseid' $userselect ");
}
/**
* Returns an array of user objects
*
* @uses $CFG
* @param int $groupid The group in question.
* @param string $sort ?
* @param string $exceptions ?
* @return object
* @todo Finish documenting this function
*/
function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='', $fields='u.*') {
global $CFG;
if (!empty($exceptions)) {
$except = ' AND u.id NOT IN ('. $exceptions .') ';
} else {
$except = '';
}
// in postgres, you can't have things in sort that aren't in the select, so...
$extrafield = str_replace('ASC','',$sort);
$extrafield = str_replace('DESC','',$extrafield);
$extrafield = trim($extrafield);
if (!empty($extrafield)) {
$extrafield = ','.$extrafield;
}
return get_records_sql("SELECT DISTINCT $fields $extrafield
FROM {$CFG->prefix}user u,
{$CFG->prefix}groups_members m
WHERE m.groupid = '$groupid'
AND m.userid = u.id $except
ORDER BY $sort");
}
/**
* An efficient way of finding all the users who aren't in groups yet
*
* Currently unimplemented.
* @uses $CFG
* @param int $courseid The course in question.
* @return object
*/
function get_users_not_in_group($courseid) {
global $CFG;
return array(); /// XXX TO BE DONE
}
/**
* Returns an array of user objects
*
* @uses $CFG
* @param int $groupid The group(s) in question.
* @param string $sort How to sort the results
* @return object (changed to groupids)
*/
function get_group_students($groupids, $sort='u.lastaccess DESC') {
global $CFG;
if (is_array($groupids)){
$groups = $groupids;
$groupstr = '(m.groupid = '.array_shift($groups);
foreach ($groups as $index => $value){
$groupstr .= ' OR m.groupid = '.$value;
}
$groupstr .= ')';
}
else {
$groupstr = 'm.groupid = '.$groupids;
}
return get_records_sql("SELECT DISTINCT u.*
FROM {$CFG->prefix}user u,
{$CFG->prefix}groups_members m,
{$CFG->prefix}groups g,
{$CFG->prefix}user_students s
WHERE $groupstr
AND m.userid = u.id
AND m.groupid = g.id
AND g.courseid = s.course
AND s.userid = u.id
ORDER BY $sort");
}
/**
* Returns list of all the teachers who can access a group
*
* @uses $CFG
* @param int $courseid The course in question.
* @param int $groupid The group in question.
* @return object
*/
function get_group_teachers($courseid, $groupid) {
/// Returns a list of all the teachers who can access a group
if ($teachers = get_course_teachers($courseid)) {
foreach ($teachers as $key => $teacher) {
if ($teacher->editall) { // These can access anything
continue;
}
if (($teacher->authority > 0) and ismember($groupid, $teacher->id)) { // Specific group teachers
continue;
}
unset($teachers[$key]);
}
}
return $teachers;
}
/**
* Returns the user's group in a particular course
*
* @uses $CFG
* @param int $courseid The course in question.
* @param int $userid The id of the user as found in the 'user' table.
* @param int $groupid The id of the group the user is in.
* @return object
* @todo Finish documenting this function
*/
function user_group($courseid, $userid) {
global $CFG;
return get_records_sql("SELECT g.*
FROM {$CFG->prefix}groups g,
{$CFG->prefix}groups_members m
WHERE g.courseid = '$courseid'
AND g.id = m.groupid
AND m.userid = '$userid'
ORDER BY name ASC");
}
/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
/**
* Returns $course object of the top-level site.
*
* @return course A {@link $COURSE} object for the site
* @todo Finish documenting this function.
*/
function get_site() {
global $SITE;
if (!empty($SITE->id)) { // We already have a global to use, so return that
return $SITE;
}
if ($course = get_record('course', 'category', 0)) {
return $course;
} else {
return false;
}
}
/**
* Returns list of courses, for whole site, or category
*
* Returns list of courses, for whole site, or category
*
* @param type description
*
* Important: Using c.* for fields is extremely expensive because
* we are using distinct. You almost _NEVER_ need all the fields
* in such a large SELECT
*/
function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
global $USER, $CFG;
$categoryselect = "";
if ($categoryid != "all" && is_numeric($categoryid)) {
$categoryselect = "c.category = '$categoryid'";
}
$teachertable = "";
$visiblecourses = "";
$sqland = "";
if (!empty($categoryselect)) {
$sqland = "AND ";
}
if (!empty($USER->id)) { // May need to check they are a teacher
if (!iscreator()) {
$visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
$teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
}
} else {
$visiblecourses = "$sqland c.visible > 0";
}
if ($categoryselect or $visiblecourses) {
$selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
} else {
$selectsql = "{$CFG->prefix}course c $teachertable";
}
$extrafield = str_replace('ASC','',$sort);
$extrafield = str_replace('DESC','',$extrafield);
$extrafield = trim($extrafield);
if (!empty($extrafield)) {
$extrafield = ','.$extrafield;
}
return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
}
/**
* Returns list of courses, for whole site, or category
*
* Similar to get_courses, but allows paging
*
* @param type description
*
* Important: Using c.* for fields is extremely expensive because
* we are using distinct. You almost _NEVER_ need all the fields
* in such a large SELECT
*/
function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
&$totalcount, $limitfrom="", $limitnum="") {
global $USER, $CFG;
$categoryselect = "";
if ($categoryid != "all" && is_numeric($categoryid)) {
$categoryselect = "c.category = '$categoryid'";
}
$teachertable = "";
$visiblecourses = "";
$sqland = "";
if (!empty($categoryselect)) {
$sqland = "AND ";
}
if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
if (!iscreator()) {
$visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
$teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
}
} else {
$visiblecourses = "$sqland c.visible > 0";
}
if ($limitfrom !== "") {
$limit = sql_paging_limit($limitfrom, $limitnum);
} else {
$limit = "";
}
$selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
$totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
}
/**
* List of courses that a user is a member of.
*
* @uses $CFG
* @param int $userid The user of interest
* @param string $sort ?
* @return object {@link $COURSE} records
*/
function get_my_courses($userid, $sort='visible DESC,sortorder ASC') {
global $CFG, $USER;
$course = array();
if ($students = get_records('user_students', 'userid', $userid, '', 'id, course')) {
foreach ($students as $student) {
$course[$student->course] = $student->course;
}
}
if (count($course) > 0 && empty($USER->admin)) {
if ($courses = get_records_list('course', 'id', implode(',', $course), '', 'id,visible')) {
foreach ($courses as $k => $c) {
if (!$c->visible) {
unset($course[$c->id]);
}
}
}
}
if ($teachers = get_records('user_teachers', 'userid', $userid, '', 'id, course')) {
foreach ($teachers as $teacher) {
$course[$teacher->course] = $teacher->course;
}
}
if (empty($course)) {
return $course;
}
$courseids = implode(',', $course);
return get_records_list('course', 'id', $courseids, $sort);
// The following is correct but VERY slow with large datasets
//
// return get_records_sql("SELECT c.*
// FROM {$CFG->prefix}course c,
// {$CFG->prefix}user_students s,
// {$CFG->prefix}user_teachers t
// WHERE (s.userid = '$userid' AND s.course = c.id)
// OR (t.userid = '$userid' AND t.course = c.id)
// GROUP BY c.id
// ORDER BY $sort");
}
/**
* A list of courses that match a search
*
* @uses $CFG
* @param array $searchterms ?
* @param string $sort ?
* @param int $page ?
* @param int $recordsperpage ?
* @param int $totalcount Passed in by reference. ?
* @return object {@link $COURSE} records
* @todo Finish documenting this function
*/
function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
global $CFG;
$limit = sql_paging_limit($page, $recordsperpage);
//to allow case-insensitive search for postgesql
if ($CFG->dbtype == 'postgres7') {
$LIKE = 'ILIKE';
$NOTLIKE = 'NOT ILIKE'; // case-insensitive
$REGEXP = '~*';
$NOTREGEXP = '!~*';
} else {
$LIKE = 'LIKE';
$NOTLIKE = 'NOT LIKE';
$REGEXP = 'REGEXP';
$NOTREGEXP = 'NOT REGEXP';
}
$fullnamesearch = '';
$summarysearch = '';
foreach ($searchterms as $searchterm) {
if ($fullnamesearch) {
$fullnamesearch .= ' AND ';
}
if ($summarysearch) {
$summarysearch .= ' AND ';
}
if (substr($searchterm,0,1) == '+') {
$searchterm = substr($searchterm,1);
$summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
$fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
} else if (substr($searchterm,0,1) == "-") {
$searchterm = substr($searchterm,1);
$summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
$fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
} else {
$summarysearch .= ' summary '. $LIKE .'\'%'. $searchterm .'%\' ';
$fullnamesearch .= ' fullname '. $LIKE .'\'%'. $searchterm .'%\' ';
}
}
$selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
$totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
$courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort .' '. $limit);
if ($courses) { /// Remove unavailable courses from the list
foreach ($courses as $key => $course) {
if (!$course->visible) {
if (!isteacher($course->id)) {
unset($courses[$key]);
$totalcount--;
}
}
}
}
return $courses;
}
/**
* Returns a sorted list of categories
*
* @param string $parent ?
* @param string $sort ?
* @return ?
* @todo Finish documenting this function
*/
function get_categories($parent='none', $sort='sortorder ASC') {
if ($parent === 'none') {
$categories = get_records('course_categories', '', '', $sort);
} else {
$categories = get_records('course_categories', 'parent', $parent, $sort);
}
if ($categories) { /// Remove unavailable categories from the list
$creator = iscreator();
foreach ($categories as $key => $category) {
if (!$category->visible) {
if (!$creator) {
unset($categories[$key]);
}
}
}
}
return $categories;
}
/**
* This recursive function makes sure that the courseorder is consecutive
*
* @param type description
*
* $n is the starting point, offered only for compatilibity -- will be ignored!
* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
* safely from 1.4 to 1.5
*/
function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
global $CFG;
$count = 0;
$catgap = 1000; // "standard" category gap
$tolerance = 200; // how "close" categories can get
if ($categoryid > 0){
// update depth and path
$cat = get_record('course_categories', 'id', $categoryid);
if ($cat->parent == 0) {
$depth = 0;
$path = '';
} else if ($depth == 0 ) { // doesn't make sense; get from DB
// this is only called if the $depth parameter looks dodgy
$parent = get_record('course_categories', 'id', $cat->parent);
$path = $parent->path;
$depth = $parent->depth;
}
$path = $path . '/' . $categoryid;
$depth = $depth + 1;
set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
set_field('course_categories', 'depth', $depth, 'id', $categoryid);
}
// get some basic info about courses in the category
$info = get_record_sql('SELECT MIN(sortorder) AS min,
MAX(sortorder) AS max,
COUNT(sortorder) AS count
FROM ' . $CFG->prefix . 'course
WHERE category=' . $categoryid);
if (is_object($info)) { // no courses?
$max = $info->max;
$count = $info->count;
$min = $info->min;
unset($info);
}
if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
$n = $min;
}
// $hasgap flag indicates whether there's a gap in the sequence
$hasgap = false;
if ($max-$min+1 != $count) {
$hasgap = true;
}
// $mustshift indicates whether the sequence must be shifted to
// meet its range
$mustshift = false;
if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
$mustshift = true;
}
// actually sort only if there are courses,
// and we meet one ofthe triggers:
// - safe flag
// - they are not in a continuos block
// - they are too close to the 'bottom'
if ($count && ( $safe || $hasgap || $mustshift ) ) {
// special, optimized case where all we need is to shift
if ( $mustshift && !$safe && !$hasgap) {
$shift = $n + $catgap - $min;
// UPDATE course SET sortorder=sortorder+$shift
execute_sql("UPDATE {$CFG->prefix}course
SET sortorder=sortorder+$shift
WHERE category=$categoryid", 0);
$n = $n + $catgap + $count;
} else { // do it slowly
$n = $n + $catgap;
// if the new sequence overlaps the current sequence, lack of transactions
// will stop us -- shift things aside for a moment...
if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbtype==='mysql')) {
$shift = $max + $n + 1000;
execute_sql("UPDATE {$CFG->prefix}course
SET sortorder=sortorder+$shift
WHERE category=$categoryid", 0);
}
$courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
begin_sql();
foreach ($courses as $course) {
if ($course->sortorder != $n ) { // save db traffic
set_field('course', 'sortorder', $n, 'id', $course->id);
}
$n++;
}
commit_sql();
}
}
set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
// $n could need updating
$max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
if ($max > $n) {
$n = $max;
}
if ($categories = get_categories($categoryid)) {
foreach ($categories as $category) {
$n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
}
}
return $n+1;
}
/**
* This function creates a default separated/connected scale
*
* This function creates a default separated/connected scale
* so there's something in the database. The locations of
* strings and files is a bit odd, but this is because we
* need to maintain backward compatibility with many different
* existing language translations and older sites.
*
* @uses $CFG
*/
function make_default_scale() {
global $CFG;
$defaultscale = NULL;
$defaultscale->courseid = 0;
$defaultscale->userid = 0;
$defaultscale->name = get_string('separateandconnected');
$defaultscale->scale = get_string('postrating1', 'forum').','.
get_string('postrating2', 'forum').','.
get_string('postrating3', 'forum');
$defaultscale->timemodified = time();
/// Read in the big description from the file. Note this is not
/// HTML (despite the file extension) but Moodle format text.
$parentlang = get_string('parentlang');
if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
$file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
} else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
$file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
} else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
$file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
} else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
$file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
} else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
$file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
} else {
$file = '';
}
$defaultscale->description = addslashes(implode('', $file));
if ($defaultscale->id = insert_record('scale', $defaultscale)) {
execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
}
}
/**
* Returns a menu of all available scales from the site as well as the given course
*
* @uses $CFG
* @param int $courseid The id of the course as found in the 'course' table.
* @return object
*/
function get_scales_menu($courseid=0) {
global $CFG;
$sql = "SELECT id, name FROM {$CFG->prefix}scale
WHERE courseid = '0' or courseid = '$courseid'
ORDER BY courseid ASC, name ASC";
if ($scales = get_records_sql_menu($sql)) {
return $scales;
}
make_default_scale();
return get_records_sql_menu($sql);
}
/**
* Given a set of timezone records, put them in the database, replacing what is there
*
* @uses $CFG
* @param array $timezones An array of timezone records
*/
function update_timezone_records($timezones) {
/// Given a set of timezone records, put them in the database
global $CFG;
/// Clear out all the old stuff
execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
/// Insert all the new stuff
foreach ($timezones as $timezone) {
insert_record('timezone', $timezone);
}
}
/// MODULE FUNCTIONS /////////////////////////////////////////////////
/**
* Just gets a raw list of all modules in a course
*
* @uses $CFG
* @param int $courseid The id of the course as found in the 'course' table.
* @return object
* @todo Finish documenting this function
*/
function get_course_mods($courseid) {
global $CFG;
if (empty($courseid)) {
return false; // avoid warnings
}
return get_records_sql("SELECT cm.*, m.name as modname
FROM {$CFG->prefix}modules m,
{$CFG->prefix}course_modules cm
WHERE cm.course = '$courseid'
AND cm.module = m.id ");
}
/**
* Given an id of a course module, finds the coursemodule description
*
* @param string $modulename name of module type, eg. resource, assignment,...
* @param int $cmid course module id (id in course_modules table)
* @param int $courseid optional course id for extra validation
* @return object course module instance with instance and module name
*/
function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
global $CFG;
$courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
return get_record_sql("SELECT cm.*, m.name, md.name as modname
FROM {$CFG->prefix}course_modules cm,
{$CFG->prefix}modules md,
{$CFG->prefix}$modulename m
WHERE $courseselect
cm.id = '$cmid' AND
cm.instance = m.id AND
md.name = '$modulename' AND
md.id = cm.module");
}
/**
* Given an instance number of a module, finds the coursemodule description
*
* @param string $modulename name of module type, eg. resource, assignment,...
* @param int $instance module instance number (id in resource, assignment etc. table)
* @param int $courseid optional course id for extra validation
* @return object course module instance with instance and module name
*/
function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
global $CFG;
$courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
return get_record_sql("SELECT cm.*, m.name, md.name as modname
FROM {$CFG->prefix}course_modules cm,
{$CFG->prefix}modules md,
{$CFG->prefix}$modulename m
WHERE $courseselect
cm.instance = m.id AND
md.name = '$modulename' AND
md.id = cm.module AND
m.id = '$instance'");
}
/**
* Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
*
* Returns an array of all the active instances of a particular
* module in given courses, sorted in the order they are defined
* in the course. Returns false on any errors.
*
* @uses $CFG
* @param string $modulename The name of the module to get instances for
* @param array(courses) $courses This depends on an accurate $course->modinfo
* @todo Finish documenting this function. Is a course object to be documented as object(course) or array(course) since a coures object is really just an associative array, not a php object?
*/
function get_all_instances_in_courses($modulename,$courses) {
global $CFG;
if (empty($courses) || !is_array($courses) || count($courses) == 0) {
return array();
}
if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
FROM {$CFG->prefix}course_modules cm,
{$CFG->prefix}course_sections cw,
{$CFG->prefix}modules md,
{$CFG->prefix}$modulename m
WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
cm.instance = m.id AND
cm.section = cw.id AND
md.name = '$modulename' AND
md.id = cm.module")) {
return array();
}
$outputarray = array();
foreach ($courses as $course) {
// Hide non-visible instances from students
if (isteacher($course->id)) {
$invisible = -1;
} else {
$invisible = 0;
}
if (!$modinfo = unserialize($course->modinfo)) {
continue;
}
foreach ($modinfo as $mod) {
if ($mod->mod == $modulename and $mod->visible > $invisible) {
$instance = $rawmods[$mod->cm];
if (!empty($mod->extra)) {
$instance->extra = $mod->extra;
}
$outputarray[] = $instance;
}
}
}
return $outputarray;
}
/**
* Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
*
* Returns an array of all the active instances of a particular
* module in a given course, sorted in the order they are defined
* in the course. Returns false on any errors.
*
* @uses $CFG
* @param string $modulename The name of the module to get instances for
* @param object(course) $course This depends on an accurate $course->modinfo
* @todo Finish documenting this function. Is a course object to be documented as object(course) or array(course) since a coures object is really just an associative array, not a php object?
*/
function get_all_instances_in_course($modulename, $course) {
global $CFG;
if (!$modinfo = unserialize($course->modinfo)) {
return array();
}
if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode
FROM {$CFG->prefix}course_modules cm,
{$CFG->prefix}course_sections cw,
{$CFG->prefix}modules md,
{$CFG->prefix}$modulename m
WHERE cm.course = '$course->id' AND
cm.instance = m.id AND
cm.section = cw.id AND
md.name = '$modulename' AND
md.id = cm.module")) {
return array();
}
// Hide non-visible instances from students
if (isteacher($course->id)) {
$invisible = -1;
} else {
$invisible = 0;
}
$outputarray = array();
foreach ($modinfo as $mod) {
if ($mod->mod == $modulename and $mod->visible > $invisible) {
$instance = $rawmods[$mod->cm];
if (!empty($mod->extra)) {
$instance->extra = $mod->extra;
}
$outputarray[] = $instance;
}
}
return $outputarray;
}
/**
* Determine whether a module instance is visible within a course
*
* Given a valid module object with info about the id and course,
* and the module's type (eg "forum") returns whether the object
* is visible or not
*
* @uses $CFG
* @param $moduletype ?
* @param $module ?
* @return bool
* @todo Finish documenting this function
*/
function instance_is_visible($moduletype, $module) {
global $CFG;
if (!empty($module->id)) {
if ($records = get_records_sql("SELECT cm.instance, cm.visible
FROM {$CFG->prefix}course_modules cm,
{$CFG->prefix}modules m
WHERE cm.course = '$module->course' AND
cm.module = m.id AND
m.name = '$moduletype' AND
cm.instance = '$module->id'")) {
foreach ($records as $record) { // there should only be one - use the first one
return $record->visible;
}
}
}
return true; // visible by default!
}
/// LOG FUNCTIONS /////////////////////////////////////////////////////
/**
* Add an entry to the log table.
*
* Add an entry to the log table. These are "action" focussed rather
* than web server hits, and provide a way to easily reconstruct what
* any particular student has been doing.
*
* @uses $CFG
* @uses $USER
* @uses $db
* @uses $REMOTE_ADDR
* @uses SITEID
* @param int $courseid The course id
* @param string $module The module name - e.g. forum, journal, resource, course, user etc
* @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
* @param string $url The file and parameters used to see the results of the action
* @param string $info Additional description information
* @param string $cm The course_module->id if there is one
* @param string $user If log regards $user other than $USER
*/
function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
// Note that this function intentionally does not follow the normal Moodle DB access idioms.
// This is for a good reason: it is the most frequently used DB update function,
// so it has been optimised for speed.
global $db, $CFG, $USER;
if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
$cm = 0;
}
if ($user) {
$userid = $user;
} else {
if (isset($USER->realuser)) { // Don't log
return;
}
$userid = empty($USER->id) ? '0' : $USER->id;
}
$REMOTE_ADDR = getremoteaddr();
$timenow = time();
$info = addslashes($info);
if (!empty($url)) { // could break doing html_entity_decode on an empty var.
$url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
}
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
$result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
if (!$result and ($CFG->debug > 7)) {
echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
}
if ( isset($USER) && (empty($user) || $user==$USER->id) ) {
$db->Execute('UPDATE '. $CFG->prefix .'user SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
WHERE id = \''. $userid .'\' ');
if ($courseid != SITEID && !empty($courseid)) { // logins etc dont't have a courseid and isteacher will break without it.
if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
if (isstudent($courseid)) {
$db->Execute('UPDATE '. $CFG->prefix .'user_students SET timeaccess = \''. $timenow .'\' '.
'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
} else if (isteacher($courseid, false, false)) {
$db->Execute('UPDATE '. $CFG->prefix .'user_teachers SET timeaccess = \''. $timenow .'\' '.
'WHERE course = \''. $courseid .'\' AND userid = \''. $userid .'\'');
}
}
}
}
/**
* Select all log records based on SQL criteria
*
* @uses $CFG
* @param string $select SQL select criteria
* @param string $order SQL order by clause to sort the records returned
* @param string $limitfrom ?
* @param int $limitnum ?
* @param int $totalcount Passed in by reference.
* @return object
* @todo Finish documenting this function
*/
function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
global $CFG;
if ($limitfrom !== '') {
$limit = sql_paging_limit($limitfrom, $limitnum);
} else {
$limit = '';
}
if ($order) {
$order = 'ORDER BY '. $order;
}
$selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
$countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
$totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
FROM '. $selectsql .' '. $order .' '. $limit);
}
/**
* Select all log records for a given course and user
*
* @uses $CFG
* @uses DAYSECS
* @param int $userid The id of the user as found in the 'user' table.
* @param int $courseid The id of the course as found in the 'course' table.
* @param string $coursestart ?
* @todo Finish documenting this function
*/
function get_logs_usercourse($userid, $courseid, $coursestart) {
global $CFG;
if ($courseid) {
$courseselect = ' AND course = \''. $courseid .'\' ';
} else {
$courseselect = '';
}
return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
FROM {$CFG->prefix}log
WHERE userid = '$userid'
AND time > '$coursestart' $courseselect
GROUP BY day ");
}
/**
* Select all log records for a given course, user, and day
*
* @uses $CFG
* @uses HOURSECS
* @param int $userid The id of the user as found in the 'user' table.
* @param int $courseid The id of the course as found in the 'course' table.
* @param string $daystart ?
* @return object
* @todo Finish documenting this function
*/
function get_logs_userday($userid, $courseid, $daystart) {
global $CFG;
if ($courseid) {
$courseselect = ' AND course = \''. $courseid .'\' ';
} else {
$courseselect = '';
}
return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
FROM {$CFG->prefix}log
WHERE userid = '$userid'
AND time > '$daystart' $courseselect
GROUP BY hour ");
}
/**
* Returns an object with counts of failed login attempts
*
* Returns information about failed login attempts. If the current user is
* an admin, then two numbers are returned: the number of attempts and the
* number of accounts. For non-admins, only the attempts on the given user
* are shown.
*
* @param string $mode Either 'admin', 'teacher' or 'everybody'
* @param string $username The username we are searching for
* @param string $lastlogin The date from which we are searching
* @return int
*/
function count_login_failures($mode, $username, $lastlogin) {
$select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
if (isadmin()) { // Return information about all accounts
if ($count->attempts = count_records_select('log', $select)) {
$count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
return $count;
}
} else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
return $count;
}
}
return NULL;
}
/// GENERAL HELPFUL THINGS ///////////////////////////////////
/**
* Dump a given object's information in a PRE block.
*
* Mostly just used for debugging.
*
* @param mixed $object The data to be printed
* @todo add example usage and example output
*/
function print_object($object) {
echo '<pre>';
print_r($object);
echo '</pre>';
}
/**
* Returns the proper SQL to do paging
*
* @uses $CFG
* @param string $page Offset page number
* @param string $recordsperpage Number of records per page
* @return string
*/
function sql_paging_limit($page, $recordsperpage) {
global $CFG;
switch ($CFG->dbtype) {
case 'postgres7':
return 'LIMIT '. $recordsperpage .' OFFSET '. $page;
default:
return 'LIMIT '. $page .','. $recordsperpage;
}
}
/**
* Returns the proper SQL to do LIKE in a case-insensitive way
*
* @uses $CFG
* @return string
*/
function sql_ilike() {
global $CFG;
switch ($CFG->dbtype) {
case 'mysql':
return 'LIKE';
default:
return 'ILIKE';
}
}
/**
* Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
*
* @uses $CFG
* @param string $firstname User's first name
* @param string $lastname User's last name
* @return string
*/
function sql_fullname($firstname='firstname', $lastname='lastname') {
global $CFG;
switch ($CFG->dbtype) {
case 'mysql':
return ' CONCAT('. $firstname .'," ",'. $lastname .') ';
case 'postgres7':
return " ". $firstname ."||' '||". $lastname ." ";
default:
return ' '. $firstname .'||" "||'. $lastname .' ';
}
}
/**
* Returns the proper SQL to do IS NULL
* @uses $CFG
* @param string $fieldname The field to add IS NULL to
* @return string
*/
function sql_isnull($fieldname) {
global $CFG;
switch ($CFG->dbtype) {
case 'mysql':
return $fieldname.' IS NULL';
default:
return $fieldname.' IS NULL';
}
}
/**
* Prepare a SQL WHERE clause to select records where the given fields match the given values.
*
* Prepares a where clause of the form
* WHERE field1 = value1 AND field2 = value2 AND field3 = value3
* except that you need only specify as many arguments (zero to three) as you need.
*
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
* @param string $value2 the value field2 must have (requred if field2 is given, else optional).
* @param string $field3 the third field to check (optional).
* @param string $value3 the value field3 must have (requred if field3 is given, else optional).
*/
function where_clause($field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
if ($field1) {
$select = "WHERE $field1 = '$value1'";
if ($field2) {
$select .= " AND $field2 = '$value2'";
if ($field3) {
$select .= " AND $field3 = '$value3'";
}
}
} else {
$select = '';
}
return $select;
}
/**
* Checks for pg or mysql > 4
*/
function check_db_compat() {
global $CFG,$db;
if ($CFG->dbtype == 'postgres7') {
return true;
}
if (!$rs = $db->Execute("SELECT version();")) {
return false;
}
if (intval($rs->fields[0]) <= 3) {
return false;
}
return true;
}
function course_parent_visible($course = null) {
global $CFG;
if (empty($course)) {
return true;
}
if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
return true;
}
return category_parent_visible($course->category);
}
function category_parent_visible($parent = 0) {
static $visible;
if (!$parent) {
return true;
}
if (empty($visible)) {
$visible = array(); // initialize
}
if (array_key_exists($parent,$visible)) {
return $visible[$parent];
}
$category = get_record('course_categories', 'id', $parent);
$list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path));
$list[] = $parent;
$parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC');
$v = true;
foreach ($parents as $p) {
if (!$p->visible) {
$v = false;
}
}
$visible[$parent] = $v; // now cache it
return $v;
}
// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
?>
|