/usr/share/moodle/lib/weblib.php is in moodle 1.9.9.dfsg2-6.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 | <?php // $Id$
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.com //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Library of functions for web output
*
* Library of all general-purpose Moodle PHP functions and constants
* that produce HTML output
*
* Other main libraries:
* - datalib.php - functions that access the database.
* - moodlelib.php - general-purpose Moodle functions.
* @author Martin Dougiamas
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
/// We are going to uses filterlib functions here
require_once("$CFG->libdir/filterlib.php");
require_once("$CFG->libdir/ajax/ajaxlib.php");
/// Constants
/// Define text formatting types ... eventually we can add Wiki, BBcode etc
/**
* Does all sorts of transformations and filtering
*/
define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
/**
* Plain HTML (with some tags stripped)
*/
define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
/**
* Plain text (even tags are printed in full)
*/
define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
/**
* Wiki-formatted text
* Deprecated: left here just to note that '3' is not used (at the moment)
* and to catch any latent wiki-like text (which generates an error)
*/
define('FORMAT_WIKI', '3'); // Wiki-formatted text
/**
* Markdown-formatted text http://daringfireball.net/projects/markdown/
*/
define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
/**
* TRUSTTEXT marker - if present in text, text cleaning should be bypassed
*/
define('TRUSTTEXT', '#####TRUSTTEXT#####');
/**
* Javascript related defines
*/
define('REQUIREJS_BEFOREHEADER', 0);
define('REQUIREJS_INHEADER', 1);
define('REQUIREJS_AFTERHEADER', 2);
/**
* Allowed tags - string of html tags that can be tested against for safe html tags
* @global string $ALLOWED_TAGS
*/
global $ALLOWED_TAGS;
$ALLOWED_TAGS =
'<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
/**
* Allowed protocols - array of protocols that are safe to use in links and so on
* @global string $ALLOWED_PROTOCOLS
*/
$ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
/// Functions
/**
* Add quotes to HTML characters
*
* Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
* This function is very similar to {@link p()}
*
* @param string $var the string potentially containing HTML characters
* @param boolean $strip to decide if we want to strip slashes or no. Default to false.
* true should be used to print data from forms and false for data from DB.
* @return string
*/
function s($var, $strip=false) {
if ($var === '0' or $var === false or $var === 0) {
return '0';
}
if ($strip) {
return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
} else {
return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars($var));
}
}
/**
* Add quotes to HTML characters
*
* Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
* This function is very similar to {@link s()}
*
* @param string $var the string potentially containing HTML characters
* @param boolean $strip to decide if we want to strip slashes or no. Default to false.
* true should be used to print data from forms and false for data from DB.
* @return string
*/
function p($var, $strip=false) {
echo s($var, $strip);
}
/**
* Does proper javascript quoting.
* Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
*
* @since 1.8 - 22/02/2007
* @param mixed value
* @return mixed quoted result
*/
function addslashes_js($var) {
if (is_string($var)) {
$var = str_replace('\\', '\\\\', $var);
$var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
$var = str_replace('</', '<\/', $var); // XHTML compliance
} else if (is_array($var)) {
$var = array_map('addslashes_js', $var);
} else if (is_object($var)) {
$a = get_object_vars($var);
foreach ($a as $key=>$value) {
$a[$key] = addslashes_js($value);
}
$var = (object)$a;
}
return $var;
}
/**
* Remove query string from url
*
* Takes in a URL and returns it without the querystring portion
*
* @param string $url the url which may have a query string attached
* @return string
*/
function strip_querystring($url) {
if ($commapos = strpos($url, '?')) {
return substr($url, 0, $commapos);
} else {
return $url;
}
}
/**
* Returns the URL of the HTTP_REFERER, less the querystring portion if required
* @param boolean $stripquery if true, also removes the query part of the url.
* @return string
*/
function get_referer($stripquery=true) {
if (isset($_SERVER['HTTP_REFERER'])) {
if ($stripquery) {
return strip_querystring($_SERVER['HTTP_REFERER']);
} else {
return $_SERVER['HTTP_REFERER'];
}
} else {
return '';
}
}
/**
* Returns the name of the current script, WITH the querystring portion.
* this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
* return different things depending on a lot of things like your OS, Web
* server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
* <b>NOTE:</b> This function returns false if the global variables needed are not set.
*
* @return string
*/
function me() {
if (!empty($_SERVER['REQUEST_URI'])) {
$return = $_SERVER['REQUEST_URI'];
} else if (!empty($_SERVER['PHP_SELF'])) {
if (!empty($_SERVER['QUERY_STRING'])) {
$return = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
} else {
$return = $_SERVER['PHP_SELF'];
}
} else if (!empty($_SERVER['SCRIPT_NAME'])) {
if (!empty($_SERVER['QUERY_STRING'])) {
$return = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
} else {
$return = $_SERVER['SCRIPT_NAME'];
}
} else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
if (!empty($_SERVER['QUERY_STRING'])) {
$return = $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
} else {
$return = $_SERVER['URL'];
}
} else {
notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
return false;
}
// sanitize the url a bit more, the encoding style may be different in vars above
$return = str_replace('"', '%22', $return);
$return = str_replace('\'', '%27', $return);
return $return;
}
/**
* Like {@link me()} but returns a full URL
* @see me()
* @return string
*/
function qualified_me() {
global $CFG;
if (!empty($CFG->wwwroot)) {
$url = parse_url($CFG->wwwroot);
}
if (!empty($url['host'])) {
$hostname = $url['host'];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$hostname = $_SERVER['SERVER_NAME'];
} else if (!empty($_ENV['SERVER_NAME'])) {
$hostname = $_ENV['SERVER_NAME'];
} else if (!empty($_SERVER['HTTP_HOST'])) {
$hostname = $_SERVER['HTTP_HOST'];
} else if (!empty($_ENV['HTTP_HOST'])) {
$hostname = $_ENV['HTTP_HOST'];
} else {
notify('Warning: could not find the name of this server!');
return false;
}
if (!empty($url['port'])) {
$hostname .= ':'.$url['port'];
} else if (!empty($_SERVER['SERVER_PORT'])) {
if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
$hostname .= ':'.$_SERVER['SERVER_PORT'];
}
}
// TODO, this does not work in the situation described in MDL-11061, but
// I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
// the server reports.
if (isset($_SERVER['HTTPS'])) {
$protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
} else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
$protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
} else {
$protocol = 'http://';
}
$url_prefix = $protocol.$hostname;
return $url_prefix . me();
}
/**
* Class for creating and manipulating urls.
*
* See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
*/
class moodle_url {
var $scheme = '';// e.g. http
var $host = '';
var $port = '';
var $user = '';
var $pass = '';
var $path = '';
var $fragment = '';
var $params = array(); //associative array of query string params
/**
* Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
*
* @param string $url url default null means use this page url with no query string
* empty string means empty url.
* if you pass any other type of url it will be parsed into it's bits, including query string
* @param array $params these params override anything in the query string where params have the same name.
*/
function moodle_url($url = null, $params = array()){
global $FULLME;
if ($url !== ''){
if ($url === null){
$url = strip_querystring($FULLME);
}
$parts = parse_url($url);
if ($parts === FALSE){
error('invalidurl');
}
if (isset($parts['query'])){
parse_str(str_replace('&', '&', $parts['query']), $this->params);
}
unset($parts['query']);
foreach ($parts as $key => $value){
$this->$key = $value;
}
$this->params($params);
}
}
/**
* Add an array of params to the params for this page.
*
* The added params override existing ones if they have the same name.
*
* @param array $params Defaults to null. If null then return value of param 'name'.
* @return array Array of Params for url.
*/
function params($params = null) {
if (!is_null($params)) {
return $this->params = $params + $this->params;
} else {
return $this->params;
}
}
/**
* Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
*
* @param string $arg1
* @param string $arg2
* @param string $arg3
*/
function remove_params(){
if ($thisargs = func_get_args()){
foreach ($thisargs as $arg){
if (isset($this->params[$arg])){
unset($this->params[$arg]);
}
}
} else { // no args
$this->params = array();
}
}
/**
* Add a param to the params for this page. The added param overrides existing one if they
* have the same name.
*
* @param string $paramname name
* @param string $param value
*/
function param($paramname, $param){
$this->params = array($paramname => $param) + $this->params;
}
function get_query_string($overrideparams = array()){
$arr = array();
$params = $overrideparams + $this->params;
foreach ($params as $key => $val){
$arr[] = urlencode($key)."=".urlencode($val);
}
return implode($arr, "&");
}
/**
* Outputs params as hidden form elements.
*
* @param array $exclude params to ignore
* @param integer $indent indentation
* @param array $overrideparams params to add to the output params, these
* override existing ones with the same name.
* @return string html for form elements.
*/
function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
$tabindent = str_repeat("\t", $indent);
$str = '';
$params = $overrideparams + $this->params;
foreach ($params as $key => $val){
if (FALSE === array_search($key, $exclude)) {
$val = s($val);
$str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
}
}
return $str;
}
/**
* Output url
*
* @param boolean $noquerystring whether to output page params as a query string in the url.
* @param array $overrideparams params to add to the output url, these override existing ones with the same name.
* @return string url
*/
function out($noquerystring = false, $overrideparams = array()) {
$uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
$uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
$uri .= $this->host ? $this->host : '';
$uri .= $this->port ? ':'.$this->port : '';
$uri .= $this->path ? $this->path : '';
if (!$noquerystring){
$uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
}
$uri .= $this->fragment ? '#'.$this->fragment : '';
return $uri;
}
/**
* Output action url with sesskey
*
* @param boolean $noquerystring whether to output page params as a query string in the url.
* @return string url
*/
function out_action($overrideparams = array()) {
$overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
return $this->out(false, $overrideparams);
}
}
/**
* Determine if there is data waiting to be processed from a form
*
* Used on most forms in Moodle to check for data
* Returns the data as an object, if it's found.
* This object can be used in foreach loops without
* casting because it's cast to (array) automatically
*
* Checks that submitted POST data exists and returns it as object.
*
* @param string $url not used anymore
* @return mixed false or object
*/
function data_submitted($url='') {
if (empty($_POST)) {
return false;
} else {
return (object)$_POST;
}
}
/**
* Moodle replacement for php stripslashes() function,
* works also for objects and arrays.
*
* The standard php stripslashes() removes ALL backslashes
* even from strings - so C:\temp becomes C:temp - this isn't good.
* This function should work as a fairly safe replacement
* to be called on quoted AND unquoted strings (to be sure)
*
* @param mixed something to remove unsafe slashes from
* @return mixed
*/
function stripslashes_safe($mixed) {
// there is no need to remove slashes from int, float and bool types
if (empty($mixed)) {
//nothing to do...
} else if (is_string($mixed)) {
if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
$mixed = str_replace("''", "'", $mixed);
} else { //the rest, simple and double quotes and backslashes
$mixed = str_replace("\\'", "'", $mixed);
$mixed = str_replace('\\"', '"', $mixed);
$mixed = str_replace('\\\\', '\\', $mixed);
}
} else if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = stripslashes_safe($value);
}
} else if (is_object($mixed)) {
$vars = get_object_vars($mixed);
foreach ($vars as $key => $value) {
$mixed->$key = stripslashes_safe($value);
}
}
return $mixed;
}
/**
* Recursive implementation of stripslashes()
*
* This function will allow you to strip the slashes from a variable.
* If the variable is an array or object, slashes will be stripped
* from the items (or properties) it contains, even if they are arrays
* or objects themselves.
*
* @param mixed the variable to remove slashes from
* @return mixed
*/
function stripslashes_recursive($var) {
if (is_object($var)) {
$new_var = new object();
$properties = get_object_vars($var);
foreach($properties as $property => $value) {
$new_var->$property = stripslashes_recursive($value);
}
} else if(is_array($var)) {
$new_var = array();
foreach($var as $property => $value) {
$new_var[$property] = stripslashes_recursive($value);
}
} else if(is_string($var)) {
$new_var = stripslashes($var);
} else {
$new_var = $var;
}
return $new_var;
}
/**
* Recursive implementation of addslashes()
*
* This function will allow you to add the slashes from a variable.
* If the variable is an array or object, slashes will be added
* to the items (or properties) it contains, even if they are arrays
* or objects themselves.
*
* @param mixed the variable to add slashes from
* @return mixed
*/
function addslashes_recursive($var) {
if (is_object($var)) {
$new_var = new object();
$properties = get_object_vars($var);
foreach($properties as $property => $value) {
$new_var->$property = addslashes_recursive($value);
}
} else if (is_array($var)) {
$new_var = array();
foreach($var as $property => $value) {
$new_var[$property] = addslashes_recursive($value);
}
} else if (is_string($var)) {
$new_var = addslashes($var);
} else { // nulls, integers, etc.
$new_var = $var;
}
return $new_var;
}
/**
* Given some normal text this function will break up any
* long words to a given size by inserting the given character
*
* It's multibyte savvy and doesn't change anything inside html tags.
*
* @param string $string the string to be modified
* @param int $maxsize maximum length of the string to be returned
* @param string $cutchar the string used to represent word breaks
* @return string
*/
function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
/// Loading the textlib singleton instance. We are going to need it.
$textlib = textlib_get_instance();
/// First of all, save all the tags inside the text to skip them
$tags = array();
filter_save_tags($string,$tags);
/// Process the string adding the cut when necessary
$output = '';
$length = $textlib->strlen($string);
$wordlength = 0;
for ($i=0; $i<$length; $i++) {
$char = $textlib->substr($string, $i, 1);
if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
$wordlength = 0;
} else {
$wordlength++;
if ($wordlength > $maxsize) {
$output .= $cutchar;
$wordlength = 0;
}
}
$output .= $char;
}
/// Finally load the tags back again
if (!empty($tags)) {
$output = str_replace(array_keys($tags), $tags, $output);
}
return $output;
}
/**
* This does a search and replace, ignoring case
* This function is only used for versions of PHP older than version 5
* which do not have a native version of this function.
* Taken from the PHP manual, by bradhuizenga @ softhome.net
*
* @param string $find the string to search for
* @param string $replace the string to replace $find with
* @param string $string the string to search through
* return string
*/
if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
function str_ireplace($find, $replace, $string) {
if (!is_array($find)) {
$find = array($find);
}
if(!is_array($replace)) {
if (!is_array($find)) {
$replace = array($replace);
} else {
// this will duplicate the string into an array the size of $find
$c = count($find);
$rString = $replace;
unset($replace);
for ($i = 0; $i < $c; $i++) {
$replace[$i] = $rString;
}
}
}
foreach ($find as $fKey => $fItem) {
$between = explode(strtolower($fItem),strtolower($string));
$pos = 0;
foreach($between as $bKey => $bItem) {
$between[$bKey] = substr($string,$pos,strlen($bItem));
$pos += strlen($bItem) + strlen($fItem);
}
$string = implode($replace[$fKey],$between);
}
return ($string);
}
}
/**
* Locate the position of a string in another string
*
* This function is only used for versions of PHP older than version 5
* which do not have a native version of this function.
* Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
*
* @param string $haystack The string to be searched
* @param string $needle The string to search for
* @param int $offset The position in $haystack where the search should begin.
*/
if (!function_exists('stripos')) { /// Only exists in PHP 5
function stripos($haystack, $needle, $offset=0) {
return strpos(strtoupper($haystack), strtoupper($needle), $offset);
}
}
/**
* This function will print a button/link/etc. form element
* that will work on both Javascript and non-javascript browsers.
* Relies on the Javascript function openpopup in javascript.php
*
* All parameters default to null, only $type and $url are mandatory.
*
* $url must be relative to home page eg /mod/survey/stuff.php
* @param string $url Web link relative to home page
* @param string $name Name to be assigned to the popup window (this is used by
* client-side scripts to "talk" to the popup window)
* @param string $linkname Text to be displayed as web link
* @param int $height Height to assign to popup window
* @param int $width Height to assign to popup window
* @param string $title Text to be displayed as popup page title
* @param string $options List of additional options for popup window
* @param string $return If true, return as a string, otherwise print
* @param string $id id added to the element
* @param string $class class added to the element
* @return string
* @uses $CFG
*/
function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
$height=400, $width=500, $title=null,
$options=null, $return=false, $id=null, $class=null) {
if (is_null($url)) {
debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
}
global $CFG;
if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
$options = null;
}
// add some sane default options for popup windows
if (!$options) {
$options = 'menubar=0,location=0,scrollbars,resizable';
}
if ($width) {
$options .= ',width='. $width;
}
if ($height) {
$options .= ',height='. $height;
}
if ($id) {
$id = ' id="'.$id.'" ';
}
if ($class) {
$class = ' class="'.$class.'" ';
}
if ($name) {
$_name = $name;
if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
}
} else {
$name = 'popup';
}
// get some default string, using the localized version of legacy defaults
if (is_null($linkname) || $linkname === '') {
$linkname = get_string('clickhere');
}
if (!$title) {
$title = get_string('popupwindowname');
}
$fullscreen = 0; // must be passed to openpopup
$element = '';
switch ($type) {
case 'button' :
$element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
"onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
break;
case 'link' :
// some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
if (!(strpos($url,$CFG->wwwroot) === false)) {
$url = substr($url, strlen($CFG->wwwroot));
}
$element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
"$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
break;
default :
error('Undefined element - can\'t create popup window.');
break;
}
if ($return) {
return $element;
} else {
echo $element;
}
}
/**
* Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
*
* @return string html code to display a link to a popup window.
* @see element_to_popup_window()
*/
function link_to_popup_window ($url, $name=null, $linkname=null,
$height=400, $width=500, $title=null,
$options=null, $return=false) {
return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
}
/**
* Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
*
* @return string html code to display a button to a popup window.
* @see element_to_popup_window()
*/
function button_to_popup_window ($url, $name=null, $linkname=null,
$height=400, $width=500, $title=null, $options=null, $return=false,
$id=null, $class=null) {
return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
}
/**
* Prints a simple button to close a window
* @param string $name name of the window to close
* @param boolean $return whether this function should return a string or output it
* @return string if $return is true, nothing otherwise
*/
function close_window_button($name='closewindow', $return=false) {
global $CFG;
$output = '';
$output .= '<div class="closewindow">' . "\n";
$output .= '<form action="#"><div>';
$output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
$output .= '</div></form>';
$output .= '</div>' . "\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
/*
* Try and close the current window immediately using Javascript
* @param int $delay the delay in seconds before closing the window
*/
function close_window($delay=0) {
?>
<script type="text/javascript">
//<![CDATA[
function close_this_window() {
self.close();
}
setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
//]]>
</script>
<noscript><center>
<?php print_string('pleaseclose') ?>
</center></noscript>
<?php
die;
}
/**
* Given an array of values, output the HTML for a select element with those options.
* Normally, you only need to use the first few parameters.
*
* @param array $options The options to offer. An array of the form
* $options[{value}] = {text displayed for that option};
* @param string $name the name of this form control, as in <select name="..." ...
* @param string $selected the option to select initially, default none.
* @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
* Set this to '' if you don't want a 'nothing is selected' option.
* @param string $script in not '', then this is added to the <select> element as an onchange handler.
* @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
* @param boolean $return if false (the default) the the output is printed directly, If true, the
* generated HTML is returned as a string.
* @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
* @param int $tabindex if give, sets the tabindex attribute on the <select> element. Default none.
* @param string $id value to use for the id attribute of the <select> element. If none is given,
* then a suitable one is constructed.
* @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
* By default, the list box will have a number of rows equal to min(10, count($options)), but if
* $listbox is an integer, that number is used for size instead.
* @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
* when $listbox display is enabled
* @param string $class value to use for the class attribute of the <select> element. If none is given,
* then a suitable one is constructed.
*/
function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
$nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
$id='', $listbox=false, $multiple=false, $class='') {
if ($nothing == 'choose') {
$nothing = get_string('choose') .'...';
}
$attributes = ($script) ? 'onchange="'. $script .'"' : '';
if ($disabled) {
$attributes .= ' disabled="disabled"';
}
if ($tabindex) {
$attributes .= ' tabindex="'.$tabindex.'"';
}
if ($id ==='') {
$id = 'menu'.$name;
// name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
$id = str_replace('[', '', $id);
$id = str_replace(']', '', $id);
}
if ($class ==='') {
$class = 'menu'.$name;
// name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
$class = str_replace('[', '', $class);
$class = str_replace(']', '', $class);
}
$class = 'select ' . $class; /// Add 'select' selector always
if ($listbox) {
if (is_integer($listbox)) {
$size = $listbox;
} else {
$numchoices = count($options);
if ($nothing) {
$numchoices += 1;
}
$size = min(10, $numchoices);
}
$attributes .= ' size="' . $size . '"';
if ($multiple) {
$attributes .= ' multiple="multiple"';
}
}
$output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
if ($nothing) {
$output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
if ($nothingvalue === $selected) {
$output .= ' selected="selected"';
}
$output .= '>'. $nothing .'</option>' . "\n";
}
if (!empty($options)) {
foreach ($options as $value => $label) {
$output .= ' <option value="'. s($value) .'"';
if ((string)$value == (string)$selected ||
(is_array($selected) && in_array($value, $selected))) {
$output .= ' selected="selected"';
}
if ($label === '') {
$output .= '>'. $value .'</option>' . "\n";
} else {
$output .= '>'. $label .'</option>' . "\n";
}
}
}
$output .= '</select>' . "\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
* Other options like choose_from_menu.
* @param string $name
* @param string $selected
* @param string $string (defaults to '')
* @param boolean $return whether this function should return a string or output it (defaults to false)
* @param boolean $disabled (defaults to false)
* @param int $tabindex
*/
function choose_from_menu_yesno($name, $selected, $script = '',
$return = false, $disabled = false, $tabindex = 0) {
return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
$selected, '', $script, '0', $return, $disabled, $tabindex);
}
/**
* Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
* including option headings with the first level.
*/
function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
$nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
if ($nothing == 'choose') {
$nothing = get_string('choose') .'...';
}
$attributes = ($script) ? 'onchange="'. $script .'"' : '';
if ($disabled) {
$attributes .= ' disabled="disabled"';
}
if ($tabindex) {
$attributes .= ' tabindex="'.$tabindex.'"';
}
$output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
if ($nothing) {
$output .= ' <option value="'. $nothingvalue .'"'. "\n";
if ($nothingvalue === $selected) {
$output .= ' selected="selected"';
}
$output .= '>'. $nothing .'</option>' . "\n";
}
if (!empty($options)) {
foreach ($options as $section => $values) {
$output .= ' <optgroup label="'. s(strip_tags(format_string($section))) .'">'."\n";
foreach ($values as $value => $label) {
$output .= ' <option value="'. format_string($value) .'"';
if ((string)$value == (string)$selected) {
$output .= ' selected="selected"';
}
if ($label === '') {
$output .= '>'. $value .'</option>' . "\n";
} else {
$output .= '>'. $label .'</option>' . "\n";
}
}
$output .= ' </optgroup>'."\n";
}
}
$output .= '</select>' . "\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Given an array of values, creates a group of radio buttons to be part of a form
*
* @param array $options An array of value-label pairs for the radio group (values as keys)
* @param string $name Name of the radiogroup (unique in the form)
* @param string $checked The value that is already checked
*/
function choose_from_radio ($options, $name, $checked='', $return=false) {
static $idcounter = 0;
if (!$name) {
$name = 'unnamed';
}
$output = '<span class="radiogroup '.$name."\">\n";
if (!empty($options)) {
$currentradio = 0;
foreach ($options as $value => $label) {
$htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
$output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
$output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
if ($value == $checked) {
$output .= ' checked="checked"';
}
if ($label === '') {
$output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
} else {
$output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
}
$currentradio = ($currentradio + 1) % 2;
}
}
$output .= '</span>' . "\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
/** Display an standard html checkbox with an optional label
*
* @param string $name The name of the checkbox
* @param string $value The valus that the checkbox will pass when checked
* @param boolean $checked The flag to tell the checkbox initial state
* @param string $label The label to be showed near the checkbox
* @param string $alt The info to be inserted in the alt tag
*/
function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
static $idcounter = 0;
if (!$name) {
$name = 'unnamed';
}
if ($alt) {
$alt = strip_tags($alt);
} else {
$alt = 'checkbox';
}
if ($checked) {
$strchecked = ' checked="checked"';
} else {
$strchecked = '';
}
$htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
$output = '<span class="checkbox '.$name."\">";
$output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
if(!empty($label)) {
$output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
}
$output .= '</span>'."\n";
if (empty($return)) {
echo $output;
} else {
return $output;
}
}
/** Display an standard html text field with an optional label
*
* @param string $name The name of the text field
* @param string $value The value of the text field
* @param string $label The label to be showed near the text field
* @param string $alt The info to be inserted in the alt tag
*/
function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
static $idcounter = 0;
if (empty($name)) {
$name = 'unnamed';
}
if (empty($alt)) {
$alt = 'textfield';
}
if (!empty($maxlength)) {
$maxlength = ' maxlength="'.$maxlength.'" ';
}
$htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
$output = '<span class="textfield '.$name."\">";
$output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
$output .= '</span>'."\n";
if (empty($return)) {
echo $output;
} else {
return $output;
}
}
/**
* Implements a complete little popup form
*
* @uses $CFG
* @param string $common The URL up to the point of the variable that changes
* @param array $options Alist of value-label pairs for the popup list
* @param string $formid Id must be unique on the page (originaly $formname)
* @param string $selected The option that is already selected
* @param string $nothing The label for the "no choice" option
* @param string $help The name of a help page if help is required
* @param string $helptext The name of the label for the help button
* @param boolean $return Indicates whether the function should return the text
* as a string or echo it directly to the page being rendered
* @param string $targetwindow The name of the target page to open the linked page in.
* @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
* @param array $optionsextra TODO, an array?
* @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
* button instead (as is always included for JS-disabled users). Set to true
* for a literal 'Go' button, or to a string to change the name of the button.
* @return string If $return is true then the entire form is returned as a string.
* @todo Finish documenting this function<br>
*/
function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
$targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
global $CFG;
static $go, $choose; /// Locally cached, in case there's lots on a page
if (empty($options)) {
return '';
}
if (!isset($go)) {
$go = get_string('go');
}
if ($nothing == 'choose') {
if (!isset($choose)) {
$choose = get_string('choose');
}
$nothing = $choose.'...';
}
// changed reference to document.getElementById('id_abc') instead of document.abc
// MDL-7861
$output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
' method="get" '.
$CFG->frametarget.
' id="'.$formid.'"'.
' class="popupform">';
if ($help) {
$button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
} else {
$button = '';
}
if ($selectlabel) {
$selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
}
if ($gobutton) {
// Using the no-JavaScript version
$javascript = '';
} else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
//IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
//onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
//Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
//so we do not fix the Opera behavior on Linux
$javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
} else {
//Other browser
$javascript = ' onchange="'.$targetwindow.
'.location=document.getElementById(\''.$formid.
'\').jump.options[document.getElementById(\''.
$formid.'\').jump.selectedIndex].value;"';
}
$output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
if ($nothing != '') {
$output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
}
$inoptgroup = false;
foreach ($options as $value => $label) {
if ($label == '--') { /// we are ending previous optgroup
/// Check to see if we already have a valid open optgroup
/// XHTML demands that there be at least 1 option within an optgroup
if ($inoptgroup and (count($optgr) > 1) ) {
$output .= implode('', $optgr);
$output .= ' </optgroup>';
}
$optgr = array();
$inoptgroup = false;
continue;
} else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
/// Check to see if we already have a valid open optgroup
/// XHTML demands that there be at least 1 option within an optgroup
if ($inoptgroup and (count($optgr) > 1) ) {
$output .= implode('', $optgr);
$output .= ' </optgroup>';
}
unset($optgr);
$optgr = array();
$optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
$inoptgroup = true; /// everything following will be in an optgroup
continue;
} else {
if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
{
$url=sid_process_url( $common . $value );
} else
{
$url=$common . $value;
}
$optstr = ' <option value="' . $url . '"';
if ($value == $selected) {
$optstr .= ' selected="selected"';
}
if (!empty($optionsextra[$value])) {
$optstr .= ' '.$optionsextra[$value];
}
if ($label) {
$optstr .= '>'. $label .'</option>' . "\n";
} else {
$optstr .= '>'. $value .'</option>' . "\n";
}
if ($inoptgroup) {
$optgr[] = $optstr;
} else {
$output .= $optstr;
}
}
}
/// catch the final group if not closed
if ($inoptgroup and count($optgr) > 1) {
$output .= implode('', $optgr);
$output .= ' </optgroup>';
}
$output .= '</select>';
$output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
if ($gobutton) {
$output .= '<input type="submit" value="'.
($gobutton===true ? $go : $gobutton).'" />';
} else {
$output .= '<div id="noscript'.$formid.'" style="display: inline;">';
$output .= '<input type="submit" value="'.$go.'" /></div>';
$output .= '<script type="text/javascript">'.
"\n//<![CDATA[\n".
'document.getElementById("noscript'.$formid.'").style.display = "none";'.
"\n//]]>\n".'</script>';
}
$output .= '</div></form>';
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints some red text
*
* @param string $error The text to be displayed in red
*/
function formerr($error) {
if (!empty($error)) {
echo '<span class="error">'. $error .'</span>';
}
}
/**
* Validates an email to make sure it makes sense.
*
* @param string $address The email address to validate.
* @return boolean
*/
function validate_email($address) {
return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
'(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
'@'.
'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
$address));
}
/**
* Extracts file argument either from file parameter or PATH_INFO
*
* @param string $scriptname name of the calling script
* @return string file path (only safe characters)
*/
function get_file_argument($scriptname) {
global $_SERVER;
$relativepath = FALSE;
// first try normal parameter (compatible method == no relative links!)
$relativepath = optional_param('file', FALSE, PARAM_PATH);
if ($relativepath === '/testslasharguments') {
echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
die;
}
// then try extract file from PATH_INFO (slasharguments method)
if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
$path_info = $_SERVER['PATH_INFO'];
// check that PATH_INFO works == must not contain the script name
if (!strpos($path_info, $scriptname)) {
$relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
if ($relativepath === '/testslasharguments') {
echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
die;
}
}
}
// now if both fail try the old way
// (for compatibility with misconfigured or older buggy php implementations)
if (!$relativepath) {
$arr = explode($scriptname, me());
if (!empty($arr[1])) {
$path_info = strip_querystring($arr[1]);
$relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
if ($relativepath === '/testslasharguments') {
echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
die;
}
}
}
return $relativepath;
}
/**
* Searches the current environment variables for some slash arguments
*
* @param string $file ?
* @todo Finish documenting this function
*/
function get_slash_arguments($file='file.php') {
if (!$string = me()) {
return false;
}
$pathinfo = explode($file, $string);
if (!empty($pathinfo[1])) {
return addslashes($pathinfo[1]);
} else {
return false;
}
}
/**
* Extracts arguments from "/foo/bar/something"
* eg http://mysite.com/script.php/foo/bar/something
*
* @param string $string ?
* @param int $i ?
* @return array|string
* @todo Finish documenting this function
*/
function parse_slash_arguments($string, $i=0) {
if (detect_munged_arguments($string)) {
return false;
}
$args = explode('/', $string);
if ($i) { // return just the required argument
return $args[$i];
} else { // return the whole array
array_shift($args); // get rid of the empty first one
return $args;
}
}
/**
* Just returns an array of text formats suitable for a popup menu
*
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_MARKDOWN
* @return array
*/
function format_text_menu() {
return array (FORMAT_MOODLE => get_string('formattext'),
FORMAT_HTML => get_string('formathtml'),
FORMAT_PLAIN => get_string('formatplain'),
FORMAT_MARKDOWN => get_string('formatmarkdown'));
}
/**
* Given text in a variety of format codings, this function returns
* the text as safe HTML.
*
* This function should mainly be used for long strings like posts,
* answers, glossary items etc. For short strings @see format_string().
*
* @uses $CFG
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_WIKI
* @uses FORMAT_MARKDOWN
* @param string $text The text to be formatted. This is raw text originally from user input.
* @param int $format Identifier of the text format to be used
* (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
* @param array $options ?
* @param int $courseid ?
* @return string
* @todo Finish documenting this function
*/
function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
global $CFG, $COURSE;
static $croncache = array();
if ($text === '') {
return ''; // no need to do any filters and cleaning
}
if (!isset($options->trusttext)) {
$options->trusttext = false;
}
if (!isset($options->noclean)) {
$options->noclean=false;
}
if (!isset($options->nocache)) {
$options->nocache=false;
}
if (!isset($options->smiley)) {
$options->smiley=true;
}
if (!isset($options->filter)) {
$options->filter=true;
}
if (!isset($options->para)) {
$options->para=true;
}
if (!isset($options->newlines)) {
$options->newlines=true;
}
if (empty($courseid)) {
$courseid = $COURSE->id;
}
if (!empty($CFG->cachetext) and empty($options->nocache)) {
$time = time() - $CFG->cachetext;
$md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
if (defined('FULLME') and FULLME == 'cron') {
if (isset($croncache[$md5key])) {
return $croncache[$md5key];
}
}
if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
if ($oldcacheitem->timemodified >= $time) {
if (defined('FULLME') and FULLME == 'cron') {
if (count($croncache) > 150) {
reset($croncache);
$key = key($croncache);
unset($croncache[$key]);
}
$croncache[$md5key] = $oldcacheitem->formattedtext;
}
return $oldcacheitem->formattedtext;
}
}
}
// trusttext overrides the noclean option!
if ($options->trusttext) {
if (trusttext_present($text)) {
$text = trusttext_strip($text);
if (!empty($CFG->enabletrusttext)) {
$options->noclean = true;
} else {
$options->noclean = false;
}
} else {
$options->noclean = false;
}
} else if (!debugging('', DEBUG_DEVELOPER)) {
// strip any forgotten trusttext in non-developer mode
// do not forget to disable text cache when debugging trusttext!!
$text = trusttext_strip($text);
}
$CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
switch ($format) {
case FORMAT_HTML:
if ($options->smiley) {
replace_smilies($text);
}
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
if ($options->filter) {
$text = filter_text($text, $courseid);
}
break;
case FORMAT_PLAIN:
$text = s($text); // cleans dangerous JS
$text = rebuildnolinktag($text);
$text = str_replace(' ', ' ', $text);
$text = nl2br($text);
break;
case FORMAT_WIKI:
// this format is deprecated
$text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
this message as all texts should have been converted to Markdown format instead.
Please post a bug report to http://moodle.org/bugs with information about where you
saw this message.</p>'.s($text);
break;
case FORMAT_MARKDOWN:
$text = markdown_to_html($text);
if ($options->smiley) {
replace_smilies($text);
}
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
if ($options->filter) {
$text = filter_text($text, $courseid);
}
break;
default: // FORMAT_MOODLE or anything else
$text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
if (!$options->noclean) {
$text = clean_text($text, FORMAT_HTML);
}
if ($options->filter) {
$text = filter_text($text, $courseid);
}
break;
}
if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
if (defined('FULLME') and FULLME == 'cron') {
// special static cron cache - no need to store it in db if its not already there
if (count($croncache) > 150) {
reset($croncache);
$key = key($croncache);
unset($croncache[$key]);
}
$croncache[$md5key] = $text;
return $text;
}
$newcacheitem = new object();
$newcacheitem->md5key = $md5key;
$newcacheitem->formattedtext = addslashes($text);
$newcacheitem->timemodified = time();
if ($oldcacheitem) { // See bug 4677 for discussion
$newcacheitem->id = $oldcacheitem->id;
@update_record('cache_text', $newcacheitem); // Update existing record in the cache table
// It's unlikely that the cron cache cleaner could have
// deleted this entry in the meantime, as it allows
// some extra time to cover these cases.
} else {
@insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
// Again, it's possible that another user has caused this
// record to be created already in the time that it took
// to traverse this function. That's OK too, as the
// call above handles duplicate entries, and eventually
// the cron cleaner will delete them.
}
}
return $text;
}
/** Converts the text format from the value to the 'internal'
* name or vice versa. $key can either be the value or the name
* and you get the other back.
*
* @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
* @return mixed as above but the other way around!
*/
function text_format_name( $key ) {
$lookup = array();
$lookup[FORMAT_MOODLE] = 'moodle';
$lookup[FORMAT_HTML] = 'html';
$lookup[FORMAT_PLAIN] = 'plain';
$lookup[FORMAT_MARKDOWN] = 'markdown';
$value = "error";
if (!is_numeric($key)) {
$key = strtolower( $key );
$value = array_search( $key, $lookup );
}
else {
if (isset( $lookup[$key] )) {
$value = $lookup[ $key ];
}
}
return $value;
}
/**
* Resets all data related to filters, called during upgrade or when filter settings change.
* @return void
*/
function reset_text_filters_cache() {
global $CFG;
delete_records('cache_text');
$purifdir = $CFG->dataroot.'/cache/htmlpurifier';
remove_dir($purifdir, true);
}
/** Given a simple string, this function returns the string
* processed by enabled string filters if $CFG->filterall is enabled
*
* This function should be used to print short strings (non html) that
* need filter processing e.g. activity titles, post subjects,
* glossary concepts.
*
* @param string $string The string to be filtered.
* @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
* @param int $courseid Current course as filters can, potentially, use it
* @return string
*/
function format_string ($string, $striplinks=true, $courseid=NULL ) {
global $CFG, $COURSE;
//We'll use a in-memory cache here to speed up repeated strings
static $strcache = false;
if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
$strcache = array();
}
//init course id
if (empty($courseid)) {
$courseid = $COURSE->id;
}
//Calculate md5
$md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
//Fetch from cache if possible
if (isset($strcache[$md5])) {
return $strcache[$md5];
}
// First replace all ampersands not followed by html entity code
$string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
if (!empty($CFG->filterall)) {
$string = filter_string($string, $courseid);
}
// If the site requires it, strip ALL tags from this string
if (!empty($CFG->formatstringstriptags)) {
$string = strip_tags($string);
} else {
// Otherwise strip just links if that is required (default)
if ($striplinks) { //strip links in string
$string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
}
$string = clean_text($string);
}
//Store to cache
$strcache[$md5] = $string;
return $string;
}
/**
* Given text in a variety of format codings, this function returns
* the text as plain text suitable for plain email.
*
* @uses FORMAT_MOODLE
* @uses FORMAT_HTML
* @uses FORMAT_PLAIN
* @uses FORMAT_WIKI
* @uses FORMAT_MARKDOWN
* @param string $text The text to be formatted. This is raw text originally from user input.
* @param int $format Identifier of the text format to be used
* (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
* @return string
*/
function format_text_email($text, $format) {
switch ($format) {
case FORMAT_PLAIN:
return $text;
break;
case FORMAT_WIKI:
$text = wiki_to_html($text);
/// This expression turns links into something nice in a text format. (Russell Jungwirth)
/// From: http://php.net/manual/en/function.eregi-replace.php and simplified
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
case FORMAT_HTML:
return html_to_text($text);
break;
case FORMAT_MOODLE:
case FORMAT_MARKDOWN:
default:
$text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
break;
}
}
/**
* Given some text in HTML format, this function will pass it
* through any filters that have been defined in $CFG->textfilterx
* The variable defines a filepath to a file containing the
* filter function. The file must contain a variable called
* $textfilter_function which contains the name of the function
* with $courseid and $text parameters
*
* @param string $text The text to be passed through format filters
* @param int $courseid ?
* @return string
* @todo Finish documenting this function
*/
function filter_text($text, $courseid=NULL) {
global $CFG, $COURSE;
if (empty($courseid)) {
$courseid = $COURSE->id; // (copied from format_text)
}
if (!empty($CFG->textfilters)) {
require_once($CFG->libdir.'/filterlib.php');
$textfilters = explode(',', $CFG->textfilters);
foreach ($textfilters as $textfilter) {
if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
$functionname = basename($textfilter).'_filter';
if (function_exists($functionname)) {
$text = $functionname($courseid, $text);
}
}
}
}
/// <nolink> tags removed for XHTML compatibility
$text = str_replace('<nolink>', '', $text);
$text = str_replace('</nolink>', '', $text);
return $text;
}
/**
* Given a string (short text) in HTML format, this function will pass it
* through any filters that have been defined in $CFG->stringfilters
* The variable defines a filepath to a file containing the
* filter function. The file must contain a variable called
* $textfilter_function which contains the name of the function
* with $courseid and $text parameters
*
* @param string $string The text to be passed through format filters
* @param int $courseid The id of a course
* @return string
*/
function filter_string($string, $courseid=NULL) {
global $CFG, $COURSE;
if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
return $string;
}
if (empty($courseid)) {
$courseid = $COURSE->id;
}
require_once($CFG->libdir.'/filterlib.php');
if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
if (empty($CFG->stringfilters)) { // but it's blank, so finish now
return $string;
}
$stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
} else { // Otherwise try to derive a list from textfilters
if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
$stringfilters = array('filter/multilang'); // Let's use just that
$CFG->stringfilters = 'filter/multilang'; // Save it for next time through
} else {
$CFG->stringfilters = ''; // Save the result and return
return $string;
}
}
foreach ($stringfilters as $stringfilter) {
if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
$functionname = basename($stringfilter).'_filter';
if (function_exists($functionname)) {
$string = $functionname($courseid, $string);
}
}
}
/// <nolink> tags removed for XHTML compatibility
$string = str_replace('<nolink>', '', $string);
$string = str_replace('</nolink>', '', $string);
return $string;
}
/**
* Is the text marked as trusted?
*
* @param string $text text to be searched for TRUSTTEXT marker
* @return boolean
*/
function trusttext_present($text) {
if (strpos($text, TRUSTTEXT) !== FALSE) {
return true;
} else {
return false;
}
}
/**
* This funtion MUST be called before the cleaning or any other
* function that modifies the data! We do not know the origin of trusttext
* in database, if it gets there in tweaked form we must not convert it
* to supported form!!!
*
* Please be carefull not to use stripslashes on data from database
* or twice stripslashes when processing data recieved from user.
*
* @param string $text text that may contain TRUSTTEXT marker
* @return text without any TRUSTTEXT marker
*/
function trusttext_strip($text) {
global $CFG;
while (true) { //removing nested TRUSTTEXT
$orig = $text;
$text = str_replace(TRUSTTEXT, '', $text);
if (strcmp($orig, $text) === 0) {
return $text;
}
}
}
/**
* Mark text as trusted, such text may contain any HTML tags because the
* normal text cleaning will be bypassed.
* Please make sure that the text comes from trusted user before storing
* it into database!
*/
function trusttext_mark($text) {
global $CFG;
if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
return TRUSTTEXT.$text;
} else {
return $text;
}
}
function trusttext_after_edit(&$text, $context) {
if (has_capability('moodle/site:trustcontent', $context)) {
$text = trusttext_strip($text);
$text = trusttext_mark($text);
} else {
$text = trusttext_strip($text);
}
}
function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
global $CFG;
$options = new object();
$options->smiley = false;
$options->filter = false;
if (!empty($CFG->enabletrusttext)
and has_capability('moodle/site:trustcontent', $context)
and trusttext_present($text)) {
$options->noclean = true;
} else {
$options->noclean = false;
}
$text = trusttext_strip($text);
if ($usehtmleditor) {
$text = format_text($text, $format, $options);
$format = FORMAT_HTML;
} else if (!$options->noclean){
$text = clean_text($text, $format);
}
}
/**
* Given raw text (eg typed in by a user), this function cleans it up
* and removes any nasty tags that could mess up Moodle pages.
*
* @uses FORMAT_MOODLE
* @uses FORMAT_PLAIN
* @uses ALLOWED_TAGS
* @param string $text The text to be cleaned
* @param int $format Identifier of the text format to be used
* (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
* @return string The cleaned up text
*/
function clean_text($text, $format=FORMAT_MOODLE) {
global $ALLOWED_TAGS, $CFG;
if (empty($text) or is_numeric($text)) {
return (string)$text;
}
switch ($format) {
case FORMAT_PLAIN:
return $text;
default:
if (!empty($CFG->enablehtmlpurifier)) {
//this is PHP5 only, the lib/setup.php contains a disabler for PHP4
$text = purify_html($text);
} else {
/// Fix non standard entity notations
$text = preg_replace('/�*([0-9]+);?/', "&#\\1;", $text);
$text = preg_replace('/�*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
/// Remove tags that are not allowed
$text = strip_tags($text, $ALLOWED_TAGS);
/// Clean up embedded scripts and , using kses
$text = cleanAttributes($text);
/// Again remove tags that are not allowed
$text = strip_tags($text, $ALLOWED_TAGS);
}
/// Remove potential script events - some extra protection for undiscovered bugs in our code
$text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
$text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
return $text;
}
}
/**
* KSES replacement cleaning function - uses HTML Purifier.
*
* @global object
* @param string $text The (X)HTML string to purify
*/
function purify_html($text) {
global $CFG;
// this can not be done only once because we sometimes need to reset the cache
$cachedir = $CFG->dataroot.'/cache/htmlpurifier';
check_dir_exists($cachedir);
static $purifier = false;
if ($purifier === false) {
require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.DefinitionID', 'moodlehtml');
$config->set('HTML.DefinitionRev', 1);
$config->set('Cache.SerializerPath', $cachedir);
//$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream
$config->set('Core.NormalizeNewlines', false);
$config->set('Core.ConvertDocumentToFragment', true);
$config->set('Core.Encoding', 'UTF-8');
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
$config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true));
$config->set('Attr.AllowedFrameTargets', array('_blank'));
if (!empty($CFG->allowobjectembed)) {
$config->set('HTML.SafeObject', true);
$config->set('Output.FlashCompat', true);
$config->set('HTML.SafeEmbed', true);
}
$def = $config->getHTMLDefinition(true);
$def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
$def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
$def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
$def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute
$def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
$purifier = new HTMLPurifier($config);
}
$multilang = (strpos($text, 'class="multilang"') !== false);
if ($multilang) {
$text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
}
$text = $purifier->purify($text);
if ($multilang) {
$text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
}
return $text;
}
/**
* This function takes a string and examines it for HTML tags.
* If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
* which checks for attributes and filters them for malicious content
* 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
*
* @param string $str The string to be examined for html tags
* @return string
*/
function cleanAttributes($str){
$result = preg_replace_callback(
'%(<[^>]*(>|$)|>)%m', #search for html tags
"cleanAttributes2",
$str
);
return $result;
}
/**
* This function takes a string with an html tag and strips out any unallowed
* protocols e.g. javascript:
* It calls ancillary functions in kses which are prefixed by kses
* 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
*
* @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
* element the html to be cleared
* @return string
*/
function cleanAttributes2($htmlArray){
global $CFG, $ALLOWED_PROTOCOLS;
require_once($CFG->libdir .'/kses.php');
$htmlTag = $htmlArray[1];
if (substr($htmlTag, 0, 1) != '<') {
return '>'; //a single character ">" detected
}
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
return ''; // It's seriously malformed
}
$slash = trim($matches[1]); //trailing xhtml slash
$elem = $matches[2]; //the element name
$attrlist = $matches[3]; // the list of attributes as a string
$attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
$attStr = '';
foreach ($attrArray as $arreach) {
$arreach['name'] = strtolower($arreach['name']);
if ($arreach['name'] == 'style') {
$value = $arreach['value'];
while (true) {
$prevvalue = $value;
$value = kses_no_null($value);
$value = preg_replace("/\/\*.*\*\//Us", '', $value);
$value = kses_decode_entities($value);
$value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
$value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
if ($value === $prevvalue) {
$arreach['value'] = $value;
break;
}
}
$arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
$arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
$arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
$arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
} else if ($arreach['name'] == 'href') {
//Adobe Acrobat Reader XSS protection
$arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
}
$attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
}
$xhtml_slash = '';
if (preg_match('%/\s*$%', $attrlist)) {
$xhtml_slash = ' /';
}
return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
}
/**
* Replaces all known smileys in the text with image equivalents
*
* @uses $CFG
* @param string $text Passed by reference. The string to search for smily strings.
* @return string
*/
function replace_smilies(&$text) {
global $CFG;
if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
return;
}
$lang = current_language();
$emoticonstring = $CFG->emoticons;
static $e = array();
static $img = array();
static $emoticons = null;
if (is_null($emoticons)) {
$emoticons = array();
if ($emoticonstring) {
$items = explode('{;}', $CFG->emoticons);
foreach ($items as $item) {
$item = explode('{:}', $item);
$emoticons[$item[0]] = $item[1];
}
}
}
if (empty($img[$lang])) { /// After the first time this is not run again
$e[$lang] = array();
$img[$lang] = array();
foreach ($emoticons as $emoticon => $image){
$alttext = get_string($image, 'pix');
$alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
$e[$lang][] = $emoticon;
$img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
}
}
// Exclude from transformations all the code inside <script> tags
// Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
// Based on code from glossary fiter by Williams Castillo.
// - Eloy
// Detect all the <script> zones to take out
$excludes = array();
preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
// Take out all the <script> zones from text
foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
$excludes['<+'.$key.'+>'] = $value;
}
if ($excludes) {
$text = str_replace($excludes,array_keys($excludes),$text);
}
/// this is the meat of the code - this is run every time
$text = str_replace($e[$lang], $img[$lang], $text);
// Recover all the <script> zones to text
if ($excludes) {
$text = str_replace(array_keys($excludes),$excludes,$text);
}
}
/**
* Given plain text, makes it into HTML as nicely as possible.
* May contain HTML tags already
*
* @uses $CFG
* @param string $text The string to convert.
* @param boolean $smiley Convert any smiley characters to smiley images?
* @param boolean $para If true then the returned string will be wrapped in paragraph tags
* @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
* @return string
*/
function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
///
global $CFG;
/// Remove any whitespace that may be between HTML tags
$text = eregi_replace(">([[:space:]]+)<", "><", $text);
/// Remove any returns that precede or follow HTML tags
$text = eregi_replace("([\n\r])<", " <", $text);
$text = eregi_replace(">([\n\r])", "> ", $text);
convert_urls_into_links($text);
/// Make returns into HTML newlines.
if ($newlines) {
$text = nl2br($text);
}
/// Turn smileys into images.
if ($smiley) {
replace_smilies($text);
}
/// Wrap the whole thing in a paragraph tag if required
if ($para) {
return '<p>'.$text.'</p>';
} else {
return $text;
}
}
/**
* Given Markdown formatted text, make it into XHTML using external function
*
* @uses $CFG
* @param string $text The markdown formatted text to be converted.
* @return string Converted text
*/
function markdown_to_html($text) {
global $CFG;
require_once($CFG->libdir .'/markdown.php');
return Markdown($text);
}
/**
* Given HTML text, make it into plain text using external function
*
* @uses $CFG
* @param string $html The text to be converted.
* @return string
*/
function html_to_text($html) {
global $CFG;
require_once($CFG->libdir .'/html2text.php');
$h2t = new html2text($html);
$result = $h2t->get_text();
return $result;
}
/**
* Given some text this function converts any URLs it finds into HTML links
*
* @param string $text Passed in by reference. The string to be searched for urls.
*/
function convert_urls_into_links(&$text) {
//I've added img tags to this list of tags to ignore.
//See MDL-21168 for more info. A better way to ignore tags whether or not
//they are escaped partially or completely would be desirable. For example:
//<a href="blah">
//<a href="blah">
//<a href="blah">
$filterignoretagsopen = array('<a\s[^>]+?>');
$filterignoretagsclose = array('</a>');
filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
// Check if we support unicode modifiers in regular expressions. Cache it.
// TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
// chars are going to arrive to URLs officially really soon (2010?)
// Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
// Various ideas from: http://alanstorm.com/url_regex_explained
// Unicode check, negative assertion and other bits from Moodle.
static $unicoderegexp;
if (!isset($unicoderegexp)) {
$unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silenty, returning false,
}
$unicoderegexp = false;//force non use of unicode modifiers. MDL-21296
if ($unicoderegexp) { //We can use unicode modifiers
$text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
'<a href="\\1" target="_blank">\\1</a>', $text);
$text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
'<a href="http://\\1" target="_blank">\\1</a>', $text);
} else { //We cannot use unicode modifiers
$text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
'<a href="\\1" target="_blank">\\1</a>', $text);
$text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
'<a href="http://\\1" target="_blank">\\1</a>', $text);
}
if (!empty($ignoretags)) {
$ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
$text = str_replace(array_keys($ignoretags),$ignoretags,$text);
}
}
/**
* This function will highlight search words in a given string
* It cares about HTML and will not ruin links. It's best to use
* this function after performing any conversions to HTML.
*
* @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
* @param string $haystack The string (HTML) within which to highlight the search terms.
* @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
* @param string $prefix the string to put before each search term found.
* @param string $suffix the string to put after each search term found.
* @return string The highlighted HTML.
*/
function highlight($needle, $haystack, $matchcase = false,
$prefix = '<span class="highlight">', $suffix = '</span>') {
/// Quick bail-out in trivial cases.
if (empty($needle) or empty($haystack)) {
return $haystack;
}
/// Break up the search term into words, discard any -words and build a regexp.
$words = preg_split('/ +/', trim($needle));
foreach ($words as $index => $word) {
if (strpos($word, '-') === 0) {
unset($words[$index]);
} else if (strpos($word, '+') === 0) {
$words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
} else {
$words[$index] = preg_quote($word, '/');
}
}
$regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
if (!$matchcase) {
$regexp .= 'i';
}
/// Another chance to bail-out if $search was only -words
if (empty($words)) {
return $haystack;
}
/// Find all the HTML tags in the input, and store them in a placeholders array.
$placeholders = array();
$matches = array();
preg_match_all('/<[^>]*>/', $haystack, $matches);
foreach (array_unique($matches[0]) as $key => $htmltag) {
$placeholders['<|' . $key . '|>'] = $htmltag;
}
/// In $hastack, replace each HTML tag with the corresponding placeholder.
$haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
/// In the resulting string, Do the highlighting.
$haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
/// Turn the placeholders back into HTML tags.
$haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
return $haystack;
}
/**
* This function will highlight instances of $needle in $haystack
* It's faster that the above function and doesn't care about
* HTML or anything.
*
* @param string $needle The string to search for
* @param string $haystack The string to search for $needle in
* @return string
*/
function highlightfast($needle, $haystack) {
if (empty($needle) or empty($haystack)) {
return $haystack;
}
$parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
if (count($parts) === 1) {
return $haystack;
}
$pos = 0;
foreach ($parts as $key => $part) {
$parts[$key] = substr($haystack, $pos, strlen($part));
$pos += strlen($part);
$parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
$pos += strlen($needle);
}
return str_replace('<span class="highlight"></span>', '', join('', $parts));
}
/**
* Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
* Internationalisation, for print_header and backup/restorelib.
* @param $dir Default false.
* @return string Attributes.
*/
function get_html_lang($dir = false) {
$direction = '';
if ($dir) {
if (get_string('thisdirection') == 'rtl') {
$direction = ' dir="rtl"';
} else {
$direction = ' dir="ltr"';
}
}
//Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
$language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
@header('Content-Language: '.$language);
return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
}
/**
* Return the markup for the destination of the 'Skip to main content' links.
* Accessibility improvement for keyboard-only users.
* Used in course formats, /index.php and /course/index.php
* @return string HTML element.
*/
function skip_main_destination() {
return '<span id="maincontent"></span>';
}
/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
/**
* Print a standard header
*
* @uses $USER
* @uses $CFG
* @uses $SESSION
* @param string $title Appears at the top of the window
* @param string $heading Appears at the top of the page
* @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
* @param string $focus Indicates form element to get cursor focus on load eg inputform.password
* @param string $meta Meta tags to be added to the header
* @param boolean $cache Should this page be cacheable?
* @param string $button HTML code for a button (usually for module editing)
* @param string $menu HTML code for a popup menu
* @param boolean $usexml use XML for this page
* @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
* @param bool $return If true, return the visible elements of the header instead of echoing them.
*/
function print_header ($title='', $heading='', $navigation='', $focus='',
$meta='', $cache=true, $button=' ', $menu='',
$usexml=false, $bodytags='', $return=false) {
global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
. "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
}
$heading = format_string($heading); // Fix for MDL-8582
/// This makes sure that the header is never repeated twice on a page
if (defined('HEADER_PRINTED')) {
debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
return;
}
define('HEADER_PRINTED', 'true');
/// Perform a browser environment check for the flash version. Should only run once per login session.
if (isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
// Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
// require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
$meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/yahoo/yahoo-min.js"></script>';
$meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/event/event-min.js"></script>';
$meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/connection/connection-min.js"></script>';
$meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/swfobject/swfobject.js"></script>';
$meta .=
"<script type=\"text/javascript\">\n".
"//<![CDATA[\n".
" var flashversion = swfobject.getFlashPlayerVersion();\n".
" YAHOO.util.Connect.asyncRequest('GET','".$CFG->httpswwwroot."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
"//]]>\n".
"</script>";
}
/// Add the required stylesheets
$stylesheetshtml = '';
foreach ($CFG->stylesheets as $stylesheet) {
$stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
}
$meta = $stylesheetshtml.$meta;
/// Add the meta page from the themes if any were requested
$metapage = '';
if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
ob_start();
include_once($CFG->dirroot.'/theme/standard/meta.php');
$metapage .= ob_get_contents();
ob_end_clean();
}
if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
ob_start();
include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
$metapage .= ob_get_contents();
ob_end_clean();
}
}
if (!isset($THEME->metainclude) || $THEME->metainclude) {
if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
ob_start();
include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
$metapage .= ob_get_contents();
ob_end_clean();
}
}
$meta = $meta."\n".$metapage;
$meta .= "\n".require_js('',1);
/// Set up some navigation variables
if (is_newnav($navigation)){
$home = false;
} else {
if ($navigation == 'home') {
$home = true;
$navigation = '';
} else {
$home = false;
}
}
/// This is another ugly hack to make navigation elements available to print_footer later
$THEME->title = $title;
$THEME->heading = $heading;
$THEME->navigation = $navigation;
$THEME->button = $button;
$THEME->menu = $menu;
$navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
if ($button == '') {
$button = ' ';
}
if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
$button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
if(!empty($title)) {
$title .= ' - ';
}
$title .= get_string('maintenancemode', 'admin');
}
if (!$menu and $navigation) {
if (empty($CFG->loginhttps)) {
$wwwroot = $CFG->wwwroot;
} else {
$wwwroot = str_replace('http:','https:',$CFG->wwwroot);
}
$menu = user_login_string($COURSE);
}
if (isset($SESSION->justloggedin)) {
unset($SESSION->justloggedin);
if (!empty($CFG->displayloginfailures)) {
if (!empty($USER->username) and $USER->username != 'guest') {
if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
$menu .= ' <font size="1">';
if (empty($count->accounts)) {
$menu .= get_string('failedloginattempts', '', $count);
} else {
$menu .= get_string('failedloginattemptsall', '', $count);
}
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
$menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
'?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
}
$menu .= '</font>';
}
}
}
}
$meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
"\n" . $meta . "\n";
if (!$usexml) {
@header('Content-Type: text/html; charset=utf-8');
}
@header('Content-Script-Type: text/javascript');
@header('Content-Style-Type: text/css');
//Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
$direction = get_html_lang($dir=true);
if ($cache) { // Allow caching on "back" (but not on normal clicks)
@header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
@header('Pragma: no-cache');
@header('Expires: ');
} else { // Do everything we can to always prevent clients and proxies caching
@header('Cache-Control: no-store, no-cache, must-revalidate');
@header('Cache-Control: post-check=0, pre-check=0', false);
@header('Pragma: no-cache');
@header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
@header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
$meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
$meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
}
@header('Accept-Ranges: none');
$currentlanguage = current_language();
if (empty($usexml)) {
$direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
} else {
$mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
if(!$mathplayer) {
header('Content-Type: application/xhtml+xml');
}
echo '<?xml version="1.0" ?>'."\n";
if (!empty($CFG->xml_stylesheets)) {
$stylesheets = explode(';', $CFG->xml_stylesheets);
foreach ($stylesheets as $stylesheet) {
echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
}
}
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
if (!empty($CFG->xml_doctype_extra)) {
echo ' plus '. $CFG->xml_doctype_extra;
}
echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
$direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
xmlns:xlink=\"http://www.w3.org/1999/xlink\"
$direction";
if($mathplayer) {
$meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
$meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
$meta .= '</object>'."\n";
$meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
}
}
// Clean up the title
$title = format_string($title); // fix for MDL-8582
$title = str_replace('"', '"', $title);
// Create class and id for this page
page_id_and_class($pageid, $pageclass);
$pageclass .= ' course-'.$COURSE->id;
if (!isloggedin()) {
$pageclass .= ' notloggedin';
}
if (!empty($USER->editing)) {
$pageclass .= ' editing';
}
if (!empty($CFG->blocksdrag)) {
$pageclass .= ' drag';
}
$pageclass .= ' dir-'.get_string('thisdirection');
$pageclass .= ' lang-'.s($currentlanguage);
$bodytags .= ' class="'.s($pageclass).'" id="'.s($pageid).'"';
ob_start();
include($CFG->header);
$output = ob_get_contents();
ob_end_clean();
// container debugging info
$THEME->open_header_containers = open_containers();
// Skip to main content, see skip_main_destination().
if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
$skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
}
$output = $matches[1]."\n". $skiplink .$matches[2];
}
$output = force_strict_header($output);
if (!empty($CFG->messaging)) {
$output .= message_popup_window();
}
// Add in any extra JavaScript libraries that occurred during the header
$output .= require_js('', 2);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Used to include JavaScript libraries.
*
* When the $lib parameter is given, the function will ensure that the
* named library is loaded onto the page - either in the HTML <head>,
* just after the header, or at an arbitrary later point in the page,
* depending on where this function is called.
*
* Libraries will not be included more than once, so this works like
* require_once in PHP.
*
* There are two special-case calls to this function which are both used only
* by weblib print_header:
* $extracthtml = 1: this is used before printing the header.
* It returns the script tag code that should go inside the <head>.
* $extracthtml = 2: this is used after printing the header and handles any
* require_js calls that occurred within the header itself.
*
* @param mixed $lib - string or array of strings
* string(s) should be the shortname for the library or the
* full path to the library file.
* @param int $extracthtml Do not set this parameter usually (leave 0), only
* weblib should set this to 1 or 2 in print_header function.
* @return mixed No return value, except when using $extracthtml it returns the html code.
*/
function require_js($lib,$extracthtml=0) {
global $CFG;
static $loadlibs = array();
static $state = REQUIREJS_BEFOREHEADER;
static $latecode = '';
if (!empty($lib)) {
// Add the lib to the list of libs to be loaded, if it isn't already
// in the list.
if (is_array($lib)) {
foreach($lib as $singlelib) {
require_js($singlelib);
}
} else {
$libpath = ajax_get_lib($lib);
if (array_search($libpath, $loadlibs) === false) {
$loadlibs[] = $libpath;
// For state other than 0 we need to take action as well as just
// adding it to loadlibs
if($state != REQUIREJS_BEFOREHEADER) {
// Get the script statement for this library
$scriptstatement=get_require_js_code(array($libpath));
if($state == REQUIREJS_AFTERHEADER) {
// After the header, print it immediately
print $scriptstatement;
} else {
// Haven't finished the header yet. Add it after the
// header
$latecode .= $scriptstatement;
}
}
}
}
} else if($extracthtml==1) {
if($state !== REQUIREJS_BEFOREHEADER) {
debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
} else {
$state = REQUIREJS_INHEADER;
}
return get_require_js_code($loadlibs);
} else if($extracthtml==2) {
if($state !== REQUIREJS_INHEADER) {
debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
return '';
} else {
$state = REQUIREJS_AFTERHEADER;
return $latecode;
}
} else {
debugging('Unexpected value for $extracthtml');
}
}
/**
* Should not be called directly - use require_js. This function obtains the code
* (script tags) needed to include JavaScript libraries.
* @param array $loadlibs Array of library files to include
* @return string HTML code to include them
*/
function get_require_js_code($loadlibs) {
global $CFG;
// Return the html needed to load the JavaScript files defined in
// our list of libs to be loaded.
$output = '';
foreach ($loadlibs as $loadlib) {
$output .= '<script type="text/javascript" ';
$output .= " src=\"$loadlib\"></script>\n";
if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
// Special case, we need the CSS too.
$output .= '<link type="text/css" rel="stylesheet" ';
$output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
}
}
return $output;
}
/**
* Debugging aid: serve page as 'application/xhtml+xml' where possible,
* and substitute the XHTML strict document type.
* Note, requires the 'xmlns' fix in function print_header above.
* See: http://tracker.moodle.org/browse/MDL-7883
* TODO:
*/
function force_strict_header($output) {
global $CFG;
$strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
$xsl = '/lib/xhtml.xsl';
if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
$ctype = 'Content-Type: ';
$prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
if (isset($_SERVER['HTTP_ACCEPT'])
&& false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
//|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
// Firefox et al.
$ctype .= 'application/xhtml+xml';
$prolog .= "<!--\n DEBUG: $ctype \n-->\n";
} else if (file_exists($CFG->dirroot.$xsl)
&& preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
// XSL hack for IE 5+ on Windows.
//$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
$www_xsl = $CFG->wwwroot .$xsl;
$ctype .= 'application/xml';
$prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
$prolog .= "<!--\n DEBUG: $ctype \n-->\n";
} else {
//ELSE: Mac/IE, old/non-XML browsers.
$ctype .= 'text/html';
$prolog = '';
}
@header($ctype.'; charset=utf-8');
$output = $prolog . $output;
// Test parser error-handling.
if (isset($_GET['error'])) {
$output .= "__ TEST: XML well-formed error < __\n";
}
}
$output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
return $output;
}
/**
* This version of print_header is simpler because the course name does not have to be
* provided explicitly in the strings. It can be used on the site page as in courses
* Eventually all print_header could be replaced by print_header_simple
*
* @param string $title Appears at the top of the window
* @param string $heading Appears at the top of the page
* @param string $navigation Premade navigation string (for use as breadcrumbs links)
* @param string $focus Indicates form element to get cursor focus on load eg inputform.password
* @param string $meta Meta tags to be added to the header
* @param boolean $cache Should this page be cacheable?
* @param string $button HTML code for a button (usually for module editing)
* @param string $menu HTML code for a popup menu
* @param boolean $usexml use XML for this page
* @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
* @param bool $return If true, return the visible elements of the header instead of echoing them.
*/
function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
$cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
global $COURSE, $CFG;
// if we have no navigation specified, build it
if( empty($navigation) ){
$navigation = build_navigation('');
}
// If old style nav prepend course short name otherwise leave $navigation object alone
if (!is_newnav($navigation)) {
if ($COURSE->id != SITEID) {
$shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
$navigation = $shortname.' '.$navigation;
}
}
$output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
$cache, $button, $menu, $usexml, $bodytags, true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Can provide a course object to make the footer contain a link to
* to the course home page, otherwise the link will go to the site home
* @uses $USER
* @param mixed $course course object, used for course link button or
* 'none' means no user link, only docs link
* 'empty' means nothing printed in footer
* 'home' special frontpage footer
* @param object $usercourse course used in user link
* @param boolean $return output as string
* @return mixed string or void
*/
function print_footer($course=NULL, $usercourse=NULL, $return=false) {
global $USER, $CFG, $THEME, $COURSE;
if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
admin_externalpage_print_footer();
return;
}
/// Course links or special footer
if ($course) {
if ($course === 'empty') {
// special hack - sometimes we do not want even the docs link in footer
$output = '';
if (!empty($THEME->open_header_containers)) {
for ($i=0; $i<$THEME->open_header_containers; $i++) {
$output .= print_container_end_all(); // containers opened from header
}
} else {
//1.8 theme compatibility
$output .= "\n</div>"; // content div
}
$output .= "\n</div>\n</body>\n</html>"; // close page div started in header
if ($return) {
return $output;
} else {
echo $output;
return;
}
} else if ($course === 'none') { // Don't print any links etc
$homelink = '';
$loggedinas = '';
$home = false;
} else if ($course === 'home') { // special case for site home page - please do not remove
$course = get_site();
$homelink = '<div class="sitelink">'.
'<a title="Moodle" href="http://moodle.org/">'.
'<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
$home = true;
} else {
$homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
'/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
$home = false;
}
} else {
$course = get_site(); // Set course as site course by default
$homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
$home = false;
}
/// Set up some other navigation links (passed from print_header by ugly hack)
$menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
$title = isset($THEME->title) ? $THEME->title : '';
$button = isset($THEME->button) ? $THEME->button : '';
$heading = isset($THEME->heading) ? $THEME->heading : '';
$navigation = isset($THEME->navigation) ? $THEME->navigation : '';
$navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
/// Set the user link if necessary
if (!$usercourse and is_object($course)) {
$usercourse = $course;
}
if (!isset($loggedinas)) {
$loggedinas = user_login_string($usercourse, $USER);
}
if ($loggedinas == $menu) {
$menu = '';
}
/// there should be exactly the same number of open containers as after the header
if ($THEME->open_header_containers != open_containers()) {
debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
}
/// Provide some performance info if required
$performanceinfo = '';
if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
$perf = get_performance_info();
if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
error_log("PERF: " . $perf['txt']);
}
if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
$performanceinfo = $perf['html'];
}
}
/// Include the actual footer file
ob_start();
include($CFG->footer);
$output = ob_get_contents();
ob_end_clean();
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Returns the name of the current theme
*
* @uses $CFG
* @uses $USER
* @uses $SESSION
* @uses $COURSE
* @uses $FULLME
* @return string
*/
function current_theme() {
global $CFG, $USER, $SESSION, $COURSE, $FULLME;
if (empty($CFG->themeorder)) {
$themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
} else {
$themeorder = $CFG->themeorder;
}
if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
require_once($CFG->dirroot.'/mnet/peer.php');
$mnet_peer = new mnet_peer();
$mnet_peer->set_id($USER->mnethostid);
}
$theme = '';
foreach ($themeorder as $themetype) {
if (!empty($theme)) continue;
switch ($themetype) {
case 'page': // Page theme is for special page-only themes set by code
if (!empty($CFG->pagetheme)) {
$theme = $CFG->pagetheme;
}
break;
case 'course':
if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
$theme = $COURSE->theme;
}
break;
case 'category':
if (!empty($CFG->allowcategorythemes)) {
/// Nasty hack to check if we're in a category page
if (stripos($FULLME, 'course/category.php') !== false) {
global $id;
if (!empty($id)) {
$theme = current_category_theme($id);
}
/// Otherwise check if we're in a course that has a category theme set
} else if (!empty($COURSE->category)) {
$theme = current_category_theme($COURSE->category);
}
}
break;
case 'session':
if (!empty($SESSION->theme)) {
$theme = $SESSION->theme;
}
break;
case 'user':
if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
$theme = $mnet_peer->theme;
} else {
$theme = $USER->theme;
}
}
break;
case 'site':
if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
$theme = $mnet_peer->theme;
} else {
$theme = $CFG->theme;
}
break;
default:
/// do nothing
}
}
/// A final check in case 'site' was not included in $CFG->themeorder
if (empty($theme)) {
$theme = $CFG->theme;
}
return $theme;
}
/**
* Retrieves the category theme if one exists, otherwise checks the parent categories.
* Recursive function.
*
* @uses $COURSE
* @param integer $categoryid id of the category to check
* @return string theme name
*/
function current_category_theme($categoryid=0) {
global $COURSE;
/// Use the COURSE global if the categoryid not set
if (empty($categoryid)) {
if (!empty($COURSE->category)) {
$categoryid = $COURSE->category;
} else {
return false;
}
}
/// Retrieve the current category
if ($category = get_record('course_categories', 'id', $categoryid)) {
/// Return the category theme if it exists
if (!empty($category->theme)) {
return $category->theme;
/// Otherwise try the parent category if one exists
} else if (!empty($category->parent)) {
return current_category_theme($category->parent);
}
/// Return false if we can't find the category record
} else {
return false;
}
}
/**
* This function is called by stylesheets to set up the header
* approriately as well as the current path
*
* @uses $CFG
* @param int $lastmodified ?
* @param int $lifetime ?
* @param string $thename ?
*/
function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
global $CFG, $THEME;
// Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
$lastmodified = time();
header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
header('Cache-Control: max-age='. $lifetime);
header('Pragma: ');
header('Content-type: text/css'); // Correct MIME type
$DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
if (empty($themename)) {
$themename = current_theme(); // So we have something. Normally not needed.
} else {
$themename = clean_param($themename, PARAM_SAFEDIR);
}
if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
unset($THEME);
include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
}
/// If this is the standard theme calling us, then find out what sheets we need
if ($themename == 'standard') {
if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
$THEME->sheets = $DEFAULT_SHEET_LIST;
} else if (empty($THEME->standardsheets)) { // We can stop right now!
echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
exit;
} else { // Use the provided subset only
$THEME->sheets = $THEME->standardsheets;
}
/// If we are a parent theme, then check for parent definitions
} else if (!empty($THEME->parent) && $themename == $THEME->parent) {
if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
$THEME->sheets = $DEFAULT_SHEET_LIST;
} else if (empty($THEME->parentsheets)) { // We can stop right now!
echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
exit;
} else { // Use the provided subset only
$THEME->sheets = $THEME->parentsheets;
}
}
/// Work out the last modified date for this theme
foreach ($THEME->sheets as $sheet) {
if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
$sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
if ($sheetmodified > $lastmodified) {
$lastmodified = $sheetmodified;
}
}
}
/// Get a list of all the files we want to include
$files = array();
foreach ($THEME->sheets as $sheet) {
$files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
}
if ($themename == 'standard') { // Add any standard styles included in any modules
if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
if ($mods = get_list_of_plugins('mod')) {
foreach ($mods as $mod) {
if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
$files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
}
}
}
}
if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
if ($mods = get_list_of_plugins('blocks')) {
foreach ($mods as $mod) {
if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
$files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
}
}
}
}
if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
foreach ($mods as $mod) {
if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
$files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
}
}
}
}
if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
if ($reports = get_list_of_plugins('grade/report')) {
foreach ($reports as $report) {
if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
$files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
}
}
}
}
if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
$files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
}
}
}
if ($files) {
/// Produce a list of all the files first
echo '/**************************************'."\n";
echo ' * THEME NAME: '.$themename."\n *\n";
echo ' * Files included in this sheet:'."\n *\n";
foreach ($files as $file) {
echo ' * '.$file[1]."\n";
}
echo ' **************************************/'."\n\n";
/// check if csscobstants is set
if (!empty($THEME->cssconstants)) {
require_once("$CFG->libdir/cssconstants.php");
/// Actually collect all the files in order.
$css = '';
foreach ($files as $file) {
$css .= '/***** '.$file[1].' start *****/'."\n\n";
$css .= file_get_contents($file[0].'/'.$file[1]);
$ccs .= '/***** '.$file[1].' end *****/'."\n\n";
}
/// replace css_constants with their values
echo replace_cssconstants($css);
} else {
/// Actually output all the files in order.
if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
foreach ($files as $file) {
echo '/***** '.$file[1].' start *****/'."\n\n";
@include_once($file[0].'/'.$file[1]);
echo '/***** '.$file[1].' end *****/'."\n\n";
}
} else {
foreach ($files as $file) {
echo '/* @group '.$file[1].' */'."\n\n";
if (strstr($file[1], '.css') !== FALSE) {
echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
} else {
@include_once($file[0].'/'.$file[1]);
}
echo '/* @end */'."\n\n";
}
}
}
}
return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
}
function theme_setup($theme = '', $params=NULL) {
/// Sets up global variables related to themes
global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
/// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
if (defined('HEADER_PRINTED')) {
return;
}
if (empty($theme)) {
$theme = current_theme();
}
/// If the theme doesn't exist for some reason then revert to standardwhite
if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
$CFG->theme = $theme = 'standardwhite';
}
/// Load up the theme config
$THEME = NULL; // Just to be sure
include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
/// Put together the parameters
if (!$params) {
$params = array();
}
if ($theme != $CFG->theme) {
$params[] = 'forceconfig='.$theme;
}
/// Force language too if required
if (!empty($THEME->langsheets)) {
$params[] = 'lang='.current_language();
}
/// Convert params to string
if ($params) {
$paramstring = '?'.implode('&', $params);
} else {
$paramstring = '';
}
/// Set up image paths
if(isset($CFG->smartpix) && $CFG->smartpix==1) {
if($CFG->slasharguments) { // Use this method if possible for better caching
$extra='';
} else {
$extra='?file=';
}
$CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
$CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
} else if (empty($THEME->custompix)) { // Could be set in the above file
$CFG->pixpath = $CFG->wwwroot .'/pix';
$CFG->modpixpath = $CFG->wwwroot .'/mod';
} else {
$CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
$CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
}
/// Header and footer paths
$CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
$CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
/// Define stylesheet loading order
$CFG->stylesheets = array();
if ($theme != 'standard') { /// The standard sheet is always loaded first
$CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
}
if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
$CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
}
$CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
if (!empty($HTTPSPAGEREQUIRED)) {
$CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
$CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
$CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
foreach ($CFG->stylesheets as $key => $stylesheet) {
$CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
}
}
// RTL support - only for RTL languages, add RTL CSS
if (get_string('thisdirection') == 'rtl') {
$CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
$CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
}
}
/**
* Returns text to be displayed to the user which reflects their login status
*
* @uses $CFG
* @uses $USER
* @param course $course {@link $COURSE} object containing course information
* @param user $user {@link $USER} object containing user information
* @return string
*/
function user_login_string($course=NULL, $user=NULL) {
global $USER, $CFG, $SITE;
if (empty($user) and !empty($USER->id)) {
$user = $USER;
}
if (empty($course)) {
$course = $SITE;
}
if (!empty($user->realuser)) {
if ($realuser = get_record('user', 'id', $user->realuser)) {
$fullname = fullname($realuser, true);
$realuserinfo = " [<a $CFG->frametarget
href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
}
} else {
$realuserinfo = '';
}
if (empty($CFG->loginhttps)) {
$wwwroot = $CFG->wwwroot;
} else {
$wwwroot = str_replace('http:','https:',$CFG->wwwroot);
}
if (empty($course->id)) {
// $course->id is not defined during installation
return '';
} else if (!empty($user->id)) {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$fullname = fullname($user, true);
$username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a>";
if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
$username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
}
if (isset($user->username) && $user->username == 'guest') {
$loggedinas = $realuserinfo.get_string('loggedinasguest').
" (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
} else if (!empty($user->access['rsw'][$context->path])) {
$rolename = '';
if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
$rolename = join("", role_fix_names(array($role->id=>$role->name), $context));
$rolename = ': '.format_string($rolename);
}
$loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
" (<a $CFG->frametarget
href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
} else {
$loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
" (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
}
} else {
$loggedinas = get_string('loggedinnot', 'moodle').
" (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
}
return '<div class="logininfo">'.$loggedinas.'</div>';
}
/**
* Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
* If not it applies sensible defaults.
*
* Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
* search forum block, etc. Important: these are 'silent' in a screen-reader
* (unlike > »), and must be accompanied by text.
* @uses $THEME
*/
function check_theme_arrows() {
global $THEME;
if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
// Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
// Also OK in Win 9x/2K/IE 5.x
$THEME->rarrow = '►';
$THEME->larrow = '◄';
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$uagent = '';
} else {
$uagent = $_SERVER['HTTP_USER_AGENT'];
}
if (false !== strpos($uagent, 'Opera')
|| false !== strpos($uagent, 'Mac')) {
// Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
// Not broken in Mac/IE 5, Mac/Netscape 7 (?).
$THEME->rarrow = '▶';
$THEME->larrow = '◀';
}
elseif (false !== strpos($uagent, 'Konqueror')) {
$THEME->rarrow = '→';
$THEME->larrow = '←';
}
elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
&& false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
// (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
// To be safe, non-Unicode browsers!
$THEME->rarrow = '>';
$THEME->larrow = '<';
}
/// RTL support - in RTL languages, swap r and l arrows
if (right_to_left()) {
$t = $THEME->rarrow;
$THEME->rarrow = $THEME->larrow;
$THEME->larrow = $t;
}
}
}
/**
* Return the right arrow with text ('next'), and optionally embedded in a link.
* See function above, check_theme_arrows.
* @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
* @param string $url An optional link to use in a surrounding HTML anchor.
* @param bool $accesshide True if text should be hidden (for screen readers only).
* @param string $addclass Additional class names for the link, or the arrow character.
* @return string HTML string.
*/
function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
global $THEME;
check_theme_arrows();
$arrowclass = 'arrow ';
if (! $url) {
$arrowclass .= $addclass;
}
$arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
$htmltext = '';
if ($text) {
$htmltext = $text.' ';
if ($accesshide) {
$htmltext = get_accesshide($htmltext);
}
}
if ($url) {
$class = '';
if ($addclass) {
$class =" class=\"$addclass\"";
}
return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
}
return $htmltext.$arrow;
}
/**
* Return the left arrow with text ('previous'), and optionally embedded in a link.
* See function above, check_theme_arrows.
* @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
* @param string $url An optional link to use in a surrounding HTML anchor.
* @param bool $accesshide True if text should be hidden (for screen readers only).
* @param string $addclass Additional class names for the link, or the arrow character.
* @return string HTML string.
*/
function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
global $THEME;
check_theme_arrows();
$arrowclass = 'arrow ';
if (! $url) {
$arrowclass .= $addclass;
}
$arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
$htmltext = '';
if ($text) {
$htmltext = ' '.$text;
if ($accesshide) {
$htmltext = get_accesshide($htmltext);
}
}
if ($url) {
$class = '';
if ($addclass) {
$class =" class=\"$addclass\"";
}
return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
}
return $arrow.$htmltext;
}
/**
* Return a HTML element with the class "accesshide", for accessibility.
* Please use cautiously - where possible, text should be visible!
* @param string $text Plain text.
* @param string $elem Lowercase element name, default "span".
* @param string $class Additional classes for the element.
* @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
* @return string HTML string.
*/
function get_accesshide($text, $elem='span', $class='', $attrs='') {
return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
}
/**
* Return the breadcrumb trail navigation separator.
* @return string HTML string.
*/
function get_separator() {
//Accessibility: the 'hidden' slash is preferred for screen readers.
return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
}
/**
* Prints breadcrumb trail of links, called in theme/-/header.html
*
* @uses $CFG
* @param mixed $navigation The breadcrumb navigation string to be printed
* @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
* @param boolean $return False to echo the breadcrumb string (default), true to return it.
* @return string or null, depending on $return.
*/
function print_navigation ($navigation, $separator=0, $return=false) {
global $CFG, $THEME;
$output = '';
if (0 === $separator) {
$separator = get_separator();
}
else {
$separator = '<span class="sep">'. $separator .'</span>';
}
if ($navigation) {
if (is_newnav($navigation)) {
if ($return) {
return($navigation['navlinks']);
} else {
echo $navigation['navlinks'];
return;
}
} else {
debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
}
if (!is_array($navigation)) {
$ar = explode('->', $navigation);
$navigation = array();
foreach ($ar as $a) {
if (strpos($a, '</a>') === false) {
$navigation[] = array('title' => $a, 'url' => '');
} else {
if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
$navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
}
}
}
}
if (! $site = get_site()) {
$site = new object();
$site->shortname = get_string('home');
}
//Accessibility: breadcrumb links now in a list, » replaced with a 'silent' character.
$output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
$output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
.$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
&& !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
foreach ($navigation as $navitem) {
$title = trim(strip_tags(format_string($navitem['title'], false)));
$url = $navitem['url'];
if (empty($url)) {
$output .= '<li>'."$separator $title</li>\n";
} else {
$output .= '<li>'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
.$url.'">'."$title</a>\n</li>\n";
}
}
$output .= "</ul>\n";
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* This function will build the navigation string to be used by print_header
* and others.
*
* It automatically generates the site and course level (if appropriate) links.
*
* If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
* and activityinstances (e.g. 'General Developer Forum') navigation levels.
*
* If you want to add any further navigation links after the ones this function generates,
* the pass an array of extra link arrays like this:
* array(
* array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
* array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
* )
* The normal case is to just add one further link, for example 'Editing forum' after
* 'General Developer Forum', with no link.
* To do that, you need to pass
* array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
* However, becuase this is a very common case, you can use a shortcut syntax, and just
* pass the string 'Editing forum', instead of an array as $extranavlinks.
*
* At the moment, the link types only have limited significance. Type 'activity' is
* recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
* that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
* This really needs to be documented better. In the mean time, try to be consistent, it will
* enable people to customise the navigation more in future.
*
* When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
* If you get the $cm object using the function get_coursemodule_from_instance or
* get_coursemodule_from_id (as recommended) then this will be done for you automatically.
* If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
* the $cm->module and $cm->instance fields, but this takes extra database queries, so a
* warning is printed in developer debug mode.
*
* @uses $CFG
* @uses $THEME
*
* @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
* only want one extra item with no link, you can pass a string instead. If you don't want
* any extra links, pass an empty string.
* @param mixed $cm - optionally the $cm object, if you want this function to generate the
* activity and activityinstance levels of navigation too.
*
* @return $navigation as an object so it can be differentiated from old style
* navigation strings.
*/
function build_navigation($extranavlinks, $cm = null) {
global $CFG, $COURSE;
if (is_string($extranavlinks)) {
if ($extranavlinks == '') {
$extranavlinks = array();
} else {
$extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
}
}
$navlinks = array();
//Site name
if ($site = get_site()) {
$navlinks[] = array(
'name' => format_string($site->shortname),
'link' => "$CFG->wwwroot/",
'type' => 'home');
}
// Course name, if appropriate.
if (isset($COURSE) && $COURSE->id != SITEID) {
$navlinks[] = array(
'name' => format_string($COURSE->shortname),
'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
'type' => 'course');
}
// Activity type and instance, if appropriate.
if (is_object($cm)) {
if (!isset($cm->modname)) {
debugging('The field $cm->modname should be set if you call build_navigation with '.
'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
error('Cannot get the module type in build navigation.');
}
}
if (!isset($cm->name)) {
debugging('The field $cm->name should be set if you call build_navigation with '.
'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
error('Cannot get the module name in build navigation.');
}
}
$navlinks[] = array(
'name' => get_string('modulenameplural', $cm->modname),
'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
'type' => 'activity');
$navlinks[] = array(
'name' => format_string($cm->name),
'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
'type' => 'activityinstance');
}
//Merge in extra navigation links
$navlinks = array_merge($navlinks, $extranavlinks);
// Work out whether we should be showing the activity (e.g. Forums) link.
// Note: build_navigation() is called from many places --
// install & upgrade for example -- where we cannot count on the
// roles infrastructure to be defined. Hence the $CFG->rolesactive check.
if (!isset($CFG->hideactivitytypenavlink)) {
$CFG->hideactivitytypenavlink = 0;
}
if ($CFG->hideactivitytypenavlink == 2) {
$hideactivitylink = true;
} else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
!empty($COURSE->id) && $COURSE->id != SITEID) {
if (!isset($COURSE->context)) {
$COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
}
$hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
} else {
$hideactivitylink = false;
}
//Construct an unordered list from $navlinks
//Accessibility: heading hidden from visual browsers by default.
$navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
$lastindex = count($navlinks) - 1;
$i = -1; // Used to count the times, so we know when we get to the last item.
$first = true;
foreach ($navlinks as $navlink) {
$i++;
$last = ($i == $lastindex);
if (!is_array($navlink)) {
continue;
}
if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
continue;
}
if ($first) {
$navigation .= '<li class="first">';
} else {
$navigation .= '<li>';
}
if (!$first) {
$navigation .= get_separator();
}
if ((!empty($navlink['link'])) && !$last) {
$navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
}
$navigation .= "{$navlink['name']}";
if ((!empty($navlink['link'])) && !$last) {
$navigation .= "</a>";
}
$navigation .= "</li>";
$first = false;
}
$navigation .= "</ul>";
return(array('newnav' => true, 'navlinks' => $navigation));
}
/**
* Prints a string in a specified size (retained for backward compatibility)
*
* @param string $text The text to be displayed
* @param int $size The size to set the font for text display.
*/
function print_headline($text, $size=2, $return=false) {
$output = print_heading($text, '', $size, true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints text in a format for use in headings.
*
* @param string $text The text to be displayed
* @param string $align The alignment of the printed paragraph of text
* @param int $size The size to set the font for text display.
*/
function print_heading($text, $align='', $size=2, $class='main', $return=false) {
if ($align) {
$align = ' style="text-align:'.$align.';"';
}
if ($class) {
$class = ' class="'.$class.'"';
}
$output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Centered heading with attached help button (same title text)
* and optional icon attached
*
* @param string $text The text to be displayed
* @param string $helppage The help page to link to
* @param string $module The module whose help should be linked to
* @param string $icon Image to display if needed
*/
function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
$output = '';
$output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
$output .= helpbutton($helppage, $text, $module, true, false, '', true);
$output .= '</h2>';
if ($return) {
return $output;
} else {
echo $output;
}
}
function print_heading_block($heading, $class='', $return=false) {
//Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
$output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a link to continue on to another page.
*
* @uses $CFG
* @param string $link The url to create a link to.
*/
function print_continue($link, $return=false) {
global $CFG;
// in case we are logging upgrade in admin/index.php stop it
if (function_exists('upgrade_log_finish')) {
upgrade_log_finish();
}
$output = '';
if ($link == '') {
if (!empty($_SERVER['HTTP_REFERER'])) {
$link = $_SERVER['HTTP_REFERER'];
$link = str_replace('&', '&', $link); // make it valid XHTML
} else {
$link = $CFG->wwwroot .'/';
}
}
$options = array();
$linkparts = parse_url(str_replace('&', '&', $link));
if (isset($linkparts['query'])) {
parse_str($linkparts['query'], $options);
}
$output .= '<div class="continuebutton">';
$output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
$output .= '</div>'."\n";
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a message in a standard themed box.
* Replaces print_simple_box (see deprecatedlib.php)
*
* @param string $message, the content of the box
* @param string $classes, space-separated class names.
* @param string $idbase
* @param boolean $return, return as string or just print it
* @return mixed string or void
*/
function print_box($message, $classes='generalbox', $ids='', $return=false) {
$output = print_box_start($classes, $ids, true);
$output .= stripslashes_safe($message);
$output .= print_box_end(true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Starts a box using divs
* Replaces print_simple_box_start (see deprecatedlib.php)
*
* @param string $classes, space-separated class names.
* @param string $idbase
* @param boolean $return, return as string or just print it
* @return mixed string or void
*/
function print_box_start($classes='generalbox', $ids='', $return=false) {
global $THEME;
if (strpos($classes, 'clearfix') !== false) {
$clearfix = true;
$classes = trim(str_replace('clearfix', '', $classes));
} else {
$clearfix = false;
}
if (!empty($THEME->customcorners)) {
$classes .= ' ccbox box';
} else {
$classes .= ' box';
}
return print_container_start($clearfix, $classes, $ids, $return);
}
/**
* Simple function to end a box (see above)
* Replaces print_simple_box_end (see deprecatedlib.php)
*
* @param boolean $return, return as string or just print it
*/
function print_box_end($return=false) {
return print_container_end($return);
}
/**
* Print a message in a standard themed container.
*
* @param string $message, the content of the container
* @param boolean $clearfix clear both sides
* @param string $classes, space-separated class names.
* @param string $idbase
* @param boolean $return, return as string or just print it
* @return string or void
*/
function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
$output = print_container_start($clearfix, $classes, $idbase, true);
$output .= stripslashes_safe($message);
$output .= print_container_end(true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Starts a container using divs
*
* @param boolean $clearfix clear both sides
* @param string $classes, space-separated class names.
* @param string $idbase
* @param boolean $return, return as string or just print it
* @return mixed string or void
*/
function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
global $THEME;
if (!isset($THEME->open_containers)) {
$THEME->open_containers = array();
}
$THEME->open_containers[] = $idbase;
if (!empty($THEME->customcorners)) {
$output = _print_custom_corners_start($clearfix, $classes, $idbase);
} else {
if ($idbase) {
$id = ' id="'.$idbase.'"';
} else {
$id = '';
}
if ($clearfix) {
$clearfix = ' clearfix';
} else {
$clearfix = '';
}
if ($classes or $clearfix) {
$class = ' class="'.$classes.$clearfix.'"';
} else {
$class = '';
}
$output = '<div'.$id.$class.'>';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Simple function to end a container (see above)
* @param boolean $return, return as string or just print it
* @return mixed string or void
*/
function print_container_end($return=false) {
global $THEME;
if (empty($THEME->open_containers)) {
debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
$idbase = '';
} else {
$idbase = array_pop($THEME->open_containers);
}
if (!empty($THEME->customcorners)) {
$output = _print_custom_corners_end($idbase);
} else {
$output = '</div>';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Returns number of currently open containers
* @return int number of open containers
*/
function open_containers() {
global $THEME;
if (!isset($THEME->open_containers)) {
$THEME->open_containers = array();
}
return count($THEME->open_containers);
}
/**
* Force closing of open containers
* @param boolean $return, return as string or just print it
* @param int $keep number of containers to be kept open - usually theme or page containers
* @return mixed string or void
*/
function print_container_end_all($return=false, $keep=0) {
$output = '';
while (open_containers() > $keep) {
$output .= print_container_end($return);
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Internal function - do not use directly!
* Starting part of the surrounding divs for custom corners
*
* @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
* @param string $classes
* @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
* @return string
*/
function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
/// Analise if we want ids for the custom corner elements
$id = '';
$idbt = '';
$idi1 = '';
$idi2 = '';
$idi3 = '';
if ($idbase) {
$id = 'id="'.$idbase.'" ';
$idbt = 'id="'.$idbase.'-bt" ';
$idi1 = 'id="'.$idbase.'-i1" ';
$idi2 = 'id="'.$idbase.'-i2" ';
$idi3 = 'id="'.$idbase.'-i3" ';
}
/// Calculate current level
$level = open_containers();
/// Output begins
$output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
$output .= '<div '.$idbt.'class="bt"><div> </div></div>';
$output .= "\n";
$output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
$output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
return $output;
}
/**
* Internal function - do not use directly!
* Ending part of the surrounding divs for custom corners
* @param string $idbase
* @return string
*/
function _print_custom_corners_end($idbase) {
/// Analise if we want ids for the custom corner elements
$idbb = '';
if ($idbase) {
$idbb = 'id="' . $idbase . '-bb" ';
}
/// Output begins
$output = '</div></div></div>';
$output .= "\n";
$output .= '<div '.$idbb.'class="bb"><div> </div></div>'."\n";
$output .= '</div>';
return $output;
}
/**
* Print a self contained form with a single submit button.
*
* @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
* @param array $options these become hidden form fields, so these options get passed to the script at $link.
* @param string $label the caption that appears on the button.
* @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
* @param string $target no longer used.
* @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
* @param string $tooltip a tooltip to add to the button as a title attribute.
* @param boolean $disabled if true, the button will be disabled.
* @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
* @return string / nothing depending on the $return paramter.
*/
function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
$output = '';
$link = str_replace('"', '"', $link); //basic XSS protection
$output .= '<div class="singlebutton">';
// taking target out, will need to add later target="'.$target.'"
$output .= '<form action="'. $link .'" method="'. $method .'">';
$output .= '<div>';
if ($options) {
foreach ($options as $name => $value) {
$output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
}
}
if ($tooltip) {
$tooltip = 'title="' . s($tooltip) . '"';
} else {
$tooltip = '';
}
if ($disabled) {
$disabled = 'disabled="disabled"';
} else {
$disabled = '';
}
if ($jsconfirmmessage){
$jsconfirmmessage = addslashes_js($jsconfirmmessage);
$jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
}
$output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a spacer image with the option of including a line break.
*
* @param int $height ?
* @param int $width ?
* @param boolean $br ?
* @todo Finish documenting this function
*/
function print_spacer($height=1, $width=1, $br=true, $return=false) {
global $CFG;
$output = '';
$output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
if ($br) {
$output .= '<br />'."\n";
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Given the path to a picture file in a course, or a URL,
* this function includes the picture in the page.
*
* @param string $path ?
* @param int $courseid ?
* @param int $height ?
* @param int $width ?
* @param string $link ?
* @todo Finish documenting this function
*/
function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
global $CFG;
$output = '';
if ($height) {
$height = 'height="'. $height .'"';
}
if ($width) {
$width = 'width="'. $width .'"';
}
if ($link) {
$output .= '<a href="'. $link .'">';
}
if (substr(strtolower($path), 0, 7) == 'http://') {
$output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
} else if ($courseid) {
$output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
require_once($CFG->libdir.'/filelib.php');
$output .= get_file_url("$courseid/$path");
$output .= '" />';
} else {
$output .= 'Error: must pass URL or course';
}
if ($link) {
$output .= '</a>';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print the specified user's avatar.
*
* @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
* If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
* if at all possible, particularly for reports. It is very bad for performance.
* @param int $courseid The course id. Used when constructing the link to the user's profile.
* @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
* @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
* @param boolean $return If false print picture to current page, otherwise return the output as string
* @param boolean $link enclose printed image in a link the user's profile (default true).
* @param string $target link target attribute. Makes the profile open in a popup window.
* @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
* decorative images, or where the username will be printed anyway.)
* @return string or nothing, depending on $return.
*/
function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
global $CFG;
$needrec = false;
// only touch the DB if we are missing data...
if (is_object($user)) {
// Note - both picture and imagealt _can_ be empty
// what we are trying to see here is if they have been fetched
// from the DB. We should use isset() _except_ that some installs
// have those fields as nullable, and isset() will return false
// on null. The only safe thing is to ask array_key_exists()
// which works on objects. property_exists() isn't quite
// what we want here...
if (! (array_key_exists('picture', $user)
&& ($alttext && array_key_exists('imagealt', $user)
|| (isset($user->firstname) && isset($user->lastname)))) ) {
$needrec = true;
$user = $user->id;
}
} else {
if ($alttext) {
// we need firstname, lastname, imagealt, can't escape...
$needrec = true;
} else {
$userobj = new StdClass; // fake it to save DB traffic
$userobj->id = $user;
$userobj->picture = $picture;
$user = clone($userobj);
unset($userobj);
}
}
if ($needrec) {
$user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
}
if ($link) {
$url = '/user/view.php?id='. $user->id .'&course='. $courseid ;
if ($target) {
$target='onclick="return openpopup(\''.$url.'\');"';
}
$output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
} else {
$output = '';
}
if (empty($size)) {
$file = 'f2';
$size = 35;
} else if ($size === true or $size == 1) {
$file = 'f1';
$size = 100;
} else if ($size >= 50) {
$file = 'f1';
} else {
$file = 'f2';
}
$class = "userpicture";
if (is_null($picture) and !empty($user->picture)) {
$picture = $user->picture;
}
if ($picture) { // Print custom user picture
require_once($CFG->libdir.'/filelib.php');
$src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
} else { // Print default user pictures (use theme version if available)
$class .= " defaultuserpic";
$src = "$CFG->pixpath/u/$file.png";
}
$imagealt = '';
if ($alttext) {
if (!empty($user->imagealt)) {
$imagealt = $user->imagealt;
} else {
$imagealt = get_string('pictureof','',fullname($user));
}
}
$output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" alt=\"".s($imagealt).'" />';
if ($link) {
$output .= '</a>';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints a summary of a user in a nice little box.
*
* @uses $CFG
* @uses $USER
* @param user $user A {@link $USER} object representing a user
* @param course $course A {@link $COURSE} object representing a course
*/
function print_user($user, $course, $messageselect=false, $return=false) {
global $CFG, $USER;
$output = '';
static $string;
static $datestring;
static $countries;
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if (isset($user->context->id)) {
$usercontext = $user->context;
} else {
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
}
if (empty($string)) { // Cache all the strings for the rest of the page
$string->email = get_string('email');
$string->city = get_string('city');
$string->lastaccess = get_string('lastaccess');
$string->activity = get_string('activity');
$string->unenrol = get_string('unenrol');
$string->loginas = get_string('loginas');
$string->fullprofile = get_string('fullprofile');
$string->role = get_string('role');
$string->name = get_string('name');
$string->never = get_string('never');
$datestring->day = get_string('day');
$datestring->days = get_string('days');
$datestring->hour = get_string('hour');
$datestring->hours = get_string('hours');
$datestring->min = get_string('min');
$datestring->mins = get_string('mins');
$datestring->sec = get_string('sec');
$datestring->secs = get_string('secs');
$datestring->year = get_string('year');
$datestring->years = get_string('years');
$countries = get_list_of_countries();
}
/// Get the hidden field list
if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
$hiddenfields = array();
} else {
$hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
}
$output .= '<table class="userinfobox">';
$output .= '<tr>';
$output .= '<td class="left side">';
$output .= print_user_picture($user, $course->id, $user->picture, true, true);
$output .= '</td>';
$output .= '<td class="content">';
$output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
$output .= '<div class="info">';
if (!empty($user->role) and ($user->role <> $course->teacher)) {
$output .= $string->role .': '. $user->role .'<br />';
}
if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
has_capability('moodle/course:viewhiddenuserfields', $context)) {
$output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
}
if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
$output .= $string->city .': ';
if ($user->city && !isset($hiddenfields['city'])) {
$output .= $user->city;
}
if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
if ($user->city && !isset($hiddenfields['city'])) {
$output .= ', ';
}
$output .= $countries[$user->country];
}
$output .= '<br />';
}
if (!isset($hiddenfields['lastaccess'])) {
if ($user->lastaccess) {
$output .= $string->lastaccess .': '. userdate($user->lastaccess);
$output .= ' ('. format_time(time() - $user->lastaccess, $datestring) .')';
} else {
$output .= $string->lastaccess .': '. $string->never;
}
}
$output .= '</div></td><td class="links">';
//link to blogs
if ($CFG->bloglevel > 0) {
$output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
}
//link to notes
if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
$output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
}
if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
$output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&user='. $user->id .'">'. $string->activity .'</a><br />';
}
if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role
$output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&user='. $user->id .'">'. $string->unenrol .'</a><br />';
}
if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
! has_capability('moodle/site:doanything', $context, $user->id, false)) {
$output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&user='. $user->id .'&sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
}
$output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&course='. $course->id .'">'. $string->fullprofile .'...</a>';
if (!empty($messageselect)) {
$output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
}
$output .= '</td></tr></table>';
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a specified group's avatar.
*
* @param group $group A single {@link group} object OR array of groups.
* @param int $courseid The course ID.
* @param boolean $large Default small picture, or large.
* @param boolean $return If false print picture, otherwise return the output as string
* @param boolean $link Enclose image in a link to view specified course?
* @return string
* @todo Finish documenting this function
*/
function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
global $CFG;
if (is_array($group)) {
$output = '';
foreach($group as $g) {
$output .= print_group_picture($g, $courseid, $large, true, $link);
}
if ($return) {
return $output;
} else {
echo $output;
return;
}
}
$context = get_context_instance(CONTEXT_COURSE, $courseid);
// If there is no picture, do nothing
if (!$group->picture) {
return '';
}
// If picture is hidden, only show to those with course:managegroups
if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
return '';
}
if ($link or has_capability('moodle/site:accessallgroups', $context)) {
$output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&group='. $group->id .'">';
} else {
$output = '';
}
if ($large) {
$file = 'f1';
} else {
$file = 'f2';
}
// Print custom group picture
require_once($CFG->libdir.'/filelib.php');
$grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
$output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
if ($link or has_capability('moodle/site:accessallgroups', $context)) {
$output .= '</a>';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a png image.
*
* @param string $url ?
* @param int $sizex ?
* @param int $sizey ?
* @param boolean $return ?
* @param string $parameters ?
* @todo Finish documenting this function
*/
function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
global $CFG;
static $recentIE;
if (!isset($recentIE)) {
$recentIE = check_browser_version('MSIE', '5.0');
}
if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
$output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
"'$url', sizingMethod='scale') ".
' '. $parameters .' />';
} else {
$output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
}
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print a nicely formatted table.
*
* @param array $table is an object with several properties.
* <ul>
* <li>$table->head - An array of heading names.
* <li>$table->align - An array of column alignments
* <li>$table->size - An array of column sizes
* <li>$table->wrap - An array of "nowrap"s or nothing
* <li>$table->data[] - An array of arrays containing the data.
* <li>$table->width - A percentage of the page
* <li>$table->tablealign - Align the whole table
* <li>$table->cellpadding - Padding on each cell
* <li>$table->cellspacing - Spacing between cells
* <li>$table->class - class attribute to put on the table
* <li>$table->id - id attribute to put on the table.
* <li>$table->rowclass[] - classes to add to particular rows.
* <li>$table->summary - Description of the contents for screen readers.
* </ul>
* @param bool $return whether to return an output string or echo now
* @return boolean or $string
* @todo Finish documenting this function
*/
function print_table($table, $return=false) {
$output = '';
if (isset($table->align)) {
foreach ($table->align as $key => $aa) {
if ($aa) {
$align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
} else {
$align[$key] = '';
}
}
}
if (isset($table->size)) {
foreach ($table->size as $key => $ss) {
if ($ss) {
$size[$key] = ' width:'. $ss .';';
} else {
$size[$key] = '';
}
}
}
if (isset($table->wrap)) {
foreach ($table->wrap as $key => $ww) {
if ($ww) {
$wrap[$key] = ' white-space:nowrap;';
} else {
$wrap[$key] = '';
}
}
}
if (empty($table->width)) {
$table->width = '80%';
}
if (empty($table->tablealign)) {
$table->tablealign = 'center';
}
if (!isset($table->cellpadding)) {
$table->cellpadding = '5';
}
if (!isset($table->cellspacing)) {
$table->cellspacing = '1';
}
if (empty($table->class)) {
$table->class = 'generaltable';
}
$tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
$output .= '<table width="'.$table->width.'" ';
if (!empty($table->summary)) {
$output .= " summary=\"$table->summary\"";
}
$output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
$countcols = 0;
if (!empty($table->head)) {
$countcols = count($table->head);
$output .= '<tr>';
$keys=array_keys($table->head);
$lastkey = end($keys);
foreach ($table->head as $key => $heading) {
if (!isset($size[$key])) {
$size[$key] = '';
}
if (!isset($align[$key])) {
$align[$key] = '';
}
if ($key == $lastkey) {
$extraclass = ' lastcol';
} else {
$extraclass = '';
}
$output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
}
$output .= '</tr>'."\n";
}
if (!empty($table->data)) {
$oddeven = 1;
$keys=array_keys($table->data);
$lastrowkey = end($keys);
foreach ($table->data as $key => $row) {
$oddeven = $oddeven ? 0 : 1;
if (!isset($table->rowclass[$key])) {
$table->rowclass[$key] = '';
}
if ($key == $lastrowkey) {
$table->rowclass[$key] .= ' lastrow';
}
$output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
if ($row == 'hr' and $countcols) {
$output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
} else { /// it's a normal row of data
$keys2=array_keys($row);
$lastkey = end($keys2);
foreach ($row as $key => $item) {
if (!isset($size[$key])) {
$size[$key] = '';
}
if (!isset($align[$key])) {
$align[$key] = '';
}
if (!isset($wrap[$key])) {
$wrap[$key] = '';
}
if ($key == $lastkey) {
$extraclass = ' lastcol';
} else {
$extraclass = '';
}
$output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
}
}
$output .= '</tr>'."\n";
}
}
$output .= '</table>'."\n";
if ($return) {
return $output;
}
echo $output;
return true;
}
function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
static $strftimerecent = null;
$output = '';
if (is_null($viewfullnames)) {
$context = get_context_instance(CONTEXT_SYSTEM);
$viewfullnames = has_capability('moodle/site:viewfullnames', $context);
}
if (is_null($strftimerecent)) {
$strftimerecent = get_string('strftimerecent');
}
$output .= '<div class="head">';
$output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
$output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
$output .= '</div>';
$output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints a basic textarea field.
*
* @uses $CFG
* @param boolean $usehtmleditor ?
* @param int $rows ?
* @param int $cols ?
* @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
* @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
* @param string $name ?
* @param string $value ?
* @param int $courseid ?
* @todo Finish documenting this function
*/
function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
/// $width and height are legacy fields and no longer used as pixels like they used to be.
/// However, you can set them to zero to override the mincols and minrows values below.
global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
static $scriptcount = 0; // For loading the htmlarea script only once.
$mincols = 65;
$minrows = 10;
$str = '';
if ($id === '') {
$id = 'edit-'.$name;
}
if ( empty($CFG->editorsrc) ) { // for backward compatibility.
if (empty($courseid)) {
$courseid = $COURSE->id;
}
if ($usehtmleditor) {
if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
$httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&httpsrequired=1';
// needed for course file area browsing in image insert plugin
$str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
$CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
} else {
$httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
$str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
$CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
}
$str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
$CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
$scriptcount++;
if ($height) { // Usually with legacy calls
if ($rows < $minrows) {
$rows = $minrows;
}
}
if ($width) { // Usually with legacy calls
if ($cols < $mincols) {
$cols = $mincols;
}
}
}
}
$str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
if ($usehtmleditor) {
$str .= htmlspecialchars($value); // needed for editing of cleaned text!
} else {
$str .= s($value);
}
$str .= '</textarea>'."\n";
if ($usehtmleditor) {
// Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
$str .= '<script type="text/javascript">
//<![CDATA[
document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
//]]>
</script>';
}
if ($return) {
return $str;
}
echo $str;
}
/**
* Sets up the HTML editor on textareas in the current page.
* If a field name is provided, then it will only be
* applied to that field - otherwise it will be used
* on every textarea in the page.
*
* In most cases no arguments need to be supplied
*
* @param string $name Form element to replace with HTMl editor by name
*/
function use_html_editor($name='', $editorhidebuttons='', $id='') {
global $THEME;
$editor = 'editor_'.md5($name); //name might contain illegal characters
if ($id === '') {
$id = 'edit-'.$name;
}
echo "\n".'<script type="text/javascript" defer="defer">'."\n";
echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
echo "$editor = new HTMLArea('$id');\n";
echo "var config = $editor.config;\n";
echo print_editor_config($editorhidebuttons);
if (empty($THEME->htmleditorpostprocess)) {
if (empty($name)) {
echo "\nHTMLArea.replaceAll($editor.config);\n";
} else {
echo "\n$editor.generate();\n";
}
} else {
if (empty($name)) {
echo "\nvar HTML_name = '';";
} else {
echo "\nvar HTML_name = \"$name;\"";
}
echo "\nvar HTML_editor = $editor;";
}
echo '//]]>'."\n";
echo '</script>'."\n";
}
function print_editor_config($editorhidebuttons='', $return=false) {
global $CFG;
$str = "config.pageStyle = \"body {";
if (!(empty($CFG->editorbackgroundcolor))) {
$str .= " background-color: $CFG->editorbackgroundcolor;";
}
if (!(empty($CFG->editorfontfamily))) {
$str .= " font-family: $CFG->editorfontfamily;";
}
if (!(empty($CFG->editorfontsize))) {
$str .= " font-size: $CFG->editorfontsize;";
}
$str .= " }\";\n";
$str .= "config.killWordOnPaste = ";
$str .= (empty($CFG->editorkillword)) ? "false":"true";
$str .= ';'."\n";
$str .= 'config.fontname = {'."\n";
$fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
$i = 1; // Counter is used to get rid of the last comma.
foreach ($fontlist as $fontline) {
if (!empty($fontline)) {
if ($i > 1) {
$str .= ','."\n";
}
list($fontkey, $fontvalue) = split(':', $fontline);
$str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
$i++;
}
}
$str .= '};';
if (!empty($editorhidebuttons)) {
$str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
} else if (!empty($CFG->editorhidebuttons)) {
$str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
}
if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
$str .= print_speller_code($CFG->htmleditor, true);
}
if ($return) {
return $str;
}
echo $str;
}
/**
* Returns a turn edit on/off button for course in a self contained form.
* Used to be an icon, but it's now a simple form button
*
* Note that the caller is responsible for capchecks.
*
* @uses $CFG
* @uses $USER
* @param int $courseid The course to update by id as found in 'course' table
* @return string
*/
function update_course_icon($courseid) {
global $CFG, $USER;
if (!empty($USER->editing)) {
$string = get_string('turneditingoff');
$edit = '0';
} else {
$string = get_string('turneditingon');
$edit = '1';
}
return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
'<div>'.
'<input type="hidden" name="id" value="'.$courseid.'" />'.
'<input type="hidden" name="edit" value="'.$edit.'" />'.
'<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
'<input type="submit" value="'.$string.'" />'.
'</div></form>';
}
/**
* Returns a little popup menu for switching roles
*
* @uses $CFG
* @uses $USER
* @param int $courseid The course to update by id as found in 'course' table
* @return string
*/
function switchroles_form($courseid) {
global $CFG, $USER;
if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
return '';
}
if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
$options = array();
$options['id'] = $courseid;
$options['sesskey'] = sesskey();
$options['switchrole'] = 0;
return print_single_button($CFG->wwwroot.'/course/view.php', $options,
get_string('switchrolereturn'), 'post', '_self', true);
}
if (has_capability('moodle/role:switchroles', $context)) {
if (!$roles = get_assignable_roles_for_switchrole($context)) {
return ''; // Nothing to show!
}
// unset default user role - it would not work
unset($roles[$CFG->guestroleid]);
return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&sesskey='.sesskey().'&switchrole=',
$roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
}
return '';
}
/**
* Returns a turn edit on/off button for course in a self contained form.
* Used to be an icon, but it's now a simple form button
*
* @uses $CFG
* @uses $USER
* @param int $courseid The course to update by id as found in 'course' table
* @return string
*/
function update_mymoodle_icon() {
global $CFG, $USER;
if (!empty($USER->editing)) {
$string = get_string('updatemymoodleoff');
$edit = '0';
} else {
$string = get_string('updatemymoodleon');
$edit = '1';
}
return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
"<div>".
"<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
"<input type=\"submit\" value=\"$string\" /></div></form>";
}
/**
* Returns a turn edit on/off button for tag in a self contained form.
*
* @uses $CFG
* @uses $USER
* @return string
*/
function update_tag_button($tagid) {
global $CFG, $USER;
if (!empty($USER->editing)) {
$string = get_string('turneditingoff');
$edit = '0';
} else {
$string = get_string('turneditingon');
$edit = '1';
}
return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
"<div>".
"<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
"<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
"<input type=\"submit\" value=\"$string\" /></div></form>";
}
/**
* Prints the editing button on a module "view" page
*
* @uses $CFG
* @param type description
* @todo Finish documenting this function
*/
function update_module_button($moduleid, $courseid, $string) {
global $CFG, $USER;
if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
$string = get_string('updatethis', '', $string);
return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/mod.php\" onsubmit=\"this.target='{$CFG->framename}'; return true\">".//hack to allow edit on framed resources
"<div>".
"<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
"<input type=\"hidden\" name=\"return\" value=\"true\" />".
"<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
"<input type=\"submit\" value=\"$string\" /></div></form>";
} else {
return '';
}
}
/**
* Prints the editing button on search results listing
* For bulk move courses to another category
*/
function update_categories_search_button($search,$page,$perpage) {
global $CFG, $USER;
// not sure if this capability is the best here
if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
if (!empty($USER->categoryediting)) {
$string = get_string("turneditingoff");
$edit = "off";
$perpage = 30;
} else {
$string = get_string("turneditingon");
$edit = "on";
}
return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
'<div>'.
"<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
"<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
"<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
"<input type=\"hidden\" name=\"page\" value=\"$page\" />".
"<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
"<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
}
}
/**
* Given a course and a (current) coursemodule
* This function returns a small popup menu with all the
* course activity modules in it, as a navigation menu
* The data is taken from the serialised array stored in
* the course record
*
* @param course $course A {@link $COURSE} object.
* @param course $cm A {@link $COURSE} object.
* @param string $targetwindow ?
* @return string
* @todo Finish documenting this function
*/
function navmenu($course, $cm=NULL, $targetwindow='self') {
global $CFG, $THEME, $USER;
if (empty($THEME->navmenuwidth)) {
$width = 50;
} else {
$width = $THEME->navmenuwidth;
}
if ($cm) {
$cm = $cm->id;
}
if ($course->format == 'weeks') {
$strsection = get_string('week');
} else {
$strsection = get_string('topic');
}
$strjumpto = get_string('jumpto');
$modinfo = get_fast_modinfo($course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$section = -1;
$selected = '';
$url = '';
$previousmod = NULL;
$backmod = NULL;
$nextmod = NULL;
$selectmod = NULL;
$logslink = NULL;
$flag = false;
$menu = array();
$menustyle = array();
$sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
$THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
}
foreach ($modinfo->cms as $mod) {
if ($mod->modname == 'label') {
continue;
}
if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
break;
}
if (!$mod->uservisible) { // do not icnlude empty sections at all
continue;
}
if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
$thissection = $sections[$mod->sectionnum];
if ($thissection->visible or !$course->hiddensections or
has_capability('moodle/course:viewhiddensections', $context)) {
$thissection->summary = strip_tags(format_string($thissection->summary,true));
if ($course->format == 'weeks' or empty($thissection->summary)) {
$menu[] = '--'.$strsection ." ". $mod->sectionnum;
} else {
if (strlen($thissection->summary) < ($width-3)) {
$menu[] = '--'.$thissection->summary;
} else {
$menu[] = '--'.substr($thissection->summary, 0, $width).'...';
}
}
$section = $mod->sectionnum;
} else {
// no activities from this hidden section shown
continue;
}
}
$url = $mod->modname.'/view.php?id='. $mod->id;
if ($flag) { // the current mod is the "next" mod
$nextmod = $mod;
$flag = false;
}
$localname = $mod->name;
if ($cm == $mod->id) {
$selected = $url;
$selectmod = $mod;
$backmod = $previousmod;
$flag = true; // set flag so we know to use next mod for "next"
$localname = $strjumpto;
$strjumpto = '';
} else {
$localname = strip_tags(format_string($localname,true));
$tl=textlib_get_instance();
if ($tl->strlen($localname) > ($width+5)) {
$localname = $tl->substr($localname, 0, $width).'...';
}
if (!$mod->visible) {
$localname = '('.$localname.')';
}
}
$menu[$url] = $localname;
if (empty($THEME->navmenuiconshide)) {
$menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
}
$previousmod = $mod;
}
//Accessibility: added Alt text, replaced > < with 'silent' character and 'accesshide' text.
if ($selectmod and has_capability('coursereport/log:view', $context)) {
$logstext = get_string('alllogs');
$logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
$CFG->wwwroot.'/course/report/log/index.php?chooselog=1&user=0&date=0&id='.
$course->id.'&modid='.$selectmod->id.'">'.
'<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
}
if ($backmod) {
$backtext= get_string('activityprev', 'access');
$backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.$CFG->frametarget.' '.
'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
'<input type="hidden" name="id" value="'.$backmod->id.'" />'.
'<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
'</button></fieldset></form></li>';
}
if ($nextmod) {
$nexttext= get_string('activitynext', 'access');
$nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.$CFG->frametarget.' '.
'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
'<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
'<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
'</button></fieldset></form></li>';
}
return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
'<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
'', '', true, $targetwindow, '', $menustyle).'</li>'.
$nextmod . '</ul>'."\n".'</div>';
}
/**
* Given a course
* This function returns a small popup menu with all the
* course activity modules in it, as a navigation menu
* outputs a simple list structure in XHTML
* The data is taken from the serialised array stored in
* the course record
*
* @param course $course A {@link $COURSE} object.
* @return string
* @todo Finish documenting this function
*/
function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
global $CFG;
$section = -1;
$url = '';
$menu = array();
$doneheading = false;
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
foreach ($modinfo->cms as $mod) {
if ($mod->modname == 'label') {
continue;
}
if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
break;
}
if (!$mod->uservisible) { // do not icnlude empty sections at all
continue;
}
if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
$thissection = $sections[$mod->sectionnum];
if ($thissection->visible or !$course->hiddensections or
has_capability('moodle/course:viewhiddensections', $coursecontext)) {
$thissection->summary = strip_tags(format_string($thissection->summary,true));
if (!$doneheading) {
$menu[] = '</ul></li>';
}
if ($course->format == 'weeks' or empty($thissection->summary)) {
$item = $strsection ." ". $mod->sectionnum;
} else {
if (strlen($thissection->summary) < ($width-3)) {
$item = $thissection->summary;
} else {
$item = substr($thissection->summary, 0, $width).'...';
}
}
$menu[] = '<li class="section"><span>'.$item.'</span>';
$menu[] = '<ul>';
$doneheading = true;
$section = $mod->sectionnum;
} else {
// no activities from this hidden section shown
continue;
}
}
$url = $mod->modname .'/view.php?id='. $mod->id;
$mod->name = strip_tags(format_string(urldecode($mod->name),true));
if (strlen($mod->name) > ($width+5)) {
$mod->name = substr($mod->name, 0, $width).'...';
}
if (!$mod->visible) {
$mod->name = '('.$mod->name.')';
}
$class = 'activity '.$mod->modname;
$class .= ($cmid == $mod->id) ? ' selected' : '';
$menu[] = '<li class="'.$class.'">'.
'<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
'<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
}
if ($doneheading) {
$menu[] = '</ul></li>';
}
$menu[] = '</ul></li></ul>';
return implode("\n", $menu);
}
/**
* Prints form items with the names $day, $month and $year
*
* @param string $day fieldname
* @param string $month fieldname
* @param string $year fieldname
* @param int $currenttime A default timestamp in GMT
* @param boolean $return
*/
function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
if (!$currenttime) {
$currenttime = time();
}
$currentdate = usergetdate($currenttime);
for ($i=1; $i<=31; $i++) {
$days[$i] = $i;
}
for ($i=1; $i<=12; $i++) {
$months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
}
for ($i=1970; $i<=2020; $i++) {
$years[$i] = $i;
}
// Build or print result
$result='';
// Note: There should probably be a fieldset around these fields as they are
// clearly grouped. However this causes problems with display. See Mozilla
// bug 474415
$result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
$result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
$result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
$result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
$result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
$result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
if ($return) {
return $result;
} else {
echo $result;
}
}
/**
*Prints form items with the names $hour and $minute
*
* @param string $hour fieldname
* @param string ? $minute fieldname
* @param $currenttime A default timestamp in GMT
* @param int $step minute spacing
* @param boolean $return
*/
function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
if (!$currenttime) {
$currenttime = time();
}
$currentdate = usergetdate($currenttime);
if ($step != 1) {
$currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
}
for ($i=0; $i<=23; $i++) {
$hours[$i] = sprintf("%02d",$i);
}
for ($i=0; $i<=59; $i+=$step) {
$minutes[$i] = sprintf("%02d",$i);
}
// Build or print result
$result='';
// Note: There should probably be a fieldset around these fields as they are
// clearly grouped. However this causes problems with display. See Mozilla
// bug 474415
$result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
$result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
$result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
$result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
if ($return) {
return $result;
} else {
echo $result;
}
}
/**
* Prints time limit value selector
*
* @uses $CFG
* @param int $timelimit default
* @param string $unit
* @param string $name
* @param boolean $return
*/
function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
global $CFG;
if ($unit) {
$unit = ' '.$unit;
}
// Max timelimit is sessiontimeout - 10 minutes.
$maxvalue = ($CFG->sessiontimeout / 60) - 10;
for ($i=1; $i<=$maxvalue; $i++) {
$minutes[$i] = $i.$unit;
}
return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
}
/**
* Prints a grade menu (as part of an existing form) with help
* Showing all possible numerical grades and scales
*
* @uses $CFG
* @param int $courseid ?
* @param string $name ?
* @param string $current ?
* @param boolean $includenograde ?
* @todo Finish documenting this function
*/
function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
global $CFG;
$output = '';
$strscale = get_string('scale');
$strscales = get_string('scales');
$scales = get_scales_menu($courseid);
foreach ($scales as $i => $scalename) {
$grades[-$i] = $strscale .': '. $scalename;
}
if ($includenograde) {
$grades[0] = get_string('nograde');
}
for ($i=100; $i>=1; $i--) {
$grades[$i] = $i;
}
$output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
$linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
$output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
$linkobject, 400, 500, $strscales, 'none', true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints a scale menu (as part of an existing form) including help button
* Just like {@link print_grade_menu()} but without the numeric grades
*
* @param int $courseid ?
* @param string $name ?
* @param string $current ?
* @todo Finish documenting this function
*/
function print_scale_menu($courseid, $name, $current, $return=false) {
global $CFG;
$output = '';
$strscales = get_string('scales');
$output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
$linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
$output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
$linkobject, 400, 500, $strscales, 'none', true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Prints a help button about a scale
*
* @uses $CFG
* @param id $courseid ?
* @param object $scale ?
* @todo Finish documenting this function
*/
function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
global $CFG;
$output = '';
$strscales = get_string('scales');
$linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
$output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true&scaleid='. $scale->id, 'ratingscale',
$linkobject, 400, 500, $scale->name, 'none', true);
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* Print an error page displaying an error message. New method - use this for new code.
*
* @uses $SESSION
* @uses $CFG
* @param string $errorcode The name of the string from error.php (or other specified file) to print
* @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
* @param object $a Extra words and phrases that might be required in the error string
* @param array $extralocations An array of strings with other locations to look for string files
* @return does not return, terminates script
*/
function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
global $CFG, $SESSION, $THEME;
if (empty($module) || $module === 'moodle' || $module === 'core') {
$module = 'error';
}
$message = get_string($errorcode, $module, $a, $extralocations);
if ($module === 'error' and strpos($message, '[[') === 0) {
//search in moodle file if error specified - needed for backwards compatibility
$message = get_string($errorcode, 'moodle', $a, $extralocations);
}
if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
if ( !empty($SESSION->fromurl) ) {
$link = $SESSION->fromurl;
unset($SESSION->fromurl);
} else {
$link = $CFG->wwwroot .'/';
}
}
// when printing an error the continue button should never link offsite
if (stripos($link, $CFG->wwwroot) === false &&
stripos($link, $CFG->httpswwwroot) === false) {
$link = $CFG->wwwroot.'/';
}
if (!empty($CFG->errordocroot)) {
$errordocroot = $CFG->errordocroot;
} else if (!empty($CFG->docroot)) {
$errordocroot = $CFG->docroot;
} else {
$errordocroot = 'http://docs.moodle.org';
}
if (defined('FULLME') && FULLME == 'cron') {
// Errors in cron should be mtrace'd.
mtrace($message);
die;
}
if ($module === 'error') {
$modulelink = 'moodle';
} else {
$modulelink = $module;
}
$message = clean_text('<p class="errormessage">'.$message.'</p>'.
'<p class="errorcode">'.
'<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
get_string('moreinformation').'</a></p>');
if (! defined('HEADER_PRINTED')) {
//header not yet printed
@header('HTTP/1.0 404 Not Found');
print_header(get_string('error'));
} else {
print_container_end_all(false, $THEME->open_header_containers);
}
echo '<br />';
print_simple_box($message, '', '', '', '', 'errorbox');
debugging('Stack trace:', DEBUG_DEVELOPER);
// in case we are logging upgrade in admin/index.php stop it
if (function_exists('upgrade_log_finish')) {
upgrade_log_finish();
}
if (!empty($link)) {
print_continue($link);
}
print_footer();
for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
echo ' ';
}
die;
}
/**
* Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
* Default errorcode is 1.
*
* Very useful for perl-like error-handling:
*
* do_somethting() or mdie("Something went wrong");
*
* @param string $msg Error message
* @param integer $errorcode Error code to emit
*/
function mdie($msg='', $errorcode=1) {
trigger_error($msg);
exit($errorcode);
}
/**
* Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
* Should be used only with htmleditor or textarea.
* @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
* helpbutton.
* @return string
*/
function editorhelpbutton(){
global $CFG, $SESSION;
$items = func_get_args();
$i = 1;
$urlparams = array();
$titles = array();
foreach ($items as $item){
if (is_array($item)){
$urlparams[] = "keyword$i=".urlencode($item[0]);
$urlparams[] = "title$i=".urlencode($item[1]);
if (isset($item[2])){
$urlparams[] = "module$i=".urlencode($item[2]);
}
$titles[] = trim($item[1], ". \t");
}elseif (is_string($item)){
$urlparams[] = "button$i=".urlencode($item);
switch ($item){
case 'reading' :
$titles[] = get_string("helpreading");
break;
case 'writing' :
$titles[] = get_string("helpwriting");
break;
case 'questions' :
$titles[] = get_string("helpquestions");
break;
case 'emoticons' :
$titles[] = get_string("helpemoticons");
break;
case 'richtext' :
$titles[] = get_string('helprichtext');
break;
case 'text' :
$titles[] = get_string('helptext');
break;
default :
error('Unknown help topic '.$item);
}
}
$i++;
}
if (count($titles)>1){
//join last two items with an 'and'
$a = new object();
$a->one = $titles[count($titles) - 2];
$a->two = $titles[count($titles) - 1];
$titles[count($titles) - 2] = get_string('and', '', $a);
unset($titles[count($titles) - 1]);
}
$alttag = join (', ', $titles);
$paramstring = join('&', $urlparams);
$linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
}
/**
* Print a help button.
*
* @uses $CFG
* @param string $page The keyword that defines a help page
* @param string $title The title of links, rollover tips, alt tags etc
* 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
* @param string $module Which module is the page defined in
* @param mixed $image Use a help image for the link? (true/false/"both")
* @param boolean $linktext If true, display the title next to the help icon.
* @param string $text If defined then this text is used in the page, and
* the $page variable is ignored.
* @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
* @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
* @return string
* @todo Finish documenting this function
*/
function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
$imagetext='') {
global $CFG, $COURSE;
//warning if ever $text parameter is used
//$text option won't work properly because the text needs to be always cleaned and,
// when cleaned... html tags always break, so it's unusable.
if ( isset($text) && $text!='') {
debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
}
// fix for MDL-7734
if (!empty($COURSE->lang)) {
$forcelang = $COURSE->lang;
} else {
$forcelang = '';
}
if ($module == '') {
$module = 'moodle';
}
if ($title == '' && $linktext == '') {
debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
}
// Warn users about new window for Accessibility
$tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
$linkobject = '';
if ($image) {
if ($linktext) {
// MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
$linkobject .= $title.' ';
$tooltip = get_string('helpwiththis');
}
if ($imagetext) {
$linkobject .= $imagetext;
} else {
$linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
$CFG->pixpath .'/help.gif" />';
}
} else {
$linkobject .= $tooltip;
}
// fix for MDL-7734
if ($text) {
$url = '/help.php?module='. $module .'&text='. s(urlencode($text).'&forcelang='.$forcelang);
} else {
$url = '/help.php?module='. $module .'&file='. $page .'.html&forcelang='.$forcelang;
}
$link = '<span class="helplink">'.
link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
'</span>';
if ($return) {
return $link;
} else {
echo $link;
}
}
/**
* Print a help button.
*
* Prints a special help button that is a link to the "live" emoticon popup
* @uses $CFG
* @uses $SESSION
* @param string $form ?
* @param string $field ?
* @todo Finish documenting this function
*/
function emoticonhelpbutton($form, $field, $return = false) {
global $CFG, $SESSION;
$SESSION->inserttextform = $form;
$SESSION->inserttextfield = $field;
$imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
$help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
if (!$return){
echo $help;
} else {
return $help;
}
}
/**
* Print a help button.
*
* Prints a special help button for html editors (htmlarea in this case)
* @uses $CFG
*/
function editorshortcutshelpbutton() {
global $CFG;
$imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
get_string('editorshortcutkeys').'" class="iconkbhelp" />';
return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
}
/**
* Print a message and exit.
*
* @uses $CFG
* @param string $message ?
* @param string $link ?
* @todo Finish documenting this function
*/
function notice ($message, $link='', $course=NULL) {
global $CFG, $SITE, $THEME, $COURSE;
$message = clean_text($message); // In case nasties are in here
if (defined('FULLME') && FULLME == 'cron') {
// notices in cron should be mtrace'd.
mtrace($message);
die;
}
if (! defined('HEADER_PRINTED')) {
//header not yet printed
print_header(get_string('notice'));
} else {
print_container_end_all(false, $THEME->open_header_containers);
}
print_box($message, 'generalbox', 'notice');
print_continue($link);
if (empty($course)) {
print_footer($COURSE);
} else {
print_footer($course);
}
exit;
}
/**
* Print a message along with "Yes" and "No" links for the user to continue.
*
* @param string $message The text to display
* @param string $linkyes The link to take the user to if they choose "Yes"
* @param string $linkno The link to take the user to if they choose "No"
* TODO Document remaining arguments
*/
function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
global $CFG;
$message = clean_text($message);
$linkyes = clean_text($linkyes);
$linkno = clean_text($linkno);
print_box_start('generalbox', 'notice');
echo '<p>'. $message .'</p>';
echo '<div class="buttons">';
print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
echo '</div>';
print_box_end();
}
/**
* Provide an definition of error_get_last for PHP before 5.2.0. This simply
* returns NULL, since there is not way to get the right answer.
*/
if (!function_exists('error_get_last')) {
// the eval is needed to prevent PHP 5.2+ from getting a parse error!
eval('
function error_get_last() {
return NULL;
}
');
}
/**
* Redirects the user to another page, after printing a notice
*
* @param string $url The url to take the user to
* @param string $message The text message to display to the user about the redirect, if any
* @param string $delay How long before refreshing to the new page at $url?
* @todo '&' needs to be encoded into '&' for XHTML compliance,
* however, this is not true for javascript. Therefore we
* first decode all entities in $url (since we cannot rely on)
* the correct input) and then encode for where it's needed
* echo "<script type='text/javascript'>alert('Redirect $url');</script>";
*/
function redirect($url, $message='', $delay=-1) {
global $CFG, $THEME;
if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
$url = sid_process_url($url);
}
$message = clean_text($message);
// Technically, HTTP/1.1 requires Location: header to contain the absolute path.
// (In practice browsers accept relative paths - but still, might as well do it properly.)
// This code turns relative into absolute.
if (!preg_match('|^[a-z]+:|', $url)) {
// Get host name http://www.wherever.com
$hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
if (preg_match('|^/|', $url)) {
// URLs beginning with / are relative to web server root so we just add them in
$url = $hostpart.$url;
} else {
// URLs not beginning with / are relative to path of current script, so add that on.
$url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
}
// Replace all ..s
while (true) {
$newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
if ($newurl == $url) {
break;
}
$url = $newurl;
}
}
// Sanitise url - we can not rely on our URL cleaning
// because it does not support all valid external URLs
$url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
$url = str_replace('"', '%22', $url);
$encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
$encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
$url = str_replace('&', '&', $encodedurl);
/// At developer debug level. Don't redirect if errors have been printed on screen.
/// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
$lasterror = error_get_last();
$error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
$errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
if ($errorprinted) {
$message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
}
$performanceinfo = '';
if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
$perf = get_performance_info();
error_log("PERF: " . $perf['txt']);
}
}
/// when no message and header printed yet, try to redirect
if (empty($message) and !defined('HEADER_PRINTED')) {
$delay = 0;
//try header redirection first
@header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
@header('Location: '.$url);
//another way for older browsers and already sent headers (eg trailing whitespace in config.php)
echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
die;
}
if ($delay == -1) {
$delay = 3; // if no delay specified wait 3 seconds
}
if (! defined('HEADER_PRINTED')) {
// this type of redirect might not be working in some browsers - such as lynx :-(
print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
$delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
} else {
print_container_end_all(false, $THEME->open_header_containers);
}
echo '<div id="redirect">';
echo '<div id="message">' . $message . '</div>';
echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
echo '</div>';
if (!$errorprinted) {
?>
<script type="text/javascript">
//<![CDATA[
function redirect() {
document.location.replace('<?php echo addslashes_js($url) ?>');
}
setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
//]]>
</script>
<?php
}
$CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
print_footer('none');
die;
}
/**
* Print a bold message in an optional color.
*
* @param string $message The message to print out
* @param string $style Optional style to display message text in
* @param string $align Alignment option
* @param bool $return whether to return an output string or echo now
*/
function notify($message, $style='notifyproblem', $align='center', $return=false) {
if ($style == 'green') {
$style = 'notifysuccess'; // backward compatible with old color system
}
$message = clean_text($message);
$output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
if ($return) {
return $output;
}
echo $output;
}
/**
* Given an email address, this function will return an obfuscated version of it
*
* @param string $email The email address to obfuscate
* @return string
*/
function obfuscate_email($email) {
$i = 0;
$length = strlen($email);
$obfuscated = '';
while ($i < $length) {
if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
$obfuscated.='%'.dechex(ord($email{$i}));
} else {
$obfuscated.=$email{$i};
}
$i++;
}
return $obfuscated;
}
/**
* This function takes some text and replaces about half of the characters
* with HTML entity equivalents. Return string is obviously longer.
*
* @param string $plaintext The text to be obfuscated
* @return string
*/
function obfuscate_text($plaintext) {
$i=0;
$length = strlen($plaintext);
$obfuscated='';
$prev_obfuscated = false;
while ($i < $length) {
$c = ord($plaintext{$i});
$numerical = ($c >= ord('0')) && ($c <= ord('9'));
if ($prev_obfuscated and $numerical ) {
$obfuscated.='&#'.ord($plaintext{$i}).';';
} else if (rand(0,2)) {
$obfuscated.='&#'.ord($plaintext{$i}).';';
$prev_obfuscated = true;
} else {
$obfuscated.=$plaintext{$i};
$prev_obfuscated = false;
}
$i++;
}
return $obfuscated;
}
/**
* This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
* to generate a fully obfuscated email link, ready to use.
*
* @param string $email The email address to display
* @param string $label The text to dispalyed as hyperlink to $email
* @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
* @return string
*/
function obfuscate_mailto($email, $label='', $dimmed=false) {
if (empty($label)) {
$label = $email;
}
if ($dimmed) {
$title = get_string('emaildisable');
$dimmed = ' class="dimmed"';
} else {
$title = '';
$dimmed = '';
}
return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
obfuscate_text('mailto'), obfuscate_email($email),
obfuscate_text($label));
}
/**
* Prints a single paging bar to provide access to other pages (usually in a search)
*
* @param int $totalcount Thetotal number of entries available to be paged through
* @param int $page The page you are currently viewing
* @param int $perpage The number of entries that should be shown per page
* @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
* If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
* @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
* @param bool $nocurr do not display the current page as a link
* @param bool $return whether to return an output string or echo now
* @return bool or string
*/
function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
$maxdisplay = 18;
$output = '';
if ($totalcount > $perpage) {
$output .= '<div class="paging">';
$output .= get_string('page') .':';
if ($page > 0) {
$pagenum = $page - 1;
if (!is_a($baseurl, 'moodle_url')){
$output .= ' (<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>) ';
} else {
$output .= ' (<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>) ';
}
}
if ($perpage > 0) {
$lastpage = ceil($totalcount / $perpage);
} else {
$lastpage = 1;
}
if ($page > 15) {
$startpage = $page - 10;
if (!is_a($baseurl, 'moodle_url')){
$output .= ' <a href="'. $baseurl . $pagevar .'=0">1</a> ...';
} else {
$output .= ' <a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a> ...';
}
} else {
$startpage = 0;
}
$currpage = $startpage;
$displaycount = $displaypage = 0;
while ($displaycount < $maxdisplay and $currpage < $lastpage) {
$displaypage = $currpage+1;
if ($page == $currpage && empty($nocurr)) {
$output .= ' '. $displaypage;
} else {
if (!is_a($baseurl, 'moodle_url')){
$output .= ' <a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
} else {
$output .= ' <a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
}
}
$displaycount++;
$currpage++;
}
if ($currpage < $lastpage) {
$lastpageactual = $lastpage - 1;
if (!is_a($baseurl, 'moodle_url')){
$output .= ' ...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a> ';
} else {
$output .= ' ...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a> ';
}
}
$pagenum = $page + 1;
if ($pagenum != $displaypage) {
if (!is_a($baseurl, 'moodle_url')){
$output .= ' (<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
} else {
$output .= ' (<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
}
}
$output .= '</div>';
}
if ($return) {
return $output;
}
echo $output;
return true;
}
/**
* This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
* will transform it to html entities
*
* @param string $text Text to search for nolink tag in
* @return string
*/
function rebuildnolinktag($text) {
$text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
return $text;
}
/**
* Prints a nice side block with an optional header. The content can either
* be a block of HTML or a list of text with optional icons.
*
* @param string $heading Block $title embedded in HTML tags, for example <h2>.
* @param string $content ?
* @param array $list ?
* @param array $icons ?
* @param string $footer ?
* @param array $attributes ?
* @param string $title Plain text title, as embedded in the $heading.
* @todo Finish documenting this function. Show example of various attributes, etc.
*/
function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
//Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
static $block_id = 0;
$block_id++;
$skip_text = get_string('skipa', 'access', strip_tags($title));
$skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
$skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
$strip_title = strip_tags($title);
if (! empty($strip_title)) {
echo $skip_link;
}
//ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
print_side_block_start($heading, $attributes);
if ($content) {
echo $content;
if ($footer) {
echo '<div class="footer">'. $footer .'</div>';
}
} else {
if ($list) {
$row = 0;
//Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
echo "\n<ul class='list'>\n";
foreach ($list as $key => $string) {
echo '<li class="r'. $row .'">';
if ($icons) {
echo '<div class="icon column c0">'. $icons[$key] .'</div>';
}
echo '<div class="column c1">' . $string . '</div>';
echo "</li>\n";
$row = $row ? 0:1;
}
echo "</ul>\n";
}
if ($footer) {
echo '<div class="footer">'. $footer .'</div>';
}
}
print_side_block_end($attributes, $title);
echo $skip_dest;
}
/**
* Starts a nice side block with an optional header.
*
* @param string $heading ?
* @param array $attributes ?
* @todo Finish documenting this function
*/
function print_side_block_start($heading='', $attributes = array()) {
global $CFG, $THEME;
// If there are no special attributes, give a default CSS class
if (empty($attributes) || !is_array($attributes)) {
$attributes = array('class' => 'sideblock');
} else if(!isset($attributes['class'])) {
$attributes['class'] = 'sideblock';
} else if(!strpos($attributes['class'], 'sideblock')) {
$attributes['class'] .= ' sideblock';
}
// OK, the class is surely there and in addition to anything
// else, it's tagged as a sideblock
/*
// IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
// If there is a cookie to hide this thing, start it hidden
if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
$attributes['class'] = 'hidden '.$attributes['class'];
}
*/
$attrtext = '';
foreach ($attributes as $attr => $val) {
$attrtext .= ' '.$attr.'="'.$val.'"';
}
echo '<div '.$attrtext.'>';
if (!empty($THEME->customcorners)) {
echo '<div class="wrap">'."\n";
}
if ($heading) {
//Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
echo '<div class="header">';
if (!empty($THEME->customcorners)) {
echo '<div class="bt"><div> </div></div>';
echo '<div class="i1"><div class="i2">';
echo '<div class="i3">';
}
echo $heading;
if (!empty($THEME->customcorners)) {
echo '</div></div></div>';
}
echo '</div>';
} else {
if (!empty($THEME->customcorners)) {
echo '<div class="bt"><div> </div></div>';
}
}
if (!empty($THEME->customcorners)) {
echo '<div class="i1"><div class="i2">';
echo '<div class="i3">';
}
echo '<div class="content">';
}
/**
* Print table ending tags for a side block box.
*/
function print_side_block_end($attributes = array(), $title='') {
global $CFG, $THEME;
echo '</div>';
if (!empty($THEME->customcorners)) {
echo '</div></div></div><div class="bb"><div> </div></div></div>';
}
echo '</div>';
$strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
$strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
// IE workaround: if I do it THIS way, it works! WTF?
if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
'","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
}
}
/**
* Prints out code needed for spellchecking.
* Original idea by Ludo (Marc Alier).
*
* Opening CDATA and <script> are output by weblib::use_html_editor()
* @uses $CFG
* @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
* @param boolean $return If false, echos the code instead of returning it
* @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
*/
function print_speller_code ($usehtmleditor=false, $return=false) {
global $CFG;
$str = '';
if(!$usehtmleditor) {
$str .= 'function openSpellChecker() {'."\n";
$str .= "\tvar speller = new spellChecker();\n";
$str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
$str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
$str .= "\tspeller.spellCheckAll();\n";
$str .= '}'."\n";
} else {
$str .= "function spellClickHandler(editor, buttonId) {\n";
$str .= "\teditor._textArea.value = editor.getHTML();\n";
$str .= "\tvar speller = new spellChecker( editor._textArea );\n";
$str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
$str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
$str .= "\tspeller._moogle_edit=1;\n";
$str .= "\tspeller._editor=editor;\n";
$str .= "\tspeller.openChecker();\n";
$str .= '}'."\n";
}
if ($return) {
return $str;
}
echo $str;
}
/**
* Print button for spellchecking when editor is disabled
*/
function print_speller_button () {
echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
}
function page_id_and_class(&$getid, &$getclass) {
// Create class and id for this page
global $CFG, $ME;
static $class = NULL;
static $id = NULL;
if (empty($CFG->pagepath)) {
$CFG->pagepath = $ME;
}
if (empty($class) || empty($id)) {
$path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
$path = str_replace('.php', '', $path);
if (substr($path, -1) == '/') {
$path .= 'index';
}
if (empty($path) || $path == 'index') {
$id = 'site-index';
$class = 'course';
} else if (substr($path, 0, 5) == 'admin') {
$id = str_replace('/', '-', $path);
$class = 'admin';
} else {
$id = str_replace('/', '-', $path);
$class = explode('-', $id);
array_pop($class);
$class = implode('-', $class);
}
}
$getid = $id;
$getclass = $class;
}
/**
* Prints a maintenance message from /maintenance.html
*/
function print_maintenance_message () {
global $CFG, $SITE;
$CFG->pagepath = "index.php";
print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
print_box_start();
print_heading(get_string('sitemaintenance', 'admin'));
@include($CFG->dataroot.'/'.SITEID.'/maintenance.html');
print_box_end();
print_footer();
}
/**
* Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
*/
function adjust_allowed_tags() {
global $CFG, $ALLOWED_TAGS;
if (!empty($CFG->allowobjectembed)) {
$ALLOWED_TAGS .= '<embed><object>';
}
}
/// Some code to print tabs
/// A class for tabs
class tabobject {
var $id;
var $link;
var $text;
var $linkedwhenselected;
/// A constructor just because I like constructors
function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
$this->id = $id;
$this->link = $link;
$this->text = $text;
$this->title = $title ? $title : $text;
$this->linkedwhenselected = $linkedwhenselected;
}
}
/**
* Returns a string containing a nested list, suitable for formatting into tabs with CSS.
*
* @param array $tabrows An array of rows where each row is an array of tab objects
* @param string $selected The id of the selected tab (whatever row it's on)
* @param array $inactive An array of ids of inactive tabs that are not selectable.
* @param array $activated An array of ids of other tabs that are currently activated
**/
function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
global $CFG;
/// $inactive must be an array
if (!is_array($inactive)) {
$inactive = array();
}
/// $activated must be an array
if (!is_array($activated)) {
$activated = array();
}
/// Convert the tab rows into a tree that's easier to process
if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
return false;
}
/// Print out the current tree of tabs (this function is recursive)
$output = convert_tree_to_html($tree);
$output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
/// We're done!
if ($return) {
return $output;
}
echo $output;
}
function convert_tree_to_html($tree, $row=0) {
$str = "\n".'<ul class="tabrow'.$row.'">'."\n";
$first = true;
$count = count($tree);
foreach ($tree as $tab) {
$count--; // countdown to zero
$liclass = '';
if ($first && ($count == 0)) { // Just one in the row
$liclass = 'first last';
$first = false;
} else if ($first) {
$liclass = 'first';
$first = false;
} else if ($count == 0) {
$liclass = 'last';
}
if ((empty($tab->subtree)) && (!empty($tab->selected))) {
$liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
}
if ($tab->inactive || $tab->active || $tab->selected) {
if ($tab->selected) {
$liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
} else if ($tab->active) {
$liclass .= (empty($liclass)) ? 'here active' : ' here active';
}
}
$str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
// The a tag is used for styling
$str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
} else {
$str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
}
if (!empty($tab->subtree)) {
$str .= convert_tree_to_html($tab->subtree, $row+1);
} else if ($tab->selected) {
$str .= '<div class="tabrow'.($row+1).' empty"> </div>'."\n";
}
$str .= ' </li>'."\n";
}
$str .= '</ul>'."\n";
return $str;
}
function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
/// Work backwards through the rows (bottom to top) collecting the tree as we go.
$tabrows = array_reverse($tabrows);
$subtree = array();
foreach ($tabrows as $row) {
$tree = array();
foreach ($row as $tab) {
$tab->inactive = in_array((string)$tab->id, $inactive);
$tab->active = in_array((string)$tab->id, $activated);
$tab->selected = (string)$tab->id == $selected;
if ($tab->active || $tab->selected) {
if ($subtree) {
$tab->subtree = $subtree;
}
}
$tree[] = $tab;
}
$subtree = $tree;
}
return $subtree;
}
/**
* Returns a string containing a link to the user documentation for the current
* page. Also contains an icon by default. Shown to teachers and admin only.
*
* @param string $text The text to be displayed for the link
* @param string $iconpath The path to the icon to be displayed
*/
function page_doc_link($text='', $iconpath='') {
global $ME, $COURSE, $CFG;
if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
return '';
}
if (empty($COURSE->id)) {
$context = get_context_instance(CONTEXT_SYSTEM);
} else {
$context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
}
if (!has_capability('moodle/site:doclinks', $context)) {
return '';
}
if (empty($CFG->pagepath)) {
$CFG->pagepath = $ME;
}
$path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
$path = str_replace('.php', '', $path);
if (empty($path)) { // Not for home page
return '';
}
return doc_link($path, $text, $iconpath);
}
/**
* Returns a string containing a link to the user documentation.
* Also contains an icon by default. Shown to teachers and admin only.
*
* @param string $path The page link after doc root and language, no
* leading slash.
* @param string $text The text to be displayed for the link
* @param string $iconpath The path to the icon to be displayed
*/
function doc_link($path='', $text='', $iconpath='') {
global $CFG;
if (empty($CFG->docroot)) {
return '';
}
$target = '';
if (!empty($CFG->doctonewwindow)) {
$target = ' target="_blank"';
}
$lang = str_replace('_utf8', '', current_language());
$str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
if (empty($iconpath)) {
$iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
}
// alt left blank intentionally to prevent repetition in screenreaders
$str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
return $str;
}
/**
* Returns true if the current site debugging settings are equal or above specified level.
* If passed a parameter it will emit a debugging notice similar to trigger_error(). The
* routing of notices is controlled by $CFG->debugdisplay
* eg use like this:
*
* 1) debugging('a normal debug notice');
* 2) debugging('something really picky', DEBUG_ALL);
* 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
* 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
*
* In code blocks controlled by debugging() (such as example 4)
* any output should be routed via debugging() itself, or the lower-level
* trigger_error() or error_log(). Using echo or print will break XHTML
* JS and HTTP headers.
*
*
* @param string $message a message to print
* @param int $level the level at which this debugging statement should show
* @return bool
*/
function debugging($message='', $level=DEBUG_NORMAL) {
global $CFG;
if (empty($CFG->debug)) {
return false;
}
if ($CFG->debug >= $level) {
if ($message) {
$callers = debug_backtrace();
$from = '<ul style="text-align: left">';
foreach ($callers as $caller) {
if (!isset($caller['line'])) {
$caller['line'] = '?'; // probably call_user_func()
}
if (!isset($caller['file'])) {
$caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
}
$from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
if (isset($caller['function'])) {
$from .= ': call to ';
if (isset($caller['class'])) {
$from .= $caller['class'] . $caller['type'];
}
$from .= $caller['function'] . '()';
}
$from .= '</li>';
}
$from .= '</ul>';
if (!isset($CFG->debugdisplay)) {
$CFG->debugdisplay = ini_get_bool('display_errors');
}
if ($CFG->debugdisplay) {
if (!defined('DEBUGGING_PRINTED')) {
define('DEBUGGING_PRINTED', 1); // indicates we have printed something
}
notify($message . $from, 'notifytiny');
} else {
trigger_error($message . $from, E_USER_NOTICE);
}
}
return true;
}
return false;
}
/**
* Disable debug messages from debugging(), while keeping PHP error reporting level as is.
*/
function disable_debugging() {
global $CFG;
$CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
}
/**
* Returns string to add a frame attribute, if required
*/
function frametarget() {
global $CFG;
if (empty($CFG->framename) or ($CFG->framename == '_top')) {
return '';
} else {
return ' target="'.$CFG->framename.'" ';
}
}
/**
* Outputs a HTML comment to the browser. This is used for those hard-to-debug
* pages that use bits from many different files in very confusing ways (e.g. blocks).
* @usage print_location_comment(__FILE__, __LINE__);
* @param string $file
* @param integer $line
* @param boolean $return Whether to return or print the comment
* @return mixed Void unless true given as third parameter
*/
function print_location_comment($file, $line, $return = false)
{
if ($return) {
return "<!-- $file at line $line -->\n";
} else {
echo "<!-- $file at line $line -->\n";
}
}
/**
* Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
* provide this function with the language strings for sortasc and sortdesc.
* If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
* @param string $direction 'up' or 'down'
* @param string $strsort The language string used for the alt attribute of this image
* @param bool $return Whether to print directly or return the html string
* @return string HTML for the image
*
* TODO See if this isn't already defined somewhere. If not, move this to weblib
*/
function print_arrow($direction='up', $strsort=null, $return=false) {
global $CFG;
if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
return null;
}
$return = null;
switch ($direction) {
case 'up':
$sortdir = 'asc';
break;
case 'down':
$sortdir = 'desc';
break;
case 'move':
$sortdir = 'asc';
break;
default:
$sortdir = null;
break;
}
// Prepare language string
$strsort = '';
if (empty($strsort) && !empty($sortdir)) {
$strsort = get_string('sort' . $sortdir, 'grades');
}
$return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
if ($return) {
return $return;
} else {
echo $return;
}
}
/**
* Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
*
*/
function right_to_left() {
static $result;
if (isset($result)) {
return $result;
}
return $result = (get_string('thisdirection') == 'rtl');
}
/**
* Returns swapped left<=>right if in RTL environment.
* part of RTL support
*
* @param string $align align to check
* @return string
*/
function fix_align_rtl($align) {
if (!right_to_left()) {
return $align;
}
if ($align=='left') { return 'right'; }
if ($align=='right') { return 'left'; }
return $align;
}
/**
* Returns true if the page is displayed in a popup window.
* Gets the information from the URL parameter inpopup.
*
* @return boolean
*
* TODO Use a central function to create the popup calls allover Moodle and
* TODO In the moment only works with resources and probably questions.
*/
function is_in_popup() {
$inpopup = optional_param('inpopup', '', PARAM_BOOL);
return ($inpopup);
}
/**
* Return the authentication plugin title
* @param string $authtype plugin type
* @return string
*/
function auth_get_plugin_title ($authtype) {
$authtitle = get_string("auth_{$authtype}title", "auth");
if ($authtitle == "[[auth_{$authtype}title]]") {
$authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
}
return $authtitle;
}
/**
* Returns a localized sentence in the current language summarizing the current password policy
*
* @uses $CFG
* @return string
*/
function print_password_policy() {
global $CFG;
$message = '';
if (!empty($CFG->passwordpolicy)) {
$messages = array();
$messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
if (!empty($CFG->minpassworddigits)) {
$messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
}
if (!empty($CFG->minpasswordlower)) {
$messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
}
if (!empty($CFG->minpasswordupper)) {
$messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
}
if (!empty($CFG->minpasswordnonalphanum)) {
$messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
}
$messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
$message = get_string('informpasswordpolicy', 'auth', $messages);
}
return $message;
}
// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
?>
|