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 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480
|
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2024 The Cacti Group |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/**
* title_trim - takes a string of text, truncates it to $max_length and appends
* three periods onto the end
*
* @param $text - the string to evaluate
* @param $max_length - the maximum number of characters the string can contain
* before it is truncated
*
* @return - the truncated string if len($text) is greater than $max_length, else
* the original string
*/
function title_trim($text, $max_length) {
if (strlen($text) > $max_length) {
return mb_substr($text, 0, $max_length) . '...';
} else {
return $text;
}
}
/**
* filter_value - a quick way to highlight text in a table from general filtering
*
* @param $text - the string to filter
* @param $filter - the search term to filter for
* @param $href - the href if you wish to have an anchor returned
*
* @return - the filtered string
*/
function filter_value($value, $filter, $href = '') {
static $charset;
if ($charset == '') {
$charset = ini_get('default_charset');
}
if ($charset == '') {
$charset = 'UTF-8';
}
if (empty($value)) {
return $value;
}
$value = htmlspecialchars($value, ENT_QUOTES, $charset, false);
// Grave Accent character can lead to xss
$value = str_replace('`', '`', $value);
if ($filter != '') {
$value = preg_replace('#(' . preg_quote($filter) . ')#i', "<span class='filteredValue'>\\1</span>", $value);
}
if ($href != '') {
$value = '<a class="linkEditMain" href="' . htmlspecialchars($href, ENT_QUOTES, $charset, false) . '">' . $value . '</a>';
}
return $value;
}
/**
* set_graph_config_option - deprecated - wrapper to set_user_setting().
*
* @param $config_name - the name of the configuration setting as specified $settings array
* @param $value - the values to be saved
* @param $user - the user id, otherwise the session user
*
* @return - void
*/
function set_graph_config_option($config_name, $value, $user = -1) {
set_user_setting($config_name, $value, $user);
}
/**
* graph_config_value_exists - deprecated - wrapper to user_setting_exists
*
* @param $config_name - the name of the configuration setting as specified $settings_user array
* in 'include/global_settings.php'
* @param $user_id - the id of the user to check the configuration value for
*
* @return (bool) - true if a value exists, false if a value does not exist
*/
function graph_config_value_exists($config_name, $user_id) {
return user_setting_exists($config_name, $user_id);
}
/**
* read_default_graph_config_option - deprecated - wrapper to read_default_user_setting
*
* @param $config_name - the name of the configuration setting as specified $settings array
* in 'include/global_settings.php'
*
* @return - the default value of the configuration option
*/
function read_default_graph_config_option($config_name) {
return read_default_user_setting($config_name);
}
/**
* read_graph_config_option - deprecated - finds the current value of a graph configuration setting
*
* @param $config_name - the name of the configuration setting as specified $settings_user array
* in 'include/global_settings.php'
*
* @return - the current value of the graph configuration option
*/
function read_graph_config_option($config_name, $force = false) {
return read_user_setting($config_name, false, $force);
}
/**
* save_user_setting - sets/updates aLL user settings
*
* @param $config_name - the name of the configuration setting as specified $settings array
* @param $value - the values to be saved
* @param $user - the user id, otherwise the session user
*
* @return - void
*/
function save_user_settings($user = -1) {
global $settings_user;
if ($user == -1 || empty($user)) {
$user = $_SESSION['sess_user_id'];
}
foreach ($settings_user as $tab_short_name => $tab_fields) {
foreach ($tab_fields as $field_name => $field_array) {
/* Check every field with a numeric default value and reset it to default if the inputted value is not numeric */
if (isset($field_array['default']) && is_numeric($field_array['default']) && !is_numeric(get_nfilter_request_var($field_name))) {
set_request_var($field_name, $field_array['default']);
}
if (isset($field_array['method'])) {
if ($field_array['method'] == 'checkbox') {
set_user_setting($field_name, (isset_request_var($field_name) ? 'on' : ''), $user);
} elseif ($field_array['method'] == 'checkbox_group') {
foreach ($field_array['items'] as $sub_field_name => $sub_field_array) {
set_user_setting($sub_field_name, (isset_request_var($sub_field_name) ? 'on' : ''), $user);
}
} elseif ($field_array['method'] == 'textbox_password') {
if (get_nfilter_request_var($field_name) != get_nfilter_request_var($field_name.'_confirm')) {
$_SESSION['sess_error_fields'][$field_name] = $field_name;
$_SESSION['sess_field_values'][$field_name] = get_nfilter_request_var($field_name);
$errors[4] = 4;
} elseif (isset_request_var($field_name)) {
set_user_setting($field_name, get_nfilter_request_var($field_name), $user);
}
} elseif ((isset($field_array['items'])) && (is_array($field_array['items']))) {
foreach ($field_array['items'] as $sub_field_name => $sub_field_array) {
if (isset_request_var($sub_field_name)) {
set_user_setting($sub_field_name, get_nfilter_request_var($sub_field_name), $user);
}
}
} elseif (isset_request_var($field_name)) {
set_user_setting($field_name, get_nfilter_request_var($field_name), $user);
}
}
}
}
}
/**
* set_user_setting - sets/updates a user setting with the given value.
*
* @param $config_name - the name of the configuration setting as specified $settings array
* @param $value - the values to be saved
* @param $user - the user id, otherwise the session user
*
* @return - void
*/
function set_user_setting($config_name, $value, $user = -1) {
global $settings_user;
if ($user == -1 && isset($_SESSION['sess_user_id'])) {
$user = $_SESSION['sess_user_id'];
}
if ($user == -1) {
if (isset($_SESSION['sess_user_id'])) {
$mode = 'WEBUI';
} else {
$mode = 'POLLER';
}
cacti_log('NOTE: Attempt to set user setting \'' . $config_name . '\', with no user id: ' . cacti_debug_backtrace('', false, false, 0, 1), false, $mode, POLLER_VERBOSITY_MEDIUM);
} elseif (db_table_exists('settings_user')) {
if (strlen($config_name) > 75) {
cacti_log("ERROR: User setting name '$config_name' is too long, will be truncated", false, 'SYSTEM');
}
db_execute_prepared('REPLACE INTO settings_user
SET user_id = ?,
name = ?,
value = ?',
array($user, $config_name, $value));
unset($_SESSION['sess_user_config_array']);
$settings_user[$config_name]['value'] = $value;
}
}
/**
* user_setting_exists - determines if a value exists for the current user/setting specified
*
* @param $config_name - the name of the configuration setting as specified $settings_user array
* in 'include/global_settings.php'
* @param $user_id - the id of the user to check the configuration value for
*
* @return (bool) - true if a value exists, false if a value does not exist
*/
function user_setting_exists($config_name, $user_id) {
static $user_setting_values = array();
if (!isset($user_setting_values[$config_name])) {
$value = 0;
if (db_table_exists('settings_user')) {
$value = db_fetch_cell_prepared('SELECT COUNT(*)
FROM settings_user
WHERE name = ?
AND user_id = ?',
array($config_name, $user_id));
}
if ($value !== false && $value > 0) {
$user_setting_values[$config_name] = true;
} else {
$user_setting_values[$config_name] = false;
}
}
return $user_setting_values[$config_name];
}
/**
* clear_user_setting - if a value exists for the current user/setting specified, removes it
*
* @param $config_name - the name of the configuration setting as specified $settings_user array
* in 'include/global_settings.php'
* @param $user_id - the id of the user to remove the configuration value for
*/
function clear_user_setting($config_name, $user = -1) {
global $settings_user;
if ($user == -1) {
$user = $_SESSION['sess_user_id'];
}
if (db_table_exists('settings_user')) {
db_execute_prepared('DELETE FROM settings_user
WHERE name = ?
AND user_id = ?',
array($config_name, $user));
}
unset($_SESSION['sess_user_config_array']);
}
/**
* read_default_user_setting - finds the default value of a user configuration setting
*
* @param $config_name - the name of the configuration setting as specified $settings array
* in 'include/global_settings.php'
*
* @return - the default value of the configuration option
*/
function read_default_user_setting($config_name) {
global $config, $settings_user;
foreach ($settings_user as $tab_array) {
if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) {
return $tab_array[$config_name]['default'];
} else {
foreach ($tab_array as $field_array) {
if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) {
return $field_array['items'][$config_name]['default'];
}
}
}
}
}
/**
* read_user_setting - finds the current value of a graph configuration setting
*
* @param $config_name - the name of the configuration setting as specified $settings_user array
* in 'include/global_settings.php'
* @param $default - the default value is none is set
* @param $force - pull the data from the database if true ignoring session
* @param $user - assume this user's identity
*
* @return - the current value of the user setting
*/
function read_user_setting($config_name, $default = false, $force = false, $user = 0) {
global $config;
/* users must have cacti user auth turned on to use this, or the guest account must be active */
if ($user == 0 && isset($_SESSION['sess_user_id'])) {
$effective_uid = $_SESSION['sess_user_id'];
} elseif (read_config_option('auth_method') == 0 || $user > 0) {
/* first attempt to get the db setting for guest */
if ($user == 0) {
$effective_uid = db_fetch_cell("SELECT user_auth.id
FROM settings
INNER JOIN user_auth
ON user_auth.username = settings.value
WHERE settings.name = 'guest_user'");
if ($effective_uid == '') {
$effective_uid = 0;
}
} else {
$effective_uid = $user;
}
$db_setting = false;
if (db_table_exists('settings_user')) {
$db_setting = db_fetch_row_prepared('SELECT value
FROM settings_user
WHERE name = ?
AND user_id = ?',
array($config_name, $effective_uid));
}
if (cacti_sizeof($db_setting)) {
return $db_setting['value'];
} elseif ($default !== false) {
return $default;
} else {
return read_default_user_setting($config_name);
}
} else {
$effective_uid = 0;
}
if (!$force) {
if (isset($_SESSION['sess_user_config_array'])) {
$user_config_array = $_SESSION['sess_user_config_array'];
}
}
if (!isset($user_config_array[$config_name])) {
$db_setting = false;
if (db_table_exists('settings_user')) {
$db_setting = db_fetch_row_prepared('SELECT value
FROM settings_user
WHERE name = ?
AND user_id = ?',
array($config_name, $effective_uid));
}
if (cacti_sizeof($db_setting)) {
$user_config_array[$config_name] = $db_setting['value'];
} elseif ($default !== false) {
$user_config_array[$config_name] = $default;
} else {
$user_config_array[$config_name] = read_default_user_setting($config_name);
}
if (isset($_SESSION)) {
$_SESSION['sess_user_config_array'] = $user_config_array;
} else {
$config['config_user_settings_array'] = $user_config_array;
}
}
return $user_config_array[$config_name];
}
/**
* is_remote_path_setting - determines of a Cacti setting should be maintained
* on the Remote Data Collector separate from the Main cacti server
*
* @param $config_name - the name of the configuration setting as specified $settings array
*
* @return (bool) - true if the setting should be saved locally
*/
function is_remote_path_setting($config_name) {
global $config;
if ($config['poller_id'] > 1 && (strpos($config_name, 'path_') !== false || strpos($config_name, '_path') !== false)) {
return true;
} else {
return false;
}
}
/**
* set_config_option - sets/updates a cacti config option with the given value.
*
* @param $config_name - the name of the configuration setting as specified $settings array
* @param $value - the values to be saved
* @param $remote - push the setting to the remote with the exception of path variables
*
* @return (void)
*/
function set_config_option($config_name, $value, $remote = false) {
global $config;
include_once($config['base_path'] . '/lib/poller.php');
if (strlen($config_name) > 75) {
cacti_log("ERROR: Config option name '$config_name' is too long, will be truncated", false, 'SYSTEM');
}
db_execute_prepared('REPLACE INTO settings
SET name = ?, value = ?',
array($config_name, $value));
if ($remote && !is_remote_path_setting($config_name)) {
$gone_time = read_config_option('poller_interval') * 2;
$pollers = array_rekey(
db_fetch_assoc('SELECT
id,
UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_status) AS last_polled
FROM poller
WHERE id > 1
AND disabled=""'),
'id', 'last_polled'
);
$sql = 'INSERT INTO settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)';
foreach($pollers as $p => $t) {
if ($t > $gone_time) {
raise_message('poller_' . $p, __('Settings save to Data Collector %d skipped due to heartbeat.', $p), MESSAGE_LEVEL_WARN);
} else {
$rcnn_id = poller_connect_to_remote($p);
if ($rcnn_id) {
if (db_execute_prepared($sql, array($config_name, $value), false, $rcnn_id) === false) {
$rcnn_id = false;
}
}
// check if we still have rcnn_id, if it's now become false, we had a problem
if (!$rcnn_id) {
raise_message('poller_' . $p, __('Settings save to Data Collector %d Failed.', $p), MESSAGE_LEVEL_ERROR);
}
}
}
}
$config_array = array();
if ($config['is_web']) {
$sess = true;
} else {
$sess = false;
}
// Store the array back for later retrieval
if ($sess) {
$_SESSION['sess_config_array'] = $value;
} else {
$config['config_options_array'] = $value;
}
if (!empty($config['DEBUG_SET_CONFIG_OPTION'])) {
file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND);
}
}
/**
* config_value_exists - determines if a value exists for the current user/setting specified
*
* @param $config_name - the name of the configuration setting as specified $settings array
* in 'include/global_settings.php'
*
* @return - true if a value exists, false if a value does not exist
*/
function config_value_exists($config_name) {
static $config_values = array();
if (!isset($config_values[$config_name])) {
$value = db_fetch_cell_prepared('SELECT COUNT(*) FROM settings WHERE name = ?', array($config_name));
if ($value > 0) {
$config_values[$config_name] = true;
} else {
$config_values[$config_name] = false;
}
}
return $config_values[$config_name];
}
/**
* read_default_config_option - finds the default value of a Cacti configuration setting
*
* @param $config_name - the name of the configuration setting as specified $settings array
* in 'include/global_settings.php'
*
* @return - the default value of the configuration option
*/
function read_default_config_option($config_name) {
global $config, $settings;
if (isset($settings) && is_array($settings)) {
foreach ($settings as $tab_array) {
if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) {
return $tab_array[$config_name]['default'];
} else {
foreach ($tab_array as $field_array) {
if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) {
return $field_array['items'][$config_name]['default'];
}
}
}
}
}
}
function prime_common_config_settings() {
global $config;
//$start = microtime(true);
$common_settings = array(
'auth_method',
'auth_cache_enabled',
'path_cactilog',
'rrdtool_version',
'log_verbosity',
'log_destination',
'default_image_format',
'default_graph_width',
'default_graph_height',
'default_datechar',
'default_date_format',
'default_poller',
'default_site',
'i18n_language_support',
'i18n_default_language',
'reports_allow_ln',
// Common page rendering
'selective_debug',
'selected_theme',
'min_tree_width',
'max_tree_width',
);
if ($config['is_web']) {
$extra_settings = array(
// Common all pages
'force_https',
'content_security_policy_script',
'content_security_alternate_sources',
'deletion_verification',
// Common graphing
'rrdtool_watermark',
'realtime_cache_path',
'path_rrdtool',
'hide_disabled',
'graph_watermark',
'graph_dateformat',
'font_method',
'date',
'boost_rrd_update_system_enable',
'boost_rrd_update_max_records_per_select',
'boost_rrd_update_enable',
'boost_png_cache_enable',
'remote_storage_method',
);
} else {
$extra_settings = array(
// Common polling
'poller_interval',
'snmp_version',
'snmp_username',
'snmp_timeout',
'snmp_community',
'snmp_auth_protocol',
'snmp_security_level',
'snmp_priv_protocol',
'snmp_priv_passphrase',
'snmp_port',
'snmp_password',
'snmp_retries',
'device_threads',
'max_get_size',
'availability_method',
'ping_method',
'ping_port',
'ping_retries',
'ping_timeout',
'path_snmpbulkwalk',
'path_snmpwalk',
'path_snmpget',
'path_spine',
// Common API
'default_template',
'delete_verification',
// Thold
'alert_bl_trigger',
'alert_deadnotify',
'alert_email',
'alert_exempt',
'alert_repeat',
'alert_trigger',
'base_url',
'thold_alert_snmp_warning',
'thold_alert_snmp_normal',
'thold_alert_snmp',
'thold_daemon_debug',
'thold_disable_all',
'thold_log_debug',
'thold_send_text_only',
'thold_show_datasource',
);
}
$common_settings = array_merge($common_settings, $extra_settings);
$settings = array_rekey(
db_fetch_assoc_prepared('SELECT name, value
FROM settings
WHERE name IN (' . trim(str_repeat('?, ', cacti_sizeof($common_settings)),', ') . ')',
$common_settings),
'name', 'value'
);
if (isset($_SESSION['sess_config_array'])) {
$sess = true;
} else {
$sess = false;
}
if (cacti_sizeof($settings)) {
foreach($settings as $name => $value) {
if ($sess) {
$_SESSION['sess_config_array'][$name] = $value;
} else {
$config['config_options_array'][$name] = $value;
}
}
}
//$end = microtime(true);
//cacti_log('The Total common load time:' . round($end - $start, 4));
}
/**
* Finds the current value of a Cacti configuration setting
*
* @param $config_name The name of the configuration setting as specified
* as a key in $settings array in
* 'include/global_settings.php'
*
* @return string|false The current value of the configuration option
*/
function read_config_option($config_name, $force = false) {
global $config, $database_hostname, $database_default, $database_port, $database_sessions;
$loaded = false;
if ($config['is_web']) {
$sess = true;
if (isset($_SESSION['sess_config_array'][$config_name])) {
$loaded = true;
}
} else {
$sess = false;
if (isset($config['config_options_array'][$config_name])) {
$loaded = true;
}
}
if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) {
file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND);
}
// Do we have a value already stored in the array, or
// do we want to make sure we have the latest value
// from the database?
if (!$loaded || $force) {
// We need to check against the DB, but lets assume default value
// unless we can actually read the DB
$value = read_default_config_option($config_name);
if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) {
file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() .
" $config_name: " .
' dh: ' . isset($database_hostname) .
' dp: ' . isset($database_port) .
' dd: ' . isset($database_default) .
' ds: ' . isset($database_sessions["$database_hostname:$database_port:$database_default"]) .
"\n", FILE_APPEND);
if (isset($database_hostname) && isset($database_port) && isset($database_default)) {
file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() .
" $config_name: [$database_hostname:$database_port:$database_default]\n", FILE_APPEND);
}
}
// Are the database variables set, and do we have a connection??
// If we don't, we'll only use the default value without storing
// so that we can read the database version later.
if (isset($database_hostname) && isset($database_port) && isset($database_default) &&
isset($database_sessions["$database_hostname:$database_port:$database_default"])) {
// Get the database setting
$db_result = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array($config_name), false);
if (cacti_sizeof($db_result)) {
$value = $db_result['value'];
}
// Store whatever value we have in the array
if ($sess) {
if (!isset($_SESSION['sess_config_array']) || !is_array($_SESSION['sess_config_array'])) {
$_SESSION['sess_config_array'] = array();
}
$_SESSION['sess_config_array'][$config_name] = $value;
} else {
if (!isset($config['config_options_array']) || !is_array($config['config_options_array'])) {
$config['config_options_array'] = array();
}
$config['config_options_array'][$config_name] = $value;
}
}
} else {
// We already have the value stored in the array and
// we don't want to force a db read, so use the cached
// version
if ($sess) {
$value = $_SESSION['sess_config_array'][$config_name];
} else {
$value = $config['config_options_array'][$config_name];
}
}
return $value;
}
/**
* get_selected_theme - checks the user settings and if the user selected
* theme is set, returns it otherwise returns the system default.
*
* @return - the theme name
*/
function get_selected_theme() {
global $config, $themes;
// shortcut if theme is set in session
if (isset($_SESSION['selected_theme'])) {
if (file_exists($config['base_path'] . '/include/themes/' . $_SESSION['selected_theme'] . '/main.css')) {
return $_SESSION['selected_theme'];
}
}
// default to system selected theme
$theme = read_config_option('selected_theme');
// check for a pre-1.x cacti being upgraded
if ($theme == '' && !db_table_exists('settings_user')) {
return 'modern';
}
// figure out user defined theme
if (isset($_SESSION['sess_user_id'])) {
// fetch user defined theme
$user_theme = db_fetch_cell_prepared("SELECT value
FROM settings_user
WHERE name='selected_theme'
AND user_id = ?",
array($_SESSION['sess_user_id']), '', false);
// user has a theme
if (!empty($user_theme)) {
$theme = $user_theme;;
}
}
if (!file_exists($config['base_path'] . '/include/themes/' . $theme . '/main.css')) {
foreach($themes as $t => $name) {
if ($t != 'classic') {
if (file_exists($config['base_path'] . '/include/themes/' . $t . '/main.css')) {
$theme = $t;
db_execute_prepared('UPDATE settings_user
SET value = ?
WHERE user_id = ?
AND name = "selected_theme"',
array($theme, $_SESSION['sess_user_id']));
break;
}
}
}
}
// update session
$_SESSION['selected_theme'] = $theme;
return $theme;
}
/**
* form_input_validate - validates the value of a form field and Takes the appropriate action if the input
* is not valid
*
* @param string $field_value value of the form field
* @param string $field_name name of the $_POST field as specified in the HTML
* @param string $regexp_match (optionally) enter a regular expression to match the value against
* @param bool $allow_nulls whether to allow an empty string as a value or not
* @param int $custom_message the ID of the message to raise upon an error which is defined in the
* $messages array in 'include/global_arrays.php'
*
* @return string the original $field_value
*/
function form_input_validate($field_value, $field_name, $regexp_match, $allow_nulls, $custom_message = 3) {
global $messages;
/* write current values to the "field_values" array so we can retain them */
$_SESSION['sess_field_values'][$field_name] = $field_value;
if (($allow_nulls == true) && ($field_value == '')) {
return $field_value;
}
if ($allow_nulls == false && $field_value == '') {
if (read_config_option('log_validation') == 'on') {
cacti_log("Form Validation Failed: Variable '$field_name' does not allow nulls and variable is null", false);
}
raise_message($custom_message);
$_SESSION['sess_error_fields'][$field_name] = $field_name;
} elseif ($regexp_match != '' && !preg_match('/' . $regexp_match . '/', $field_value)) {
if (read_config_option('log_validation') == 'on') {
cacti_log("Form Validation Failed: Variable '$field_name' with Value '$field_value' Failed REGEX '$regexp_match'", false);
cacti_debug_backtrace('REGEX FAILURE');
}
raise_message($custom_message);
$_SESSION['sess_error_fields'][$field_name] = $field_name;
}
return $field_value;
}
/**
* check_changed - determines if a request variable has changed between page loads
*
* @return - true if the value changed between loads
*/
function check_changed($request, $session) {
if ((isset_request_var($request)) && (isset($_SESSION[$session]))) {
if (get_nfilter_request_var($request) != $_SESSION[$session]) {
return 1;
}
}
}
/**
* is_error_message - finds whether an error message has been raised and has not been outputted to the
* user
*
* @return - whether the messages array contains an error or not
*/
function is_error_message() {
global $config, $messages;
if (isset($_SESSION['sess_error_fields']) && cacti_sizeof($_SESSION['sess_error_fields'])) {
return true;
} else {
return false;
}
}
function get_message_level($current_message) {
$current_level = MESSAGE_LEVEL_NONE;
if (isset($current_message['level'])) {
$current_level = $current_message['level'];
} elseif (isset($current_message['type'])) {
switch ($current_message['type']) {
case 'error':
$current_level = MESSAGE_LEVEL_ERROR;
break;
case 'info':
$current_level = MESSAGE_LEVEL_INFO;
break;
}
}
return $current_level;
}
/**
* get_format_message_instance - finds the level of the current message instance
*
* @param message array the message instance
*
* @return - a formatted message
*/
function get_format_message_instance($current_message) {
if (is_array($current_message)) {
$fmessage = isset($current_message['message']) ? $current_message['message'] : __esc('Message Not Found.');
} else {
$fmessage = $current_message;
}
$level = get_message_level($current_message);
switch ($level) {
case MESSAGE_LEVEL_NONE:
$message = '<span>' . $fmessage . '</span>';
break;
case MESSAGE_LEVEL_INFO:
$message = '<span class="deviceUp">' . $fmessage . '</span>';
break;
case MESSAGE_LEVEL_WARN:
$message = '<span class="deviceWarning">' . $fmessage . '</span>';
break;
case MESSAGE_LEVEL_ERROR:
$message = '<span class="deviceDown">' . $fmessage . '</span>';
break;
case MESSAGE_LEVEL_CSRF:
$message = '<span class="deviceDown">' . $fmessage . '</span>';
break;
default;
$message = '<span class="deviceUnknown">' . $fmessage . '</span>';
break;
}
return $message;
}
/**
* get_message_max_type - finds the message and returns its type
*
* @return - the message type 'info', 'warn', 'error' or 'csrf'
*/
function get_message_max_type() {
global $messages;
$level = MESSAGE_LEVEL_NONE;
if (isset($_SESSION['sess_messages'])) {
if (is_array($_SESSION['sess_messages'])) {
foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) {
$current_level = get_message_level($current_message);
if ($current_level == MESSAGE_LEVEL_NONE && isset($messages[$current_message_id])) {
$current_level = get_message_level($messages[$current_message_id]);
}
if ($current_level != $level && $level != MESSAGE_LEVEL_NONE) {
$level = MESSAGE_LEVEL_MIXED;
} else {
$level = $current_level;
}
}
}
}
return $level;
}
/**
* raise_message - mark a message to be displayed to the user once display_output_messages() is called
*
* @param $message_id - the ID of the message to raise as defined in $messages in 'include/global_arrays.php'
*/
function raise_message($message_id, $message = '', $message_level = MESSAGE_LEVEL_NONE) {
global $config, $messages, $no_http_headers;
// This function should always exist, if not its an invalid install
if (function_exists('session_status')) {
$need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers));
} else {
return false;
}
if (empty($message)) {
if (array_key_exists($message_id, $messages)) {
$predefined = $messages[$message_id];
if (isset($predefined['message'])) {
$message = $predefined['message'];
} else {
$message = $predefined;
}
if ($message_level == MESSAGE_LEVEL_NONE) {
$message_level = get_message_level($predefined);
}
} elseif (isset($_SESSION[$message_id])) {
$message = $_SESSION[$message_id];
$message_level = MESSAGE_LEVEL_ERROR;
} else {
$message = __('Message Not Found.');
$message_level = MESSAGE_LEVEL_ERROR;
}
}
if ($need_session) {
cacti_session_start();
}
if (!isset($_SESSION['sess_messages'])) {
$_SESSION['sess_messages'] = array();
}
$_SESSION['sess_messages'][$message_id] = array('message' => $message, 'level' => $message_level);
if ($need_session) {
cacti_session_close();
}
}
/**
* raise_message_javascript - raises a message that will appear in the UI
* as the result of an server side error that can not be captured
* normally.
*
* @param (string) The title for the dialog title bar
* @param (string) Header section for the message
* @param (string) The actual error message to display
*
* @return (void)
*/
function raise_message_javascript($title, $header, $message) {
?>
<script type='text/javascript'>
var mixedReasonTitle = DOMPurify.sanitize(<?php print json_encode($title, JSON_THROW_ON_ERROR);?>);
var mixedOnPage = DOMPurify.sanitize(<?php print json_encode($header, JSON_THROW_ON_ERROR);?>);
sessionMessage = {
message: DOMPurify.sanitize(<?php print json_encode($message, JSON_THROW_ON_ERROR);?>),
level: MESSAGE_LEVEL_MIXED
};
$(function() {
displayMessages();
});
</script>
<?php
exit;
}
/**
* display_output_messages - displays all of the cached messages from the raise_message() function and clears
* the message cache
*/
function display_output_messages() {
global $messages;
$omessage = array();
$debug_message = debug_log_return('new_graphs');
if ($debug_message != '') {
$omessage['level'] = MESSAGE_LEVEL_NONE;
$omessage['message'] = $debug_message;
debug_log_clear('new_graphs');
} elseif (isset($_SESSION['sess_messages'])) {
if (!is_array($_SESSION['sess_messages'])) {
$_SESSION['sess_messages'] = array('custom_error' => array('level' => 3, 'message' => $_SESSION['sess_messages']));
}
$omessage['level'] = get_message_max_type();
foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) {
$message = get_format_message_instance($current_message);
if (!empty($message)) {
$omessage['message'] = (isset($omessage['message']) && $omessage['message'] != '' ? $omessage['message'] . '<br>':'') . $message;
} else {
cacti_log("ERROR: Cacti Error Message Id '$current_message_id' Not Defined", false, 'WEBUI');
}
}
}
clear_messages();
return json_encode($omessage);
}
function display_custom_error_message($message) {
raise_message('custom_error', $message);
}
/**
* clear_messages - clears the message cache
*/
function clear_messages() {
// This function should always exist, if not its an invalid install
if (function_exists('session_status')) {
$need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers));
} else {
return false;
}
if ($need_session) {
cacti_session_start();
}
kill_session_var('sess_error_fields');
kill_session_var('sess_messages');
if ($need_session) {
cacti_session_close();
}
}
/**
* kill_session_var - kills a session variable using unset()
*/
function kill_session_var($var_name) {
/* register_global = on: reset local settings cache so the user sees the new settings */
unset($_SESSION[$var_name]);
/* register_global = off: reset local settings cache so the user sees the new settings */
/* session_unregister is deprecated in PHP 5.3.0, unset is sufficient */
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
session_unregister($var_name);
} else {
unset($var_name);
}
}
/**
* force_session_data - forces session data into the session if the session was closed for some reason
*/
function force_session_data() {
// This function should always exist, if not its an invalid install
if (!function_exists('session_status')) {
return false;
} elseif (session_status() == PHP_SESSION_NONE) {
$data = $_SESSION;
cacti_session_start();
$_SESSION = $data;
cacti_session_close();
}
}
/**
* array_rekey - changes an array in the form:
*
* '$arr[0] = array('id' => 23, 'name' => 'blah')' to the form
* '$arr = array(23 => 'blah')'
*
* @param array $array The original array to manipulate
* @param string $key The name of the key
* @param string $key_value The name of the key value
*
* @return array the modified array
*/
function array_rekey($array, $key, $key_value) {
$ret_array = array();
if (is_array($array)) {
foreach ($array as $item) {
$item_key = $item[$key];
if (is_array($key_value)) {
foreach ($key_value as $value) {
$ret_array[$item_key][$value] = $item[$value];
}
} else {
$ret_array[$item_key] = $item[$key_value];
}
}
}
return $ret_array;
}
/**
* cacti_log_file - returns the log filename
*/
function cacti_log_file() {
global $config;
$logfile = read_config_option('path_cactilog');
if ($logfile == '') {
$logfile = $config['base_path'] . '/log/cacti.log';
}
$config['log_path'] = $logfile;
return $logfile;
}
function get_selective_log_level() {
static $force_level = null;
if ($force_level !== null) {
return $force_level;
}
if (isset($_SERVER['PHP_SELF'])) {
$current_file = basename($_SERVER['PHP_SELF']);
$dir_name = dirname($_SERVER['PHP_SELF']);
} elseif (isset($_SERVER['SCRIPT_NAME'])) {
$current_file = basename($_SERVER['SCRIPT_NAME']);
$dir_name = dirname($_SERVER['SCRIPT_NAME']);
} elseif (isset($_SERVER['SCRIPT_FILENAME'])) {
$current_file = basename($_SERVER['SCRIPT_FILENAME']);
$dir_name = dirname($_SERVER['SCRIPT_FILENAME']);
} else {
$current_file = basename(__FILE__);
$dir_name = dirname(__FILE__);
}
$force_level = '';
$debug_files = read_config_option('selective_debug');
if ($debug_files != '') {
$files = explode(',', $debug_files);
if (array_search($current_file, $files) !== false) {
$force_level = POLLER_VERBOSITY_DEBUG;
}
}
if (strpos($dir_name, 'plugins') !== false) {
$debug_plugins = read_config_option('selective_plugin_debug');
if ($debug_plugins != '') {
$debug_plugins = explode(',', $debug_plugins);
foreach($debug_plugins as $myplugin) {
if (strpos($dir_name, DIRECTORY_SEPARATOR . $myplugin) !== false) {
$force_level = POLLER_VERBOSITY_DEBUG;
break;
}
}
}
}
return $force_level;
}
/**
* cacti_log - logs a string to Cacti's log file or optionally to the browser
*
* @param $string - the string to append to the log file
* @param $output - (bool) whether to output the log line to the browser using print() or not
* @param $environ - (string) tells from where the script was called from
* @param $level - (int) only log if above the specified log level
*/
function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') {
global $config, $database_log;
static $start = null;
if ($start == null) {
$start = microtime(true);
}
if (!isset($database_log)) {
$database_log = false;
}
if (trim($string) == '') {
return false;
}
$last_log = $database_log;
$database_log = false;
$force_level = get_selective_log_level();
$oprefix = '';
$omessage = '';
/* only log if the specific level is reached, developer debug is special low + specific devdbg calls */
if ($force_level == '') {
if ($level != '') {
$logVerbosity = read_config_option('log_verbosity');
if ($logVerbosity == POLLER_VERBOSITY_DEVDBG) {
if ($level != POLLER_VERBOSITY_DEVDBG) {
if ($level > POLLER_VERBOSITY_LOW) {
$database_log = $last_log;
return;
}
}
} elseif ($level > $logVerbosity) {
$database_log = $last_log;
return;
}
}
}
cacti_system_zone_set();
/* fill in the current date for printing in the log */
if (defined('CACTI_DATE_TIME_FORMAT')) {
$date = date(CACTI_DATE_TIME_FORMAT);
} else {
$date = date('Y-m-d H:i:s');
}
cacti_browser_zone_set();
/* determine how to log data */
$logdestination = read_config_option('log_destination');
$logfile = cacti_log_file();
/* format the message */
if ($environ == 'POLLER') {
$prefix = "$date - " . $environ . ': Poller[' . $config['poller_id'] . '] PID[' . getmypid() . '] ';
if ($output) {
$oprefix = sprintf('Total[%3.4f] ', microtime(true) - $start);
}
} else {
$prefix = "$date - " . $environ . ' ';
if ($output) {
$oprefix = $prefix;
}
}
/* Log to Logfile */
$message = clean_up_lines($string) . PHP_EOL;
if ($output) {
$omessage = $oprefix . $message;
}
if (($logdestination == 1 || $logdestination == 2) && read_config_option('log_verbosity') != POLLER_VERBOSITY_NONE) {
/* print the data to the log (append) */
$fp = @fopen($logfile, 'a');
if ($fp) {
$message = $prefix . $message;
@fwrite($fp, $message);
fclose($fp);
}
}
/* Log to Syslog/Eventlog */
/* Syslog is currently Unstable in Win32 */
if ($logdestination == 2 || $logdestination == 3) {
$log_type = '';
if (strpos($string, 'ERROR:') !== false) {
$log_type = 'err';
} elseif (strpos($string, 'WARNING:') !== false) {
$log_type = 'warn';
} elseif (strpos($string, 'STATS:') !== false) {
$log_type = 'stat';
} elseif (strpos($string, 'NOTICE:') !== false) {
$log_type = 'note';
}
if ($log_type != '') {
if ($config['cacti_server_os'] == 'win32') {
openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_USER);
} else {
openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_SYSLOG);
}
if ($log_type == 'err' && read_config_option('log_perror')) {
syslog(LOG_CRIT, $environ . ': ' . $string);
} elseif ($log_type == 'warn' && read_config_option('log_pwarn')) {
syslog(LOG_WARNING, $environ . ': ' . $string);
} elseif (($log_type == 'stat' || $log_type == 'note') && read_config_option('log_pstats')) {
syslog(LOG_INFO, $environ . ': ' . $string);
}
closelog();
}
}
/* print output to standard out if required */
if ($output == true && isset($_SERVER['argv'][0])) {
print $omessage;
}
$database_log = $last_log;
}
/**
* tail_file - Emulates the tail function with PHP native functions.
* It is used in 0.8.6 to speed the viewing of the Cacti log file, which
* can be problematic in the 0.8.6 branch.
*
* @param $file_name - (char constant) the name of the file to tail
* @param $line_cnt - (int constant) the number of lines to count
* @param $message_type - (int constant) the type of message to return
* @param $filter - (char) the filtering expression to search for
* @param $page_nr - (int) the page we want to show rows for
* @param $total_rows - (int) the total number of rows in the logfile
* @param $matches - (bool) match or does not match the filter
*/
function tail_file($file_name, $number_of_lines, $message_type = -1, $filter = '', &$page_nr = 1, &$total_rows = 0, $matches = true) {
if (!file_exists($file_name)) {
touch($file_name);
return array();
}
if (!is_readable($file_name)) {
return array(__('Error %s is not readable', $file_name));
}
$filter = strtolower($filter);
$fp = fopen($file_name, 'r');
/* Count all lines in the logfile */
$total_rows = 0;
while (($line = fgets($fp)) !== false) {
if (determine_display_log_entry($message_type, $line, $filter, $matches)) {
++$total_rows;
}
}
// Reset the page count to 1 if the number of lines is exceeded
if (($page_nr - 1) * $number_of_lines > $total_rows) {
set_request_var('page', 1);
$page_nr = 1;
}
/* rewind file pointer, to start all over */
rewind($fp);
$start = $total_rows - ($page_nr * $number_of_lines);
$end = $start + $number_of_lines;
if ($start < 0) {
$start = 0;
}
force_session_data();
/* load up the lines into an array */
$file_array = array();
$i = 0;
while (($line = fgets($fp)) !== false) {
$display = determine_display_log_entry($message_type, $line, $filter, $matches);
if ($display === false) {
continue;
}
if ($i < $start) {
++$i;
continue;
}
if ($i >= $end) {
break;
}
++$i;
$file_array[$i] = $line;
}
fclose($fp);
return $file_array;
}
/**
* determine_display_log_entry - function to determine if we display the line
*
* @param $message_type
* @param $line
* @param $filter
* @param $matches
*
* @return - should the entry be displayed
*/
function determine_display_log_entry($message_type, $line, $filter, $matches = true) {
static $thold_enabled = null;
if ($thold_enabled == null) {
$thold_enabled = api_plugin_is_enabled('thold');
}
/* determine if we are to display the line */
switch ($message_type) {
case 1: /* stats only */
$display = (strpos($line, 'STATS') !== false);
break;
case 2: /* warnings only */
$display = (strpos($line, 'WARN') !== false);
break;
case 3: /* warnings + */
$display = (strpos($line, 'WARN') !== false);
if (!$display) {
$display = (strpos($line, 'ERROR') !== false);
}
if (!$display) {
$display = (strpos($line, 'DEBUG') !== false);
}
if (!$display) {
$display = (strpos($line, ' SQL') !== false);
}
break;
case 4: /* errors only */
$display = (strpos($line, 'ERROR') !== false);
break;
case 5: /* errors + */
$display = (strpos($line, 'ERROR') !== false);
if (!$display) {
$display = (strpos($line, 'DEBUG') !== false);
}
if (!$display) {
$display = (strpos($line, ' SQL') !== false);
}
break;
case 6: /* debug only */
$display = (strpos($line, 'DEBUG') !== false && strpos($line, ' SQL ') === false);
break;
case 7: /* sql calls only */
$display = (strpos($line, ' SQL ') !== false);
break;
case 8: /* AutoM8 Only */
$display = (strpos($line, 'AUTOM8') !== false);
break;
case 9: /* Non Stats */
$display = (strpos($line, 'STATS') === false);
break;
case 10: /* Boost Only*/
$display = (strpos($line, 'BOOST') !== false);
break;
case 11: /* device events + */
$display = (strpos($line, 'HOST EVENT') !== false);
if (!$display) {
$display = (strpos($line, '] is recovering!') !== false);
}
if (!$display) {
$display = (strpos($line, '] is down!') !== false);
}
break;
case 12: /* Assertions */
$display = (strpos($line, 'ASSERT FAILED') !== false);
if (!$display) {
$display = (strpos($line, 'Recache Event') !== false);
}
break;
case -1: /* all */
$display = true;
break;
default: /* all other lines */
if ($thold_enabled) {
if ($message_type == 99) {
$display = (strpos($line, 'THOLD: Threshold') !== false);
}
} else {
$display = true;
}
}
/* match any lines that match the search string */
if ($display === true && $filter != '') {
if ($matches) {
if (validate_is_regex($filter) && preg_match('/' . $filter . '/i', $line)) {
return $line;
} elseif (stripos($line, $filter) !== false) {
return $line;
}
} else {
if (validate_is_regex($filter)) {
if (!preg_match('/' . $filter . '/i', $line)) {
return $line;
}
} elseif (!stripos($line, $filter) !== false) {
return $line;
}
}
return false;
}
return $display;
}
/**
* update_host_status - updates the host table with information about its status.
* It will also output to the appropriate log file when an event occurs.
*
* @param $status - (int constant) the status of the host (Up/Down)
* @param $host_id - (int) the host ID for the results
* @param $ping - (class array) results of the ping command.
*/
function update_host_status($status, $host_id, &$ping, $ping_availability, $print_data_to_stdout) {
$issue_log_message = false;
$ping_failure_count = read_config_option('ping_failure_count');
$ping_recovery_count = read_config_option('ping_recovery_count');
$host = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
/* initialize fail and recovery dates correctly */
if ($host['status_fail_date'] == '') {
$host['status_fail_date'] = 0;
} else {
$host['status_fail_date'] = strtotime($host['status_fail_date']);;
}
if ($host['status_rec_date'] == '') {
$host['status_rec_date'] = 0;
} else {
$host['status_rec_date'] = strtotime($host['status_rec_date']);;
}
if ($status == HOST_DOWN) {
/* Set initial date down. BUGFIX */
if (empty($host['status_fail_date'])) {
$host['status_fail_date'] = time();
}
/* update total polls, failed polls and availability */
$host['failed_polls']++;
$host['total_polls']++;
$host['availability'] = 100 * ($host['total_polls'] - $host['failed_polls']) / $host['total_polls'];
/* determine the error message to display */
if (($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING)) {
if (($host['snmp_community'] == '') && ($host['snmp_version'] != 3)) {
/* snmp version 1/2 without community string assume SNMP test to be successful
due to backward compatibility issues */
$host['status_last_error'] = $ping->ping_response;
} else {
$host['status_last_error'] = $ping->snmp_response . ', ' . $ping->ping_response;
}
} elseif ($ping_availability == AVAIL_SNMP) {
if (($host['snmp_community'] == '') && ($host['snmp_version'] != 3)) {
$host['status_last_error'] = 'Device does not require SNMP';
} else {
$host['status_last_error'] = $ping->snmp_response;
}
} else {
$host['status_last_error'] = $ping->ping_response;
}
/* determine if to send an alert and update remainder of statistics */
if ($host['status'] == HOST_UP) {
/* increment the event failure count */
$host['status_event_count']++;
/* if it's time to issue an error message, indicate so */
if ($host['status_event_count'] >= $ping_failure_count) {
/* host is now down, flag it that way */
$host['status'] = HOST_DOWN;
$issue_log_message = true;
$host['status_fail_date'] = time();
$host['status_event_count'] = 0;
}
} elseif ($host['status'] == HOST_RECOVERING) {
/* host is recovering, put back in failed state */
$host['status_event_count'] = 1;
$host['status'] = HOST_DOWN;
} elseif ($host['status'] == HOST_UNKNOWN) {
/* host was unknown and now is down */
$host['status'] = HOST_DOWN;
$host['status_event_count'] = 0;
} else {
$host['status_event_count']++;
}
} else {
/* host is up. Update total polls and availability */
$host['total_polls']++;
$host['availability'] = 100 * ($host['total_polls'] - $host['failed_polls']) / $host['total_polls'];
if ((($ping_availability == AVAIL_SNMP_AND_PING) ||
($ping_availability == AVAIL_SNMP_OR_PING) ||
($ping_availability == AVAIL_SNMP)) &&
(!is_numeric($ping->snmp_status))) {
$ping->snmp_status = 0.000;
}
if ((($ping_availability == AVAIL_SNMP_AND_PING) ||
($ping_availability == AVAIL_SNMP_OR_PING) ||
($ping_availability == AVAIL_PING)) &&
(!is_numeric($ping->ping_status))) {
$ping->ping_status = 0.000;
}
/* determine the ping statistic to set and do so */
if (($ping_availability == AVAIL_SNMP_AND_PING) ||
($ping_availability == AVAIL_SNMP_OR_PING)) {
if (($host['snmp_community'] == '') && ($host['snmp_version'] != 3)) {
$ping_time = 0.000;
} else {
/* calculate the average of the two times */
$ping_time = ($ping->snmp_status + $ping->ping_status) / 2;
}
} elseif ($ping_availability == AVAIL_SNMP) {
if (($host['snmp_community'] == '') && ($host['snmp_version'] != 3)) {
$ping_time = 0.000;
} else {
$ping_time = $ping->snmp_status;
}
} elseif ($ping_availability == AVAIL_NONE) {
$ping_time = 0.000;
} else {
$ping_time = $ping->ping_status;
}
/* update times as required */
if (is_numeric($ping_time)) {
$host['cur_time'] = $ping_time;
/* maximum time */
if ($ping_time > $host['max_time']) {
$host['max_time'] = $ping_time;
}
/* minimum time */
if ($ping_time < $host['min_time']) {
$host['min_time'] = $ping_time;
}
/* average time */
$host['avg_time'] = (($host['total_polls'] - 1 - $host['failed_polls'])
* $host['avg_time'] + $ping_time) / ($host['total_polls'] - $host['failed_polls']);
}
/* the host was down, now it's recovering */
if ($host['status'] == HOST_DOWN || $host['status'] == HOST_RECOVERING) {
/* just up, change to recovering */
if ($host['status'] == HOST_DOWN) {
$host['status'] = HOST_RECOVERING;
$host['status_event_count'] = 1;
} else {
$host['status_event_count']++;
}
/* if it's time to issue a recovery message, indicate so */
if ($host['status_event_count'] >= $ping_recovery_count) {
/* host is up, flag it that way */
$host['status'] = HOST_UP;
$issue_log_message = true;
$host['status_rec_date'] = time();
$host['status_event_count'] = 0;
}
} else {
/* host was unknown and now is up */
$host['status'] = HOST_UP;
$host['status_event_count'] = 0;
}
}
/* if the user wants a flood of information then flood them */
if ($host['status'] == HOST_UP || $host['status'] == HOST_RECOVERING) {
/* log ping result if we are to use a ping for reachability testing */
if ($ping_availability == AVAIL_SNMP_AND_PING) {
cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
} elseif ($ping_availability == AVAIL_SNMP) {
if (($host['snmp_community'] == '') && ($host['snmp_version'] != 3)) {
cacti_log("Device[$host_id] SNMP: Device does not require SNMP", $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
} else {
cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
}
} else {
cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
}
} else {
if ($ping_availability == AVAIL_SNMP_AND_PING) {
cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
} elseif ($ping_availability == AVAIL_SNMP) {
cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
} else {
cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH);
}
}
/* if there is supposed to be an event generated, do it */
if ($issue_log_message) {
if ($host['status'] == HOST_DOWN) {
cacti_log("Device[$host_id] ERROR: HOST EVENT: Device is DOWN Message: " . $host['status_last_error'], $print_data_to_stdout);
} else {
cacti_log("Device[$host_id] NOTICE: HOST EVENT: Device Returned FROM DOWN State: ", $print_data_to_stdout);
}
}
db_execute_prepared('UPDATE host SET
status = ?,
status_event_count = ?,
status_fail_date = FROM_UNIXTIME(?),
status_rec_date = FROM_UNIXTIME(?),
status_last_error = ?,
min_time = ?,
max_time = ?,
cur_time = ?,
avg_time = ?,
total_polls = ?,
failed_polls = ?,
availability = ?
WHERE hostname = ?
AND deleted = ""',
array(
$host['status'],
$host['status_event_count'],
$host['status_fail_date'],
$host['status_rec_date'],
$host['status_last_error'],
$host['min_time'],
$host['max_time'],
$host['cur_time'],
$host['avg_time'],
$host['total_polls'],
$host['failed_polls'],
$host['availability'],
$host['hostname']
)
);
}
/**
* is_hexadecimal - test whether a string represents a hexadecimal number,
* ignoring space and tab, and case insensitive.
*
* @param $result - the string to test
* @param 1 if the argument is hex, 0 otherwise, and false on error
*/
function is_hexadecimal($result) {
$hexstr = str_replace(array(' ', '-'), ':', trim($result));
$parts = explode(':', $hexstr);
foreach($parts as $part) {
if (strlen($part) != 2) {
return false;
}
if (ctype_xdigit($part) == false) {
return false;
}
}
return true;
}
/**
* strip_domain - removes the domain from a hostname
*
* @param $hostname - the hostname for a device
*
* @return - the stripped hostname
*/
function strip_domain($hostname) {
if (is_ipaddress($hostname)) {
return $hostname;
} elseif (read_config_option('strip_domain') == 'on') {
$parts = explode('.', $hostname);
return $parts[0];
} else {
return $hostname;
}
}
/**
* is_mac_address - determines if the result value is a mac address
*
* @param $result - some string to be evaluated
*
* @return - either to result is a mac address of not
*/
function is_mac_address($result) {
if (!defined('FILTER_VALIDATE_MAC')) {
if (preg_match('/^([0-9a-f]{1,2}[\.:-]) {5}([0-9a-f]{1,2})$/i', $result)) {
return true;
} else {
return false;
}
} else {
return filter_var($result, FILTER_VALIDATE_MAC);
}
}
function is_hex_string(&$result) {
if ($result == '') {
return false;
}
$compare = strtolower($result);
/* strip off the 'Hex:, Hex-, and Hex-STRING:'
* Hex- is considered due to the stripping of 'String:' in
* lib/snmp.php
*/
if (substr($compare, 0, 4) == 'hex-') {
$check = trim(str_ireplace('hex-', '', $result));
} elseif (substr($compare, 0, 11) == 'hex-string:') {
$check = trim(str_ireplace('hex-string:', '', $result));
} else {
return false;
}
$parts = explode(' ', $check);
/* assume if something is a hex string
it will have a length > 1 */
if (cacti_sizeof($parts) == 1) {
return false;
}
foreach($parts as $part) {
if (strlen($part) != 2) {
return false;
}
if (ctype_xdigit($part) == false) {
return false;
}
}
$result = $check;
return true;
}
/**
* prepare_validate_result - determines if the result value is valid or not. If not valid returns a "U"
*
* @param $result - the result from the poll, the result can be modified in the call
*
* @return - either to result is valid or not
*/
function prepare_validate_result(&$result) {
/* first trim the string */
$result = trim($result, "'\"\n\r");
/* clean off ugly non-numeric data */
if (is_numeric($result)) {
dsv_log('prepare_validate_result','data is numeric', POLLER_VERBOSITY_MEDIUM);
return true;
} elseif ($result == 'U') {
dsv_log('prepare_validate_result', 'data is U', POLLER_VERBOSITY_MEDIUM);
return true;
} elseif (is_hexadecimal($result)) {
dsv_log('prepare_validate_result', 'data is hex', POLLER_VERBOSITY_MEDIUM);
return hexdec($result);
} elseif (substr_count($result, ':') || substr_count($result, '!')) {
/* looking for name value pairs */
if (substr_count($result, ' ') == 0) {
dsv_log('prepare_validate_result', 'data has no spaces', POLLER_VERBOSITY_MEDIUM);
return true;
} else {
$delim_cnt = 0;
if (substr_count($result, ':')) {
$delim_cnt = substr_count($result, ':');
} elseif (strstr($result, '!')) {
$delim_cnt = substr_count($result, '!');
}
$space_cnt = substr_count(trim($result), ' ');
dsv_log('prepare_validate_result', "data has $space_cnt spaces and $delim_cnt fields which is " . (($space_cnt + 1 == $delim_cnt) ? '' : 'NOT') . ' okay', POLLER_VERBOSITY_MEDIUM);
return ($space_cnt+1 == $delim_cnt);
}
} else {
$result = strip_alpha($result);
if ($result === false) {
$result = 'U';
return false;
} else {
return true;
}
}
}
/**
* strip_alpha - remove non-numeric data from a string and return the numeric part
*
* @param $string - the string to be evaluated
*
* @return - either the numeric value or false if not numeric
*/
function strip_alpha($string) {
/* strip all non numeric data */
$string = trim(preg_replace('/[^0-9,.+-]/', '', $string));
/* check the easy cases first */
/* it has no delimiters, and no space, therefore, must be numeric */
if (is_numeric($string) || is_float($string)) {
return $string;
} else {
return false;
}
}
/**
* is_valid_pathname - takes a pathname are verifies it matches file name rules
*
* @param $path - the pathname to be tested
*
* @return - either true or false
*/
function is_valid_pathname($path) {
if (preg_match('/^([a-zA-Z0-9\_\.\-\\\:\/]+)$/', trim($path))) {
return true;
} else {
return false;
}
}
/**
* dsv_log - provides debug logging when tracing Graph/Data Source creation
*
* @param $message - the message to output to the log
* @param $data - the data to be carried with the message
* @param $level - the level to log the dsv_log at or above
*/
function dsv_log($message, $data = null, $level = POLLER_VERBOSITY_LOW) {
if (read_config_option('data_source_trace') == 'on') {
cacti_log(($message . ' = ') . (is_array($data) ? json_encode($data) : ($data === null ? 'NULL' : $data)), false, 'DSTRACE', $level);
}
}
/**
* test_data_sources
*
* Tests all data sources to confirm that it returns valid data. This
* function is used by automation to prevent the creation of graphs
* that will never generate data.
*
* @param $graph_template_id - The Graph Template to test
* @param $host_id - The Host to test
*
* @return boolean true or false
*/
function test_data_sources($graph_template_id, $host_id, $snmp_query_id = 0, $snmp_index = '', $values = array()) {
$data_template_ids = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT data_template_id
FROM graph_templates_item AS gti
INNER JOIN data_template_rrd AS dtr
ON gti.task_item_id = dtr.id
WHERE gti.hash != ""
AND gti.local_graph_id = 0
AND dtr.local_data_id = 0
AND gti.graph_template_id = ?',
array($graph_template_id)),
'data_template_id', 'data_template_id'
);
$test_source = db_fetch_cell_prepared('SELECT test_source
FROM graph_templates
WHERE id = ?',
array($graph_template_id));
if (cacti_sizeof($data_template_ids) && $test_source == 'on') {
foreach($data_template_ids as $dt) {
dsv_log("test_data_source", [ 'dt' => $dt, 'host_id' => $host_id, 'snmp_query_id' => $snmp_query_id, 'snmp_index' => $snmp_index, 'values' => $values]);
if (!test_data_source($dt, $host_id, $snmp_query_id, $snmp_index, $values)) {
return false;
}
}
}
return true;
}
/**
* test_data_source
*
* Tests a single data source to confirm that it returns valid data. This
* function is used by automation to prevent the creation of graphs
* that will never generate data.
*
* @param $graph_template_id - The Graph Template to test
* @param $host_id - The Host to test
*
* @return boolean true or false
*/
function test_data_source($data_template_id, $host_id, $snmp_query_id = 0, $snmp_index = '', $suggested_vals = array()) {
global $called_by_script_server;
$called_by_script_server = true;
dsv_log('test_data_source', [ 'data_template_id' => $data_template_id, 'host_id' => $host_id, 'snmp_query_id' => $snmp_query_id, 'snmp_index' => $snmp_index, 'suggested_vals' => $suggested_vals]);
$data_input = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . '
di.id, di.type_id, dtd.id AS data_template_data_id,
dtd.data_template_id, dtd.active, dtd.rrd_step, di.name
FROM data_template_data AS dtd
INNER JOIN data_input AS di
ON dtd.data_input_id=di.id
WHERE dtd.local_data_id = 0
AND dtd.data_template_id = ?',
array($data_template_id));
dsv_log('data_input', $data_input);
$host = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' *
FROM host
WHERE id = ?',
array($host_id));
dsv_log('host', $host);
$data_template_data_id = 0;
if (cacti_sizeof($data_input) && $data_input['active'] == 'on') {
$data_template_data_id = $data_input['data_template_data_id'];
/* we have to perform some additional sql queries if this is a 'query' */
if (($data_input['type_id'] == DATA_INPUT_TYPE_SNMP_QUERY) ||
($data_input['type_id'] == DATA_INPUT_TYPE_SCRIPT_QUERY) ||
($data_input['type_id'] == DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER)) {
$field = data_query_field_list($data_template_data_id);
dsv_log('query field', $field);
$params = array();
$params[] = $data_input['data_template_id'];
if ($field['output_type'] != '') {
$output_type_sql = ' AND sqgr.snmp_query_graph_id = ?';
$params[] = $field['output_type'];
} else {
$output_type_sql = '';
}
$outputs_sql = 'SELECT DISTINCT ' . SQL_NO_CACHE . "
sqgr.snmp_field_name, dtr.id as data_template_rrd_id
FROM snmp_query_graph_rrd AS sqgr
INNER JOIN data_template_rrd AS dtr
ON sqgr.data_template_rrd_id = dtr.id
WHERE sqgr.data_template_id = ?
AND dtr.local_data_id = 0
$output_type_sql
ORDER BY dtr.id";
dsv_log('outputs_sql', $outputs_sql);
dsv_log('outputs_params', $params);
$outputs = db_fetch_assoc_prepared($outputs_sql, $params);
dsv_log('outputs', $outputs);
}
if (($data_input['type_id'] == DATA_INPUT_TYPE_SCRIPT) ||
($data_input['type_id'] == DATA_INPUT_TYPE_PHP_SCRIPT_SERVER)) {
if ($data_input['type_id'] == DATA_INPUT_TYPE_PHP_SCRIPT_SERVER) {
$action = POLLER_ACTION_SCRIPT_PHP;
} else {
$action = POLLER_ACTION_SCRIPT;
}
$script_path = get_full_test_script_path($data_template_id, $host_id);
dsv_log('script_path', $script_path);
$num_output_fields_sql = 'SELECT ' . SQL_NO_CACHE . ' id
FROM data_input_fields
WHERE data_input_id = ?
AND input_output = "out"
AND update_rra="on"';
dsv_log('num_output_fields_sql',$num_output_fields_sql);
$num_output_fields = cacti_sizeof(db_fetch_assoc_prepared($num_output_fields_sql, array($data_input['id'])));
dsv_log('num_output_fields', $num_output_fields);
if ($num_output_fields == 1) {
$data_template_rrd_id = db_fetch_cell_prepared('SELECT ' . SQL_NO_CACHE . ' id
FROM data_template_rrd
WHERE local_data_id = 0
AND hash != ""
AND data_template_id = ?',
array($data_template_id));
$data_source_item_name = get_data_source_item_name($data_template_rrd_id);
} else {
$data_source_item_name = '';
}
dsv_log('data_source_item_name', $data_source_item_name);
if ($action == POLLER_ACTION_SCRIPT) {
dsv_log('script_path', $script_path);
$output = shell_exec($script_path);
} else {
// Script server is a bit more complicated
$php = read_config_option('path_php_binary');
$parts = explode(' ', $script_path);
dsv_log('parts', $parts);
if (file_exists($parts[0])) {
unset($parts[1]);
$script = implode(' ', $parts);
dsv_log('script', $script);
$output = shell_exec("$php -q $script");
if ($output == '' || $output == false) {
$output = 'U';
}
} else {
$output = 'U';
}
}
dsv_log('output', $output);
if (!is_numeric($output)) {
if ($output == 'U') {
return false;
} elseif (strpos($output, ':U') !== false) {
return false;
} elseif (prepare_validate_result($output) === false) {
return false;
}
}
return true;
} elseif ($data_input['type_id'] == DATA_INPUT_TYPE_SNMP) {
/* get host fields first */
$host_fields_sql = 'SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code IN("hostname","host_id"))
AND did.data_template_data_id = ?
AND did.value != ""';
dsv_log('host_fields_sql', $host_fields_sql);
dsv_log('host_fields_sql_params', ['data_template_data_id' => $data_template_data_id]);
$host_fields = array_rekey(
db_fetch_assoc_prepared($host_fields_sql,
array($data_template_data_id)),
'type_code', 'value'
);
dsv_log('SNMP host_fields', $host_fields);
$data_template_data = db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id = did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?',
array($data_template_data_id));
dsv_log('SNMP data_template_data', $data_template_data);
if (cacti_sizeof($data_template_data)) {
foreach ($data_template_data as $field) {
$key = $field['type_code'];
$value = $field['value'];
dsv_log('SNMP field', $field);
dsv_log('SNMP value', $value);
if (!empty($suggested_vals['custom_data'][$data_template_id][$field['id']])) {
$value = $suggested_vals['custom_data'][$data_template_id][$field['id']];
dsv_log("SNMP value replace suggested $key", $value);
}
if (!empty($value) && !isset($host_fields[$key])) {
$host_fields[$key] = $value;
dsv_log("SNMP value replace template $key", $value);
}
}
}
dsv_log('SNMP [updated] host_fields', $host_fields);
$host = array_merge($host, $host_fields);
dsv_log('SNMP [updated] host', $host);
$session = cacti_snmp_session($host['hostname'], $host['snmp_community'], $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'],
$host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_engine_id'], $host['snmp_port'],
$host['snmp_timeout'], $host['ping_retries'], $host['max_oids']);
$output = cacti_snmp_session_get($session, $host['snmp_oid']);
dsv_log('SNMP output', $output);
if (!is_numeric($output)) {
if (prepare_validate_result($output) === false) {
return false;
}
}
return true;
} elseif ($data_input['type_id'] == DATA_INPUT_TYPE_SNMP_QUERY) {
$snmp_queries = get_data_query_array($snmp_query_id);
/* get host fields first */
$host_fields = array_rekey(
db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?
AND did.value != ""', array($data_template_data_id)),
'type_code', 'value'
);
dsv_log('SNMP_QUERY host_fields', $host_fields);
$data_template_data = db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?',
array($data_template_data_id));
dsv_log('SNMP_QUERY data_template_data', $data_template_data);
if (cacti_sizeof($data_template_data)) {
foreach ($data_template_data as $field) {
$key = $field['type_code'];
$value = $field['value'];
dsv_log('SNMP_QUERY field', $field);
if (!empty($suggested_vals['custom_data'][$data_template_id][$field['id']])) {
$value = $suggested_vals['custom_data'][$data_template_id][$field['id']];
dsv_log("SNMP_QUERY value replace suggested $key", $value);
}
if (!empty($value) && !isset($host_fields[$key])) {
$host_fields[$key] = $value;
dsv_log("SNMP_QUERY value replace template $key", $value);
}
}
}
dsv_log('SNMP_QUERY [updated] host_fields', $host_fields);
$host = array_merge($host, $host_fields);
dsv_log('SNMP_QUERY [updated] host', $host);
if (cacti_sizeof($outputs) && cacti_sizeof($snmp_queries)) {
foreach ($outputs as $output) {
if (isset($snmp_queries['fields'][$output['snmp_field_name']]['oid'])) {
$oid = $snmp_queries['fields'][$output['snmp_field_name']]['oid'] . '.' . $snmp_index;
if (isset($snmp_queries['fields'][$output['snmp_field_name']]['oid_suffix'])) {
$oid .= '.' . $snmp_queries['fields'][$output['snmp_field_name']]['oid_suffix'];
}
}
if (!empty($oid)) {
$session = cacti_snmp_session($host['hostname'], $host['snmp_community'], $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'],
$host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_engine_id'], $host['snmp_port'],
$host['snmp_timeout'], $host['ping_retries'], $host['max_oids']);
$output = cacti_snmp_session_get($session, $oid);
if (!is_numeric($output)) {
if (prepare_validate_result($output) === false) {
return false;
}
}
return true;
}
}
}
} elseif (($data_input['type_id'] == DATA_INPUT_TYPE_SCRIPT_QUERY) ||
($data_input['type_id'] == DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER)) {
$script_queries = get_data_query_array($snmp_query_id);
/* get host fields first */
$host_fields = array_rekey(
db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?
AND did.value != ""', array($data_template_data_id)),
'type_code', 'value'
);
dsv_log('SCRIPT host_fields', $host_fields);
$data_template_fields = array_rekey(
db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?
AND did.value != ""', array($data_template_data_id)),
'type_code', 'value'
);
$data_template_data = db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' dif.id, dif.type_code, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id=did.data_input_field_id
WHERE (type_code LIKE "snmp_%" OR type_code="hostname")
AND did.data_template_data_id = ?',
array($data_template_data_id));
dsv_log('SCRIPT data_template_data', $data_template_data);
if (cacti_sizeof($data_template_data)) {
foreach ($data_template_data as $field) {
$key = $field['type_code'];
$value = $field['value'];
dsv_log('SCRIPT field', $field);
if (!empty($suggested_vals['custom_data'][$data_template_id][$field['id']])) {
$value = $suggested_vals['custom_data'][$data_template_id][$field['id']];
dsv_log("SCRIPT value replace suggested $key", $value);
}
if (!empty($value) && !isset($host_fields[$key])) {
$host_fields[$key] = $value;
dsv_log("SCRIPT value replace template $key", $value);
}
}
}
dsv_log('SCRIPT [updated] host_fields', $host_fields);
$host = array_merge($host, $host_fields);
dsv_log('SCRIPT [updated] host', $host);
if (cacti_sizeof($outputs) && cacti_sizeof($script_queries)) {
foreach ($outputs as $output) {
if (isset($script_queries['fields'][$output['snmp_field_name']]['query_name'])) {
$identifier = $script_queries['fields'][$output['snmp_field_name']]['query_name'];
if ($data_input['type_id'] == DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER) {
$action = POLLER_ACTION_SCRIPT;
$prepend = '';
if (isset($script_queries['arg_prepend']) && $script_queries['arg_prepend'] != '') {
$prepend = $script_queries['arg_prepend'];
}
$script_path = read_config_option('path_php_binary') . ' -q ' . get_script_query_path(trim($prepend . ' ' . $script_queries['arg_get'] . ' ' . $identifier . ' "' . $snmp_index . '"'), $script_queries['script_path'], $host_id);
} else {
$action = POLLER_ACTION_SCRIPT;
$script_path = get_script_query_path(trim((isset($script_queries['arg_prepend']) ? $script_queries['arg_prepend'] : '') . ' ' . $script_queries['arg_get'] . ' ' . $identifier . ' "' . $snmp_index . '"'), $script_queries['script_path'], $host_id);
}
}
if (isset($script_path)) {
$output = shell_exec($script_path);
if (!is_numeric($output)) {
if (prepare_validate_result($output) === false) {
return false;
}
}
return true;
}
}
}
}
}
return false;
}
/**
* get_full_test_script_path - gets the full path to the script to execute to obtain data for a
* given data template for testing. this function does not work on SNMP actions, only
* script-based actions
*
* @param $data_template_id - (int) the ID of the data template
*
* @return string - the full script path or (bool) false for an error
*/
function get_full_test_script_path($data_template_id, $host_id) {
global $config;
$data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . '
dtd.id,
dtd.data_input_id,
di.type_id,
di.input_string
FROM data_template_data AS dtd
INNER JOIN data_input AS di
ON dtd.data_input_id = di.id
WHERE dtd.local_data_id = 0
AND dtd.data_template_id = ?',
array($data_template_id));
$data = db_fetch_assoc_prepared("SELECT " . SQL_NO_CACHE . " dif.data_name, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id = did.data_input_field_id
WHERE dif.data_input_id = ?
AND did.data_template_data_id = ?
AND dif.input_output = 'in'",
array($data_source['data_input_id'], $data_source['id']));
$full_path = $data_source['input_string'];
$host = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
if (cacti_sizeof($data)) {
foreach ($data as $item) {
if (isset($host[$item['data_name']])) {
$value = cacti_escapeshellarg($host[$item['data_name']]);
} elseif ($item['data_name'] == 'host_id' || $item['data_name'] == 'hostid') {
$value = cacti_escapeshellarg($host['id']);
} else {
$value = "'" . $item['value'] . "'";
}
$full_path = str_replace('<' . $item['data_name'] . '>', $value, $full_path);
}
}
$search = array('<path_cacti>', '<path_snmpget>', '<path_php_binary>');
$replace = array($config['base_path'], read_config_option('path_snmpget'), read_config_option('path_php_binary'));
$full_path = str_replace($search, $replace, $full_path);
/**
* sometimes a certain input value will not have anything entered... null out these fields
* in the input string so we don't mess up the script
*/
return preg_replace('/(<[A-Za-z0-9_]+>)+/', '', $full_path);
}
/**
* get_full_script_path - gets the full path to the script to execute to obtain data for a
* given data source. this function does not work on SNMP actions, only script-based actions
*
* @param $local_data_id - (int) the ID of the data source
*
* @return - the full script path or (bool) false for an error
*/
function get_full_script_path($local_data_id) {
global $config;
$data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' dtd.id, dtd.data_input_id,
di.type_id, di.input_string
FROM data_template_data AS dtd
INNER JOIN data_input AS di
ON dtd.data_input_id = di.id
WHERE dtd.local_data_id = ?',
array($local_data_id));
/* snmp-actions don't have paths */
if (($data_source['type_id'] == DATA_INPUT_TYPE_SNMP) || ($data_source['type_id'] == DATA_INPUT_TYPE_SNMP_QUERY)) {
return false;
}
$data = db_fetch_assoc_prepared("SELECT " . SQL_NO_CACHE . " dif.data_name, did.value
FROM data_input_fields AS dif
LEFT JOIN data_input_data AS did
ON dif.id = did.data_input_field_id
WHERE dif.data_input_id = ?
AND did.data_template_data_id = ?
AND dif.input_output = 'in'",
array($data_source['data_input_id'], $data_source['id']));
$full_path = $data_source['input_string'];
if (cacti_sizeof($data)) {
foreach ($data as $item) {
$value = cacti_escapeshellarg($item['value']);
if ($value == '') {
$value = "''";
}
$full_path = str_replace('<' . $item['data_name'] . '>', $value, $full_path);
}
}
$search = array('<path_cacti>', '<path_snmpget>', '<path_php_binary>');
$replace = array($config['base_path'], read_config_option('path_snmpget'), read_config_option('path_php_binary'));
$full_path = str_replace($search, $replace, $full_path);
/* sometimes a certain input value will not have anything entered... null out these fields
in the input string so we don't mess up the script */
return preg_replace('/(<[A-Za-z0-9_]+>)+/', '', $full_path);
}
/**
* get_data_source_item_name - gets the name of a data source item or generates a new one if one does not
* already exist
*
* @param $data_template_rrd_id - (int) the ID of the data source item
*
* @return - the name of the data source item or an empty string for an error
*/
function get_data_source_item_name($data_template_rrd_id) {
if (empty($data_template_rrd_id)) {
return '';
}
$data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . '
dtr.data_source_name, dtd.name
FROM data_template_rrd AS dtr
INNER JOIN data_template_data AS dtd
ON dtr.local_data_id = dtd.local_data_id
WHERE dtr.id = ?',
array($data_template_rrd_id)
);
/* use the cacti ds name by default or the user defined one, if entered */
if (empty($data_source['data_source_name'])) {
/* limit input to 19 characters */
$data_source_name = clean_up_name($data_source['name']);
$data_source_name = substr(strtolower($data_source_name), 0, (19-strlen($data_template_rrd_id))) . $data_template_rrd_id;
return $data_source_name;
} else {
return $data_source['data_source_name'];
}
}
/**
* get_data_source_path - gets the full path to the .rrd file associated with a given data source
*
* @param $local_data_id - (int) the ID of the data source
* @param $expand_paths - (bool) whether to expand the <path_rra> variable into its full path or not
*
* @return - the full path to the data source or an empty string for an error
*/
function get_data_source_path($local_data_id, $expand_paths) {
global $config;
static $data_source_path_cache = array();
if (empty($local_data_id)) {
return '';
}
if (isset($data_source_path_cache[$local_data_id])) {
return $data_source_path_cache[$local_data_id];
}
$data_source = db_fetch_row_prepared('SELECT name, data_source_path
FROM data_template_data AS dtd
WHERE local_data_id = ?',
array($local_data_id));
if (cacti_sizeof($data_source)) {
if (empty($data_source['data_source_path'])) {
/* no custom path was specified */
$data_source_path = generate_data_source_path($local_data_id);
} elseif (!strstr($data_source['data_source_path'], '/')) {
$data_source_path = '<path_rra>/' . $data_source['data_source_path'];
} else {
$data_source_path = $data_source['data_source_path'];
}
/* whether to show the "actual" path or the <path_rra> variable name (for edit boxes) */
if ($expand_paths == true) {
$data_source_path = str_replace('<path_rra>/', $config['rra_path'] . '/', $data_source_path);
}
$data_source_path_cache[$local_data_id] = $data_source_path;
return $data_source_path;
}
}
/**
* stri_replace - a case insensitive string replace
*
* @param $find - needle
* @param $replace - replace needle with this
* @param $string - haystack
*
* @return - the original string with '$find' replaced by '$replace'
*/
function stri_replace($find, $replace, $string) {
$parts = explode(strtolower($find), strtolower($string));
$pos = 0;
$findLength = strlen($find);
foreach ($parts as $key => $part) {
$partLength = strlen($part);
$parts[$key] = substr($string, $pos, $partLength);
$pos += $partLength + $findLength;
}
return (join($replace, $parts));
}
/**
* clean_up_lines - runs a string through a regular expression designed to remove
* new lines and the spaces around them
*
* @param $string - the string to modify/clean
*
* @return string The modified string
*/
function clean_up_lines($string) {
if ($string != '') {
return preg_replace('/\s*[\r\n]+\s*/',' ', $string);
} else {
return $string;
}
}
/**
* clean_up_name - runs a string through a series of regular expressions designed to
* eliminate "bad" characters
*
* @param $string - the string to modify/clean
*
* @return string The modified string
*/
function clean_up_name($string) {
if ($string != '') {
$string = preg_replace('/[\s\.]+/', '_', $string);
$string = preg_replace('/[^a-zA-Z0-9_]+/', '', $string);
$string = preg_replace('/_{2,}/', '_', $string);
}
return $string;
}
/**
* clean_up_file name - runs a string through a series of regular expressions designed to
* eliminate "bad" characters
*
* @param $string - the string to modify/clean
*
* @return string The modified string
*/
function clean_up_file_name($string) {
if ($string != '') {
$string = preg_replace('/[\s\.]+/', '_', $string);
$string = preg_replace('/[^a-zA-Z0-9_-]+/', '', $string);
$string = preg_replace('/_{2,}/', '_', $string);
}
return $string;
}
/**
* clean_up_path - takes any path and makes sure it contains the correct directory
* separators based on the current operating system
*
* @param $path - the path to modify
*
* @return - the modified path
*/
function clean_up_path($path) {
global $config;
if ($config['cacti_server_os'] == 'win32') {
return str_replace('/', "\\", $path);
} elseif ($config['cacti_server_os'] == 'unix' || read_config_option('using_cygwin') == 'on' || read_config_option('storage_location')) {
return str_replace("\\", '/', $path);
} else {
return $path;
}
}
/**
* get_data_source_title - returns the title of a data source without using the title cache
*
* @param $local_data_id - (int) the ID of the data source to get a title for
*
* @return - the data source title
*/
function get_data_source_title($local_data_id) {
$data = db_fetch_row_prepared('SELECT
dl.host_id, dl.snmp_query_id, dl.snmp_index, dl.data_template_id,
dtd.name, dtd.id as template_id
FROM data_local AS dl
LEFT JOIN data_template_data AS dtd
ON dtd.local_data_id = dl.id
WHERE dl.id = ?',
array($local_data_id));
$title = 'Missing Datasource ' . $local_data_id;
if (cacti_sizeof($data)) {
if (strstr($data['name'], '|') !== false && $data['host_id'] > 0) {
$data['name'] = substitute_data_input_data($data['name'], '', $local_data_id);
$title = expand_title($data['host_id'], $data['snmp_query_id'], $data['snmp_index'], $data['name']);
} else {
$title = $data['name'];
}
// Is the data source linked to a template? If so, make sure we have a template on the
// LEFT JOIN since it may not find one. Also, we can't check that they are the same ID
// ID yet because there are two, one with a 0 local_data_id (base template) and one with
// this source's id (instance of template).
if ($data['data_template_id'] && !$data['template_id']) {
$title .= ' (Bad template "' . $data['data_template_id'] . '")';
}
}
return $title;
}
/**
* get_device_name - returns the description of the device in cacti host table
*
* @param $host_id - (int) the ID of the device to get a description for
*
* @return - the device name
*/
function get_device_name($host_id) {
return db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($host_id));
}
/**
* get_color - returns the hex color value from the cacti colors table
*
* @param $color_id - (int) the ID of the cacti color
* @return - the hex color value
*
*/
function get_color($color_id) {
return db_fetch_cell_prepared('SELECT hex FROM colors WHERE id = ?', array($color_id));
}
/**
* get_graph_title_cache - returns the title of the graph using the title cache
*
* @param $local_graph_id - (int) the ID of the graph to get the title for
*
* @return - the graph title
*/
function get_graph_title_cache($local_graph_id) {
return db_fetch_cell_prepared('SELECT title_cache
FROM graph_templates_graph
WHERE local_graph_id = ?',
array($local_graph_id));
}
/**
* get_graph_title - returns the title of a graph without using the title cache
*
* @param $local_graph_id - (int) the ID of the graph to get a title for
*
* @return string The graph title
*/
function get_graph_title($local_graph_id) {
$graph = db_fetch_row_prepared('SELECT gl.host_id, gl.snmp_query_id,
gl.snmp_index, gtg.local_graph_id, gtg.t_title, gtg.title
FROM graph_templates_graph AS gtg
INNER JOIN graph_local AS gl
ON gtg.local_graph_id = gl.id
WHERE gl.id = ?',
array($local_graph_id));
if (cacti_sizeof($graph)) {
if (strstr($graph['title'], '|') !== false && $graph['host_id'] > 0 && empty($graph['t_title'])) {
$graph['title'] = substitute_data_input_data($graph['title'], $graph, 0);
return expand_title($graph['host_id'], $graph['snmp_query_id'], $graph['snmp_index'], $graph['title']);
} else {
return $graph['title'];
}
} else {
return '';
}
}
/**
* get_guest_account - return the guest account as defined in the system
* if there is one, else return 0.
*
* @return (int) the guest account if greater than 0
*/
function get_guest_account() {
$user = db_fetch_cell_prepared('SELECT id
FROM user_auth
WHERE username = ? OR id = ?',
array(read_config_option('guest_user'), read_config_option('guest_user')));
if (empty($user)) {
return 0;
} else {
return $user;
}
}
/**
* get_template_account - return the template account given a user.
* if a user is not given, provide the 'default' template account.
* This function is hookable by third party plugins.
*
* @param (int|string) either the username or user_id of the user
*
* @return (int) the template account if one exist for the user
*/
function get_template_account($user = '') {
if ($user == '') {
// no username or user_id passed, use default functionality
$user = db_fetch_cell_prepared('SELECT id
FROM user_auth
WHERE username = ? OR id = ?',
array(read_config_option('user_template'), read_config_option('user_template')));
if (empty($user)) {
return 0;
} else {
return $user;
}
} else {
$template = api_plugin_hook_function('get_template_account', $user);
if ($template == $user) {
// no plugin present, use default functionality
$user = db_fetch_cell_prepared('SELECT id
FROM user_auth
WHERE username = ? OR id = ?',
array(read_config_option('user_template'), read_config_option('user_template')));
if (empty($user)) {
return 0;
} else {
return $user;
}
} elseif ($template > 0) {
// plugin present and returned account
return $template;
} else {
// plugin present and returned no account
return 0;
}
}
}
/**
* get_username - returns the username for the selected user
*
* @param $user_id - (int) the ID of the user
*
* @return - the username */
function get_username($user_id) {
return db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($user_id));
}
/**
* get_execution_user - returns the username of the running process
*
* @return - the username
*/
function get_execution_user() {
if (function_exists('posix_getpwuid')) {
$user_info = posix_getpwuid(posix_geteuid());
return $user_info['name'];
} else {
return exec('whoami');
}
}
/**
* generate_data_source_path - creates a new data source path from scratch using the first data source
* item name and updates the database with the new value
*
* @param $local_data_id - (int) the ID of the data source to generate a new path for
*
* @return - the new generated path
*/
function generate_data_source_path($local_data_id) {
global $config;
static $extended_paths = false;
static $pattern = false;
if ($extended_paths === false) {
$extended_paths = read_config_option('extended_paths');
}
if ($pattern === false) {
$pattern = read_config_option('extended_paths_type');
}
/* try any prepend the name with the host description */
$data = db_fetch_row_prepared('SELECT dl.host_id, h.description, dl.snmp_query_id
FROM host AS h
INNER JOIN data_local AS dl
ON dl.host_id = h.id
AND dl.id = ?',
array($local_data_id));
if (cacti_sizeof($data)) {
$host_name = $data['description'];
$host_id = $data['host_id'];
$data_query_id = $data['snmp_query_id'];
} else {
$host_name = 'undefinedhost';
$host_id = 0;
$data_query_id = 0;
}
/* put it all together using the local_data_id at the end */
if ($extended_paths == 'on') {
$maxdirs = read_config_option('extended_paths_hashes');
if (empty($maxdirs) || $maxdirs < 0 || !is_numeric($maxdirs)) {
$maxdirs = 100;
}
$hash_id = $host_id % $maxdirs;
if ($pattern == 'device' || $pattern == '') {
$new_path = "<path_rra>/$host_id/$local_data_id.rrd";
} elseif ($pattern == 'device_dq') {
$new_path = "<path_rra>/$host_id/$data_query_id/$local_data_id.rrd";
} elseif ($pattern == 'hash_device') {
$new_path = "<path_rra>/$hash_id/$host_id/$local_data_id.rrd";
} elseif ($pattern == 'hash_device_dq') {
$new_path = "<path_rra>/$hash_id/$host_id/$data_query_id/$local_data_id.rrd";
}
} else {
$host_part = strtolower(clean_up_file_name($host_name)) . '_';
/* then try and use the internal DS name to identify it */
$data_source_rrd_name = db_fetch_cell_prepared('SELECT data_source_name
FROM data_template_rrd
WHERE local_data_id = ?
ORDER BY id
LIMIT 1',
array($local_data_id)
);
if (!empty($data_source_rrd_name)) {
$ds_part = strtolower(clean_up_file_name($data_source_rrd_name));
} else {
$ds_part = 'ds';
}
$new_path = "<path_rra>/$host_part$ds_part" . '_' . "$local_data_id.rrd";
}
/* update our changes to the db */
db_execute_prepared('UPDATE data_template_data SET data_source_path = ? WHERE local_data_id = ?', array($new_path, $local_data_id));
return $new_path;
}
/**
* generate graph_best_cf - takes the requested consolidation function and maps against
* the list of available consolidation functions for the consolidation functions and returns
* the most appropriate. Typically, this will be the requested value
*
* @param $data_template_id
* @param $requested_cf
* @param $ds_step
*
* @return - the best cf to use
*/
function generate_graph_best_cf($local_data_id, $requested_cf, $ds_step = 60) {
static $best_cf;
if ($local_data_id > 0) {
$avail_cf_functions = get_rrd_cfs($local_data_id);
if (cacti_sizeof($avail_cf_functions)) {
/* workaround until we have RRA presets in 0.8.8 */
/* check through the cf's and get the best */
/* if none was found, take the first */
$best_cf = reset($avail_cf_functions);
foreach($avail_cf_functions as $cf) {
if ($cf == $requested_cf) {
$best_cf = $requested_cf;
}
}
} else {
$best_cf = '1';
}
}
/* if you can not figure it out return average */
return $best_cf;
}
/**
* get_rrd_cfs - reads the RRDfile and gets the RRAs stored in it.
*
* @param $local_data_id
*
* @return - array of the CF functions
*/
function get_rrd_cfs($local_data_id) {
global $consolidation_functions;
static $rrd_cfs = array();
if (array_key_exists($local_data_id, $rrd_cfs)) {
return $rrd_cfs[$local_data_id];
}
$cfs = array();
$rrdfile = get_data_source_path($local_data_id, true);
$output = @rrdtool_execute("info $rrdfile", false, RRDTOOL_OUTPUT_STDOUT);
/* search for
* rra[0].cf = 'LAST'
* or similar
*/
if ($output != '') {
$output = explode("\n", $output);
if (cacti_sizeof($output)) {
foreach($output as $line) {
if (substr_count($line, '.cf')) {
$values = explode('=',$line);
if (!in_array(trim($values[1], '" '), $cfs)) {
$cfs[] = trim($values[1], '" ');
}
}
}
}
}
$new_cfs = array();
if (cacti_sizeof($cfs)) {
foreach($cfs as $cf) {
switch($cf) {
case 'AVG':
case 'AVERAGE':
$new_cfs[1] = array_search('AVERAGE', $consolidation_functions);
break;
case 'MIN':
$new_cfs[2] = array_search('MIN', $consolidation_functions);
break;
case 'MAX':
$new_cfs[3] = array_search('MAX', $consolidation_functions);
break;
case 'LAST':
$new_cfs[4] = array_search('LAST', $consolidation_functions);
break;
}
}
}
$rrd_cfs[$local_data_id] = $new_cfs;
return $new_cfs;
}
/**
* generate_graph_def_name - takes a number and turns each digit into its letter-based
* counterpart for RRDtool DEF names (ex 1 -> a, 2 -> b, etc)
*
* @param $graph_item_id - (int) the ID to generate a letter-based representation of
*
* @return - a letter-based representation of the input argument
*/
function generate_graph_def_name($graph_item_id) {
$lookup_table = array('a','b','c','d','e','f','g','h','i','j');
$result = '';
$strValGII = strval($graph_item_id);
for ($i=0; $i<strlen($strValGII); $i++) {
$result .= $lookup_table[substr($strValGII, $i, 1)];
}
if (preg_match('/^(cf|cdef|def)$/', $result)) {
return 'zz' . $result;
} else {
return $result;
}
}
/**
* generate_data_input_field_sequences - re-numbers the sequences of each field associated
* with a particular data input method based on its position within the input string
*
* @param $string - the input string that contains the field variables in a certain order
* @param $data_input_id - (int) the ID of the data input method
*/
function generate_data_input_field_sequences($string, $data_input_id) {
global $config, $registered_cacti_names;
if (preg_match_all('/<([_a-zA-Z0-9]+)>/', $string, $matches)) {
$j = 0;
for ($i=0; ($i < cacti_count($matches[1])); $i++) {
if (in_array($matches[1][$i], $registered_cacti_names) == false) {
$j++;
db_execute_prepared("UPDATE data_input_fields
SET sequence = ?
WHERE data_input_id = ?
AND input_output IN ('in')
AND data_name = ?",
array($j, $data_input_id, $matches[1][$i]));
}
}
update_replication_crc(0, 'poller_replicate_data_input_fields_crc');
}
}
/**
* move_graph_group - takes a graph group (parent+children) and swaps it with another graph
* group
*
* @param $graph_template_item_id - (int) the ID of the (parent) graph item that was clicked
* @param $graph_group_array - (array) an array containing the graph group to be moved
* @param $target_id - (int) the ID of the (parent) graph item of the target group
* @param $direction - ('next' or 'previous') whether the graph group is to be swapped with
* group above or below the current group
*/
function move_graph_group($graph_template_item_id, $graph_group_array, $target_id, $direction) {
$graph_item = db_fetch_row_prepared('SELECT local_graph_id, graph_template_id
FROM graph_templates_item
WHERE id = ?',
array($graph_template_item_id));
if (empty($graph_item['local_graph_id'])) {
$sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0';
} else {
$sql_where = 'local_graph_id = ' . $graph_item['local_graph_id'];
}
/* get a list of parent+children of our target group */
$target_graph_group_array = get_graph_group($target_id);
/* if this "parent" item has no children, then treat it like a regular gprint */
if (cacti_sizeof($target_graph_group_array) == 0) {
if ($direction == 'next') {
move_item_down('graph_templates_item', $graph_template_item_id, $sql_where);
} elseif ($direction == 'previous') {
move_item_up('graph_templates_item', $graph_template_item_id, $sql_where);
}
return;
}
/* start the sequence at '1' */
$sequence_counter = 1;
$graph_items = db_fetch_assoc_prepared("SELECT id, sequence
FROM graph_templates_item
WHERE $sql_where
ORDER BY sequence");
if (cacti_sizeof($graph_items)) {
foreach ($graph_items as $item) {
/* check to see if we are at the "target" spot in the loop; if we are, update the sequences and move on */
if ($target_id == $item['id']) {
if ($direction == 'next') {
$group_array1 = $target_graph_group_array;
$group_array2 = $graph_group_array;
} elseif ($direction == 'previous') {
$group_array1 = $graph_group_array;
$group_array2 = $target_graph_group_array;
}
foreach ($group_array1 as $graph_template_item_id) {
db_execute_prepared('UPDATE graph_templates_item
SET sequence = ?
WHERE id = ?',
array($sequence_counter, $graph_template_item_id));
/* propagate to ALL graphs using this template */
if (empty($graph_item['local_graph_id'])) {
db_execute_prepared('UPDATE graph_templates_item
SET sequence = ?
WHERE local_graph_template_item_id = ?',
array($sequence_counter, $graph_template_item_id));
}
$sequence_counter++;
}
foreach ($group_array2 as $graph_template_item_id) {
db_execute_prepared('UPDATE graph_templates_item
SET sequence = ?
WHERE id = ?',
array($sequence_counter, $graph_template_item_id));
/* propagate to ALL graphs using this template */
if (empty($graph_item['local_graph_id'])) {
db_execute_prepared('UPDATE graph_templates_item
SET sequence = ?
WHERE local_graph_template_item_id = ?',
array($sequence_counter, $graph_template_item_id));
}
$sequence_counter++;
}
}
/* make sure to "ignore" the items that we handled above */
if ((!isset($graph_group_array[$item['id']])) && (!isset($target_graph_group_array[$item['id']]))) {
db_execute_prepared('UPDATE graph_templates_item
SET sequence = ?
WHERE id = ?',
array($sequence_counter, $item['id']));
$sequence_counter++;
}
}
}
}
/**
* get_graph_group - returns an array containing each item in the graph group given a single
* graph item in that group
*
* @param $graph_template_item_id - (int) the ID of the graph item to return the group of
*
* @return - (array) an array containing each item in the graph group
*/
function get_graph_group($graph_template_item_id) {
global $graph_item_types;
$graph_item = db_fetch_row_prepared('SELECT graph_type_id, sequence, local_graph_id, graph_template_id
FROM graph_templates_item
WHERE id = ?',
array($graph_template_item_id));
$params[] = $graph_item['sequence'];
if (empty($graph_item['local_graph_id'])) {
$params[] = $graph_item['graph_template_id'];
$sql_where = 'graph_template_id = ? AND local_graph_id = 0';
} else {
$params[] = $graph_item['sequence'];
$sql_where = 'local_graph_id = ?';
}
/* parents are LINE%, AREA%, and STACK%. If not return */
if (!preg_match('/(LINE|AREA|STACK)/', $graph_item_types[$graph_item['graph_type_id']])) {
return array();
}
$graph_item_children_array = array();
/* put the parent item in the array as well */
$graph_item_children_array[$graph_template_item_id] = $graph_template_item_id;
$graph_items = db_fetch_assoc_prepared("SELECT id, graph_type_id, text_format, hard_return
FROM graph_templates_item
WHERE sequence > ?
AND $sql_where
ORDER BY sequence",
$params);
$is_hard = false;
if (cacti_sizeof($graph_items)) {
foreach ($graph_items as $item) {
if ($is_hard) {
return $graph_item_children_array;
} elseif (strstr($graph_item_types[$item['graph_type_id']], 'GPRINT') !== false) {
/* a child must be a GPRINT */
$graph_item_children_array[$item['id']] = $item['id'];
if ($item['hard_return'] == 'on') {
$is_hard = true;
}
} elseif (strstr($graph_item_types[$item['graph_type_id']], 'COMMENT') !== false) {
if (preg_match_all('/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/', $item['text_format'], $matches, PREG_SET_ORDER)) {
$graph_item_children_array[$item['id']] = $item['id'];
} elseif (preg_match_all('/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/', $item['text_format'], $matches, PREG_SET_ORDER)) {
$graph_item_children_array[$item['id']] = $item['id'];
} else {
/* if not a GPRINT or special COMMENT then get out */
return $graph_item_children_array;
}
} else {
/* if not a GPRINT or special COMMENT then get out */
return $graph_item_children_array;
}
}
}
return $graph_item_children_array;
}
/**
* get_graph_parent - returns the ID of the next or previous parent graph item id
*
* @param $graph_template_item_id - the ID of the current graph item
* @param $direction - ('next' or 'previous') whether to find the next or previous parent
*
* @return - the ID of the next or previous parent graph item id
*/
function get_graph_parent($graph_template_item_id, $direction) {
$graph_item = db_fetch_row_prepared('SELECT sequence, local_graph_id, graph_template_id
FROM graph_templates_item
WHERE id = ?',
array($graph_template_item_id));
if (empty($graph_item['local_graph_id'])) {
$sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0';
} else {
$sql_where = 'local_graph_id = ' . $graph_item['local_graph_id'];
}
if ($direction == 'next') {
$sql_operator = '>';
$sql_order = 'ASC';
} elseif ($direction == 'previous') {
$sql_operator = '<';
$sql_order = 'DESC';
}
$next_parent_id = db_fetch_cell("SELECT id
FROM graph_templates_item
WHERE sequence $sql_operator " . $graph_item['sequence'] . "
AND graph_type_id IN (4, 5, 6, 7, 8, 20)
AND $sql_where
ORDER BY sequence $sql_order
LIMIT 1");
if (empty($next_parent_id)) {
return 0;
} else {
return $next_parent_id;
}
}
/**
* get_item - returns the ID of the next or previous item id
*
* @param $tblname - the table name that contains the target id
* @param $field - the field name that contains the target id
* @param $startid - (int) the current id
* @param $lmt_query - an SQL "where" clause to limit the query
* @param $direction - ('next' or 'previous') whether to find the next or previous item id
*
* @return - (int) the ID of the next or previous item id
*/
function get_item($tblname, $field, $startid, $lmt_query, $direction) {
if ($direction == 'next') {
$sql_operator = '>';
$sql_order = 'ASC';
} elseif ($direction == 'previous') {
$sql_operator = '<';
$sql_order = 'DESC';
}
$current_sequence = db_fetch_cell_prepared("SELECT $field
FROM $tblname
WHERE id = ?",
array($startid));
$new_item_id = db_fetch_cell("SELECT id
FROM $tblname
WHERE $field $sql_operator $current_sequence " . ($lmt_query != '' ? " AND $lmt_query":"") . "
ORDER BY $field $sql_order
LIMIT 1");
if (empty($new_item_id)) {
return $startid;
} else {
return $new_item_id;
}
}
/**
* get_sequence - returns the next available sequence id
*
* @param $id - (int) the current id
* @param $field - the field name that contains the target id
* @param $table_name - the table name that contains the target id
* @param $group_query - an SQL "where" clause to limit the query
*
* @return - (int) the next available sequence id
*/
function get_sequence($id, $field, $table_name, $group_query) {
if (empty($id)) {
$data = db_fetch_row("SELECT max($field)+1 AS seq
FROM $table_name
WHERE $group_query");
if ($data['seq'] == '') {
return 1;
} else {
return $data['seq'];
}
} else {
$data = db_fetch_row_prepared("SELECT $field
FROM $table_name
WHERE id = ?",
array($id));
return $data[$field];
}
}
/**
* move_item_down - moves an item down by swapping it with the item below it
*
* @param $table_name - the table name that contains the target id
* @param $current_id - (int) the current id
* @param $group_query - an SQL "where" clause to limit the query
*/
function move_item_down($table_name, $current_id, $group_query = '') {
$next_item = get_item($table_name, 'sequence', $current_id, $group_query, 'next');
$sequence = db_fetch_cell_prepared("SELECT sequence
FROM $table_name
WHERE id = ?",
array($current_id));
$sequence_next = db_fetch_cell_prepared("SELECT sequence
FROM $table_name
WHERE id = ?",
array($next_item));
db_execute_prepared("UPDATE $table_name
SET sequence = ?
WHERE id = ?",
array($sequence_next, $current_id));
db_execute_prepared("UPDATE $table_name
SET sequence = ?
WHERE id = ?",
array($sequence, $next_item));
}
/**
* move_item_up - moves an item down by swapping it with the item above it
*
* @param $table_name - the table name that contains the target id
* @param $current_id - (int) the current id
* @param $group_query - an SQL "where" clause to limit the query
*/
function move_item_up($table_name, $current_id, $group_query = '') {
$last_item = get_item($table_name, 'sequence', $current_id, $group_query, 'previous');
$sequence = db_fetch_cell_prepared("SELECT sequence
FROM $table_name
WHERE id = ?",
array($current_id));
$sequence_last = db_fetch_cell_prepared("SELECT sequence
FROM $table_name
WHERE id = ?",
array($last_item));
db_execute_prepared("UPDATE $table_name
SET sequence = ?
WHERE id = ?",
array($sequence_last, $current_id));
db_execute_prepared("UPDATE $table_name
SET sequence = ?
WHERE id = ?",
array($sequence, $last_item));
}
/**
* exec_into_array - executes a command and puts each line of its output into
* an array
*
* @param $command_line - the command to execute
*
* @return - (array) an array containing the command output
*/
function exec_into_array($command_line) {
$out = array();
$err = 0;
exec($command_line,$out,$err);
return array_values($out);
}
/**
* get_web_browser - determines the current web browser in use by the client
*
* @return - ('ie' or 'moz' or 'other')
*/
function get_web_browser() {
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
if (stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla') && (!(stristr($_SERVER['HTTP_USER_AGENT'], 'compatible')))) {
return 'moz';
} elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
return 'ie';
} else {
return 'other';
}
} else {
return 'other';
}
}
/**
* draw_login_status - provides a consistent login status page for all pages that use it
*/
function draw_login_status($using_guest_account = false) {
global $config;
$guest_account = get_guest_account();
$auth_method = read_config_option('auth_method');
if (isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] === $guest_account) {
api_plugin_hook('nav_login_before');
print __('Logged in as') . " <span id='user' class='user usermenuup'>". __('guest') . "</span></div><div><ul class='menuoptions' style='display:none;'>" . ($auth_method != 2 ? "<li><a href='" . $config['url_path'] . "index.php?login=true'>" . __('Login as Regular User') . "</a></li>":"<li><a href='#'>" . __('Logged in a Guest') . '</a></li>');
print "<li class='menuHr'><hr class='menu'></li>";
print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank' rel='noopener'>" . __('User Community') . "</a></li>";
print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank' rel='noopener'>" . __('Documentation') . "</a></li>";
print "</ul>";
api_plugin_hook('nav_login_after');
} elseif (isset($_SESSION['sess_user_id']) && $using_guest_account == false) {
$user = db_fetch_row_prepared('SELECT username, password_change, realm
FROM user_auth
WHERE id = ?',
array($_SESSION['sess_user_id']));
api_plugin_hook('nav_login_before');
print __('Logged in as') . " <span id='user' class='user usermenuup'>" . html_escape($user['username']) .
"</span></div><div><ul class='menuoptions' style='display:none;'>";
print "<li><a href='#' class='loggedInAs' style='display:none;'>" . __esc('Logged in as %s', $user['username']) . "</a></li><hr class='menu'>";
print (is_realm_allowed(20) ? "<li><a href='" . html_escape($config['url_path'] . 'auth_profile.php?action=edit') . "'>" . __('Edit Profile') . '</a></li>':'');
print ($user['password_change'] == 'on' && $user['realm'] == 0 ? "<li><a href='" . html_escape($config['url_path'] . 'auth_changepassword.php') . "'>" . __('Change Password') . '</a></li>':'');
print ((is_realm_allowed(20) || ($user['password_change'] == 'on' && $user['realm'] == 0)) ? "<li class='menuHr'><hr class='menu'></li>":'');
if (is_realm_allowed(28)) {
print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank' rel='noopener'>" . __('User Community') . '</a></li>';
print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank' rel='noopener'>" . __('Documentation') . '</a></li>';
print "<li class='menuHr'><hr class='menu'></li>";
}
print ($auth_method > 0 && $auth_method != 2 ? "<li><a href='" . html_escape($config['url_path'] . 'logout.php') . "'>" . __('Logout') . '</a></li>':'');
print '</ul>';
api_plugin_hook('nav_login_after');
}
}
/**
* draw_navigation_text - determines the top header navigation text for the current page and displays it to
*
* @param $type - Either 'url' or 'title'
*
* @return - Either the navigation text or title
*/
function draw_navigation_text($type = 'url') {
global $config, $navigation;
$navigation = api_plugin_hook_function('draw_navigation_text', $navigation);
$current_page = get_current_page();
if (!isempty_request_var('action')) {
get_filter_request_var('action', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^([-a-zA-Z0-9_\s]+)$/')));
}
$current_action = (isset_request_var('action') ? get_request_var('action') : '');
// find the current page in the big array
if (isset($navigation[$current_page . ':' . $current_action])) {
$current_array = $navigation[$current_page . ':' . $current_action];
} else {
// If it's not set in the array, then default to a generic title
$current_array = array(
'mapping' => 'index.php:',
'title' => ucwords(str_replace('_', ' ', basename(get_current_page(), '.php'))),
'level' => 0
);
}
// Extract the full breadcrumb path from the current_array
if (isset($current_array['mapping'])) {
$current_mappings = explode(',', $current_array['mapping']);
} else {
$current_mappings = array();
}
$current_nav = "<ul id='breadcrumbs'>";
$title = '';
$nav_count = 0;
// resolve all mappings to build the navigation string
// this process is more simple than you might think
// we don't care about history as the breadcrumb is
// always based upon it's parent.
foreach($current_mappings as $i => $breadcrumb) {
$url = '';
if (empty($breadcrumb)) {
continue;
}
if ($i == 0) {
// Always use the default for level == 0
$url = $navigation[basename($breadcrumb)]['url'];
if (basename($url) == 'graph_view.php') {
continue;
}
} elseif (isset($current_array['url']) && $current_array['url'] != '') {
// Where the user specified a non-blank URL
$url = $current_array['url'];
} else {
// No 'url' was specified, so parse the breadcrumb path and use it
$parts = explode(':', $breadcrumb);
$url = $parts[0] . (isset($parts[1]) && $parts[1] != '' ? '?action=' . $parts[1]:'');
}
// Construct the list item and anchor from the 'url' if there was one. There should always
// be one.
$current_nav .= "<li><a id='nav_$i' href='" . (empty($url) ? '#':html_escape($url)) . "'>";
$current_nav .= html_escape(resolve_navigation_variables($navigation[basename($breadcrumb)]['title']));
$current_nav .= '</a>' . (get_selected_theme() == 'classic' ? ' > ':'') . '</li>';
$title .= html_escape(resolve_navigation_variables($navigation[basename($breadcrumb)]['title'])) . ' > ';
$nav_count++;
}
// Add a title for the current level
if ($nav_count) {
// We've already appended the full path, not the end bit
if (isset($current_array['title'])) {
$current_nav .= "<li><a id='nav_$i' href='#'>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>';
}
} else {
// No breadcrumb was found for the current path, make one up
$current_array = $navigation[$current_page . ':' . $current_action];
$url = (isset($current_array['url']) ? $current_array['url']:'');
if (isset($current_array['title'])) {
$current_nav .= "<li><a id='nav_$i' href='$url'>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>';
}
}
// Handle Special Navigation Cases of Tree's and External Links
if (isset_request_var('action') || get_nfilter_request_var('action') == 'tree_content') {
$tree_id = 0;
$leaf_id = 0;
if (isset_request_var('node')) {
$parts = explode('-', get_request_var('node'));
// Check for tree anchor
if (strpos(get_request_var('node'), 'tree_anchor') !== false) {
$tree_id = $parts[1];
$leaf_id = 0;
} elseif (strpos(get_request_var('node'), 'tbranch') !== false) {
// Check for branch
$leaf_id = $parts[1];
$tree_id = db_fetch_cell_prepared('SELECT graph_tree_id
FROM graph_tree_items
WHERE id = ?',
array($leaf_id));
}
}
if ($leaf_id > 0) {
$leaf = db_fetch_row_prepared('SELECT host_id, title, graph_tree_id
FROM graph_tree_items
WHERE id = ?',
array($leaf_id));
if (cacti_sizeof($leaf)) {
if ($leaf['host_id'] > 0) {
$leaf_name = db_fetch_cell_prepared('SELECT description
FROM host
WHERE id = ?',
array($leaf['host_id']));
} else {
$leaf_name = $leaf['title'];
}
$tree_name = db_fetch_cell_prepared('SELECT name
FROM graph_tree
WHERE id = ?',
array($leaf['graph_tree_id']));
} else {
$leaf_name = __('Leaf');
$tree_name = '';
}
if (isset_request_var('hgd') && get_nfilter_request_var('hgd') != '') {
$parts = explode(':', get_nfilter_request_var('hgd'));
input_validate_input_number($parts[1]);
if ($parts[0] == 'gt') {
$leaf_sub = db_fetch_cell_prepared('SELECT name
FROM graph_templates
WHERE id = ?',
array($parts[1]));
} else {
if ($parts[1] > 0) {
$leaf_sub = db_fetch_cell_prepared('SELECT name
FROM snmp_query
WHERE id = ?',
array($parts[1]));
} else {
$leaf_sub = __('Non Query Based');
}
}
} else {
$leaf_sub = '';
}
} else {
$leaf_name = '';
$leaf_sub = '';
if ($tree_id > 0) {
$tree_name = db_fetch_cell_prepared('SELECT name
FROM graph_tree
WHERE id = ?',
array($tree_id));
} else {
$tree_name = '';
}
}
$tree_title = $tree_name . ($leaf_name != '' ? ' (' . trim($leaf_name):'') . ($leaf_sub != '' ? ':' . trim($leaf_sub) . ')':($leaf_name != '' ? ')':''));
if ($tree_title != '') {
$current_nav .= "<li><a id='nav_title' href='#'>" . html_escape($tree_title) . '</a></li>';
}
} elseif (preg_match('#link.php\?id=(\d+)#', $_SERVER['REQUEST_URI'], $matches)) {
$externalLinks = db_fetch_row_prepared('SELECT title, style FROM external_links WHERE id = ?', array($matches[1]));
$title = $externalLinks['title'];
$style = $externalLinks['style'];
if ($style == 'CONSOLE') {
$current_nav = "<ul id='breadcrumbs'>
<li>
<a id='nav_0' href='" . $config['url_path'] . "index.php'>" . __('Console') . '</a>' . (get_selected_theme() == 'classic' ? ' > ':'') .
'</li>';
$current_nav .= "<li><a id='nav_1' href='#'>" . __('Link %s', html_escape($title)) . '</a></li>';
} else {
$current_nav = "<ul id='breadcrumbs'><li><a id='nav_0'>" . html_escape($title) . '</a></li>';
}
$tree_title = '';
} else {
$tree_title = '';
}
// Finally create a navigation title
if (isset($current_array['title'])) {
$title .= html_escape(resolve_navigation_variables($current_array['title']) . ' ' . $tree_title);
}
$current_nav .= '</ul>';
if ($type == 'url') {
return $current_nav;
} else {
return $title;
}
}
/**
* resolve_navigation_variables - substitute any variables contained in the navigation text
*
* @param $text - the text to substitute in
*
* @return - the original navigation text with all substitutions made
*/
function resolve_navigation_variables($text) {
$graphTitle = get_graph_title(get_filter_request_var('local_graph_id'));
if (preg_match_all("/\|([a-zA-Z0-9_]+)\|/", $text, $matches)) {
foreach($matches[1] as $i => $match) {
switch ($match) {
case 'current_graph_title':
$text = str_replace('|' . $match . '|', $graphTitle, $text);
break;
}
}
}
return $text;
}
/**
* get_associated_rras - returns a list of all RRAs referenced by a particular graph
*
* @param $local_graph_id - (int) the ID of the graph to retrieve a list of RRAs for
*
* @return - (array) an array containing the name and id of each RRA found
*/
function get_associated_rras($local_graph_id, $sql_where = '') {
return db_fetch_assoc_prepared('SELECT DISTINCT ' . SQL_NO_CACHE . "
dspr.id, dsp.step, dspr.steps, dspr.rows, dspr.name, dtd.rrd_step, dspr.timespan
FROM graph_templates_item AS gti
LEFT JOIN data_template_rrd AS dtr
ON gti.task_item_id=dtr.id
LEFT JOIN data_template_data AS dtd
ON dtr.local_data_id = dtd.local_data_id
LEFT JOIN data_source_profiles AS dsp
ON dtd.data_source_profile_id=dsp.id
LEFT JOIN data_source_profiles_rra AS dspr
ON dsp.id=dspr.data_source_profile_id
AND dtd.local_data_id != 0
WHERE gti.local_graph_id = ?
$sql_where
ORDER BY dspr.steps",
array($local_graph_id)
);
}
/**
* get_nearest_timespan - returns the nearest defined timespan. Used for adding a default
* graph timespan for data source profile rras.
*
* @param $timespan - (int) the timespan to fine a default for
*
* @return - (int) the timespan to apply for the data source profile rra value
*/
function get_nearest_timespan($timespan) {
global $timespans;
$last = end($timespans);
foreach($timespans as $index => $name) {
if ($timespan > $index) {
$last = $index;
continue;
} elseif ($timespan == $index) {
return $index;
} else {
return $last;
}
}
return $last;
}
/**
* get_browser_query_string - returns the full url, including args requested by the browser
*
* @return - the url requested by the browser
*/
function get_browser_query_string() {
if (!empty($_SERVER['REQUEST_URI'])) {
return sanitize_uri($_SERVER['REQUEST_URI']);
} else {
return sanitize_uri(get_current_page() . (empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING']));
}
}
/**
* get_current_page - returns the basename of the current page in a web server friendly way
*
* @return string The basename of the current script file
*/
function get_current_page($basename = true) {
if (isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME'] != '') {
if ($basename) {
return basename($_SERVER['SCRIPT_NAME']);
} else {
return $_SERVER['SCRIPT_NAME'];
}
} elseif (isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME'] != '') {
if ($basename) {
return basename($_SERVER['SCRIPT_FILENAME']);
} else {
return $_SERVER['SCRIPT_FILENAME'];
}
} else {
cacti_log('ERROR: unable to determine current_page');
}
return false;
}
/**
* get_hash_graph_template - returns the current unique hash for a graph template
*
* @param $graph_template_id - (int) the ID of the graph template to return a hash for
* @param $sub_type (optional) return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_graph_template($graph_template_id, $sub_type = 'graph_template') {
switch ($sub_type) {
case 'graph_template':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates WHERE id = ?', array($graph_template_id));
break;
case 'graph_template_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_item WHERE id = ?', array($graph_template_id));
break;
case 'graph_template_input':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_template_input WHERE id = ?', array($graph_template_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_data_template - returns the current unique hash for a data template
*
* @param $graph_template_id - (int) the ID of the data template to return a hash for
* @param $sub_type (optional) return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_data_template($data_template_id, $sub_type = 'data_template') {
switch ($sub_type) {
case 'data_template':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_template WHERE id = ?', array($data_template_id));
break;
case 'data_template_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_template_rrd WHERE id = ?', array($data_template_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_data_input - returns the current unique hash for a data input method
*
* @param $graph_template_id - (int) the ID of the data input method to return a hash for
* @param $sub_type (optional) return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_data_input($data_input_id, $sub_type = 'data_input_method') {
switch ($sub_type) {
case 'data_input_method':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_input WHERE id = ?', array($data_input_id));
break;
case 'data_input_field':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_input_fields WHERE id = ?', array($data_input_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_cdef - returns the current unique hash for a cdef
*
* @param $graph_template_id - (int) the ID of the cdef to return a hash for
* @param $sub_type (optional) return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_cdef($cdef_id, $sub_type = 'cdef') {
if (!is_numeric($cdef_id)) {
return generate_hash();
}
switch ($sub_type) {
case 'cdef':
$hash = db_fetch_cell_prepared('SELECT hash FROM cdef WHERE id = ?', array($cdef_id));
break;
case 'cdef_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM cdef_items WHERE id = ?', array($cdef_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_gprint - returns the current unique hash for a gprint preset
*
* @param $graph_template_id - (int) the ID of the gprint preset to return a hash for
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_gprint($gprint_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_gprint WHERE id = ?', array($gprint_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* returns the current unique hash for a vdef
*
* @param $graph_template_id - the ID of the vdef to return a hash for
* @param $sub_type - return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_vdef($vdef_id, $sub_type = "vdef") {
switch ($sub_type) {
case 'vdef':
$hash = db_fetch_cell_prepared('SELECT hash FROM vdef WHERE id = ?', array($vdef_id));
break;
case 'vdef_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM vdef_items WHERE id = ?', array($vdef_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_data_source_profile - returns the current unique hash for a vdef
*
* @param $data_source_profile_id - the ID of the data_source_profile to return a hash for
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_data_source_profile($data_source_profile_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM data_source_profiles WHERE id = ?', array($data_source_profile_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_host_template - returns the current unique hash for a gprint preset
*
* @param $host_template_id - the ID of the host template to return a hash for
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_host_template($host_template_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM host_template WHERE id = ?', array($host_template_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_data_query - returns the current unique hash for a data query
*
* @param $graph_template_id - the ID of the data query to return a hash for
* @param $sub_type return the hash for a particular subtype of this type
*
* @return - a 128-bit, hexadecimal hash
*/
function get_hash_data_query($data_query_id, $sub_type = 'data_query') {
switch ($sub_type) {
case 'data_query':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query WHERE id = ?', array($data_query_id));
break;
case 'data_query_graph':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph WHERE id = ?', array($data_query_id));
break;
case 'data_query_sv_data_source':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_rrd_sv WHERE id = ?', array($data_query_id));
break;
case 'data_query_sv_graph':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_sv WHERE id = ?', array($data_query_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* get_hash_version - returns the item type and cacti version in a hash format
*
* @param $type - the type of item to represent ('graph_template','data_template',
* 'data_input_method','cdef','vdef','gprint_preset','data_query','host_template')
*
* @return - a 24-bit hexadecimal hash (8-bits for type, 16-bits for version)
*/
function get_hash_version($type) {
global $hash_type_codes, $cacti_version_codes, $config;
return $hash_type_codes[$type] . $cacti_version_codes[CACTI_VERSION];
}
/**
* generate_hash - generates a new unique hash
*
* @return - a 128-bit, hexadecimal hash
*/
function generate_hash() {
return md5(session_id() . microtime() . rand(0,1000));
}
/**
* debug_log_insert_section_start - creates a header item for breaking down the debug log
*
* @param $type - the 'category' or type of debug message
* @param $text - section header
*/
function debug_log_insert_section_start($type, $text, $allowcopy = false) {
$copy_prefix = '';
$copy_dataid = '';
if ($allowcopy) {
$uid = generate_hash();
$copy_prefix = '<div class=\'cactiTableButton debug\'><span><a class=\'linkCopyDark cactiTableCopy\' id=\'copyToClipboard' . $uid . '\'>' . __esc('Copy') . '</a></span></div>';
$copy_dataid = ' id=\'clipboardData'.$uid.'\'';
$copy_headerid = ' id=\'clipboardHeader'.$uid.'\'';
}
debug_log_insert($type, '<table class=\'cactiTable debug\'' . $copy_headerid . '><tr class=\'tableHeader\'><td>' . html_escape($text) . $copy_prefix . '</td></tr><tr><td style=\'padding:0px;\'><table style=\'display:none;\'' . $copy_dataid . '><tr><td><div style=\'font-family: monospace;\'>');
}
/**
* debug_log_insert_section_end - finalizes the header started with the start function
*
* @param $type - the 'category' or type of debug message
*/
function debug_log_insert_section_end($type) {
debug_log_insert($type, '</div></td></tr></table></td></tr></td></table>');
}
/**
* debug_log_insert - inserts a line of text into the debug log
*
* @param $type - the 'category' or type of debug message
* @param $text - the actual debug message
*/
function debug_log_insert($type, $text) {
global $config;
if ($config['poller_id'] == 1 || isset($_SESSION)) {
if (!isset($_SESSION['debug_log'][$type])) {
$_SESSION['debug_log'][$type] = array();
}
array_push($_SESSION['debug_log'][$type], $text);
} else {
if (!isset($config['debug_log'][$type])) {
$config['debug_log'][$type] = array();
}
array_push($config['debug_log'][$type], $text);
}
}
/**
* debug_log_clear - clears the debug log for a particular category
*
* @param $type - the 'category' to clear the debug log for. omitting this argument
* implies all categories
*/
function debug_log_clear($type = '') {
if ($type == '') {
kill_session_var('debug_log');
} else {
if (isset($_SESSION['debug_log'])) {
unset($_SESSION['debug_log'][$type]);
}
}
}
/**
* debug_log_return - returns the debug log for a particular category.
*
* NOTE: Escaping is done in the insert functions.
*
* @param $type - the 'category' to return the debug log for.
*
* @return - the full debug log for a particular category
*/
function debug_log_return($type) {
$log_text = '';
if ($type == 'new_graphs') {
if (isset($_SESSION['debug_log'][$type])) {
$log_text .= "<table style='width:100%;'>";
foreach($_SESSION['debug_log'][$type] as $key => $val) {
$log_text .= '<tr><td>' . $val . '</td></tr>';
}
$log_text .= '</table>';
}
} else {
if (isset($_SESSION['debug_log'][$type])) {
$log_text .= "<table style='width:100%;'>";
foreach($_SESSION['debug_log'][$type] as $key => $val) {
$log_text .= '<tr><td>' . $val . '</td></tr>';
unset($_SESSION['debug_log'][$type][$key]);
}
$log_text .= '</table>';
}
}
return $log_text;
}
/**
* sanitize_search_string - cleans up a search string submitted by the user to be passed
* to the database. NOTE: some of the code for this function came from the phpBB project.
*
* @param $string - the original raw search string
*
* @return - the sanitized search string
*/
function sanitize_search_string($string) {
static $drop_char_match = array('(',')','^', '$', '<', '>', '`', '\'', '"', '|', ',', '?', '+', '[', ']', '{', '}', '#', ';', '!', '=', '*');
static $drop_char_replace = array('','',' ', ' ', ' ', ' ', '', '', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
/* Replace line endings by a space */
$string = preg_replace('/[\n\r]/is', ' ', $string);
/* HTML entities like */
$string = preg_replace('/\b&[a-z]+;\b/', ' ', $string);
/* Remove URL's */
$string = preg_replace('/\b[a-z0-9]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/]+)?/', ' ', $string);
/* Filter out strange characters like ^, $, &, change "it's" to "its" */
for($i = 0; $i < cacti_count($drop_char_match); $i++) {
$string = str_replace($drop_char_match[$i], $drop_char_replace[$i], $string);
}
return $string;
}
/**
* cleans up a URI, e.g. from REQUEST_URI and/or QUERY_STRING
* in case of XSS attack, expect the result to be broken
* we do NOT sanitize in a way, that attacks are converted to valid HTML
* it is ok, when the result is broken but the application stays alive
*
* @param string $uri - the uri to be sanitized
*
* @return string - the sanitized uri
*/
function sanitize_uri($uri) {
static $drop_char_match = array('^', '$', '<', '>', '`', "'", '"', '|', '+', '[', ']', '{', '}', ';', '!', '(', ')');
static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
if (strpos($uri, 'graph_view.php')) {
if (!strpos($uri, 'action=')) {
$uri = $uri . (strpos($uri, '?') ? '&':'?') . 'action=' . get_nfilter_request_var('action');
}
}
return str_replace($drop_char_match, $drop_char_replace, strip_tags(urldecode($uri)));
}
/**
* Checks to see if a string is base64 encoded
*
* @param string $data - the string to be validated
*
* @return boolean - true is the string is base64 otherwise false
*/
function is_base64_encoded($data) {
// Perform a simple check first
if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $data)) {
return false;
}
// Now test with the built-in function
$ndata = base64_decode($data, true);
if ($ndata === false) {
return false;
}
// Do a re-encode test and compare
if (base64_encode($ndata) != $data) {
return false;
}
return true;
}
/**
* cleans up a CDEF/VDEF string
* the CDEF/VDEF must have passed all magic string replacements beforehand
*
* @param string $cdef - the CDEF/VDEF to be sanitized
*
* @return string - the sanitized CDEF/VDEF
*/
function sanitize_cdef($cdef) {
static $drop_char_match = array('^', '$', '<', '>', '`', '\'', '"', '|', '[', ']', '{', '}', ';', '!');
static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '');
return str_replace($drop_char_match, $drop_char_replace, $cdef);
}
/**
* verifies all selected items are numeric to guard against injection
*
* @param string $items An array of serialized items from a post
*
* @return array The sanitized selected items array
*/
function sanitize_unserialize_selected_items($items) {
if ($items != '') {
$unstripped = stripslashes($items);
// validate that sanitized string is correctly formatted
if (preg_match('/^a:[0-9]+:{/', $unstripped) && !preg_match('/(^|;|{|})O:\+?[0-9]+:"/', $unstripped)) {
if(version_compare(PHP_VERSION, '7.0.0', '>=')) {
$items = unserialize($unstripped, array('allowed_classes' => false));
} else {
$items = unserialize($unstripped);
}
if (is_array($items)) {
foreach ($items as $item) {
if (is_array($item)) {
return false;
} elseif (!is_numeric($item) && ($item != '')) {
return false;
}
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
return $items;
}
function cacti_escapeshellcmd($string) {
global $config;
if ($string == '') {
return $string;
}
if ($config['cacti_server_os'] == 'unix') {
return escapeshellcmd($string);
} else {
$replacements = "#&;`|*?<>^()[]{}$\\";
for ($i=0; $i < strlen($replacements); $i++) {
$string = str_replace($replacements[$i], ' ', $string);
}
return $string;
}
}
/**
* mimics escapeshellarg, even for windows
*
* @param $string - the string to be escaped
* @param $quote - true: do NOT remove quotes from result; false: do remove quotes
*
* @return - the escaped [quoted|unquoted] string
*/
function cacti_escapeshellarg($string, $quote = true) {
global $config;
if ($string == '') {
return $string;
}
/* remove any carriage returns or line feeds from the argument */
$string = str_replace(array("\n", "\r"), array('', ''), $string);
/*
* we must use an apostrophe to escape community names under Unix in case the user uses
* characters that the shell might interpret. the ucd-snmp binaries on Windows flip out when
* you do this, but are perfectly happy with a quotation mark.
*/
if ($config['cacti_server_os'] == 'unix') {
$string = escapeshellarg($string);
if ($quote) {
return $string;
} else {
# remove first and last char
return substr($string, 1, (strlen($string)-2));
}
} else {
/**
* escapeshellarg takes care of different quotation for both linux and windows,
* but unfortunately, it blanks out percent signs
* we want to keep them, e.g. for GPRINT format strings
* so we need to create our own escapeshellarg
* on windows, command injection requires to close any open quotation first
* so we have to escape any quotation here
*/
if (substr_count($string, CACTI_ESCAPE_CHARACTER)) {
$string = str_replace(CACTI_ESCAPE_CHARACTER, "\\" . CACTI_ESCAPE_CHARACTER, $string);
}
/* ... before we add our own quotation */
if ($quote) {
return CACTI_ESCAPE_CHARACTER . $string . CACTI_ESCAPE_CHARACTER;
} else {
return $string;
}
}
}
/**
* set a page refresh in Cacti through a callback
*
* @param $refresh - an array containing the page, seconds, and logout
*
* @return - nill
*/
function set_page_refresh($refresh) {
if (isset($refresh['seconds'])) {
$_SESSION['refresh']['seconds'] = $refresh['seconds'];
}
if (read_config_option('auth_cache_enabled') == 'on' && isset($_SESSION['cacti_remembers']) && $_SESSION['cacti_remembers'] == true) {
$_SESSION['refresh']['logout'] = 'false';
} elseif (isset($refresh['logout'])) {
if ($refresh['logout'] == 'true' || $refresh['logout'] === true) {
$_SESSION['refresh']['logout'] = 'true';
} else {
$_SESSION['refresh']['logout'] = 'false';
}
} else {
$_SESSION['refresh']['logout'] = 'true';
}
if (isset($refresh['page'])) {
$_SESSION['refresh']['page'] = $refresh['page'];
}
}
function bottom_footer() {
global $config, $no_session_write;
include_once($config['base_path'] . '/include/global_session.php');
if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') {
include_once($config['base_path'] . '/include/bottom_footer.php');
}
/* we use this session var to store field values for when a save fails,
this way we can restore the field's previous values. we reset it here, because
they only need to be stored for a single page
*/
kill_session_var('sess_field_values');
/* make sure the debug log doesn't get too big */
debug_log_clear();
/* close the session */
if (array_search(get_current_page(), $no_session_write) === false) {
cacti_session_close();
}
/* close the database connection */
db_close();
}
function top_header() {
global $config;
if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') {
include_once($config['base_path'] . '/include/top_header.php');
}
}
function top_graph_header() {
global $config;
if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') {
include_once($config['base_path'] . '/include/top_graph_header.php');
}
}
function general_header() {
global $config;
if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') {
include_once($config['base_path'] . '/include/top_general_header.php');
}
}
function appendHeaderSuppression($url) {
if (strpos($url, 'header=false') < 0) {
return $url . (strpos($url, '?') ? '&':'?') . 'header=false';
}
return $url;
}
function admin_email($subject, $message) {
if (read_config_option('admin_user') > 0) {
if (read_config_option('notify_admin') == 'on') {
$admin_details = db_fetch_row_prepared('SELECT full_name, email_address
FROM user_auth
WHERE id = ?',
array(read_config_option('admin_user')));
if (cacti_sizeof($admin_details)) {
$email = read_config_option('settings_from_email');
$name = read_config_option('settings_from_name');
if ($name != '') {
$from = '"' . $name . '" <' . $email . '>';
} else {
$from = $email;
}
if ($admin_details['email_address'] != '') {
if ($admin_details['full_name'] != '') {
$to = '"' . $admin_details['full_name'] . '" <' . $admin_details['email_address'] . '>';
} else {
$to = $admin_details['email_address'];
}
send_mail($to, $from, $subject, $message, '', '', true);
} else {
cacti_log('WARNING: Primary Admin account does not have an email address! Unable to send administrative Email.', false, 'SYSTEM');
}
} else {
cacti_log('WARNING: Primary Admin account set to an invalid user! Unable to send administrative Email.', false, 'SYSTEM');
}
} else {
cacti_log('WARNING: Primary Admin account notifications disabled! Unable to send administrative Email.', false, 'SYSTEM');
}
} else {
cacti_log('WARNING: Primary Admin account not set! Unable to send administrative Email.', false, 'SYSTEM');
}
}
function send_mail($to, $from, $subject, $body, $attachments = '', $headers = '', $html = false) {
$fromname = '';
if (is_array($from)) {
$fromname = $from[1];
$from = $from[0];
}
if ($from == '') {
$from = read_config_option('settings_from_email');
$fromname = read_config_option('settings_from_name');
} elseif ($fromname == '') {
$full_name = db_fetch_cell_prepared('SELECT full_name
FROM user_auth
WHERE email_address = ?',
array($from));
if (empty($full_name)) {
$fromname = $from;
} else {
$fromname = $full_name;
}
}
$from = array(0 => $from, 1 => $fromname);
return mailer($from, $to, '', '', '', $subject, $body, '', $attachments, $headers, $html);
}
/**
* mailer - function to send mails to users
*
* @param $from - single contact (see below)
* @param $to - single or multiple contacts (see below)
* @param $cc - none, single or multiple contacts (see below)
* @param $bcc - none, single or multiple contacts (see below)
* @param $replyto - none, single or multiple contacts (see below)
* note that this value is used when hitting reply (overriding the default of using from)
* @param $subject - the email subject
* @param $body - the email body, in HTML format. If content_text is not set, the function will attempt to extract
* from the HTML format.
* @param $body_text - the email body in TEXT format. If set, it will override the stripping tags method
* @param $attachments - the emails attachments as an array
* @param $headers - an array of name value pairs representing custom headers.
* @param $html - if set to true, html is the default, otherwise text format will be used
*
* For contact parameters, they can accept arrays containing zero or more values in the forms of:
* 'email@email.com,email2@email.com,email3@email.com'
* array('email1@email.com' => 'My email', 'email2@email.com' => 'Your email', 'email3@email.com' => 'Whose email')
* array(array('email' => 'email1@email.com', 'name' => 'My email'), array('email' => 'email2@email.com',
* 'name' => 'Your email'), array('email' => 'email3@email.com', 'name' => 'Whose email'))
*
* The $from field will only use the first contact specified. If no contact is provided for $replyto
* then $from is used for that too. If $from is empty, it will default to cacti@<server> or if no server name can
* be found, it will use cacti@cacti.net
*
* The $attachments parameter may either be a single string, or a list of attachments
* either as strings or an array. The array can have the following keys:
*
* filename : name of the file to attach (display name for graphs)
* display : displayed name of the attachment
* mime_type : MIME type to be set against the attachment. If blank or missing mailer will attempt to auto detect
* attachment : String containing attachment for image-based attachments (<GRAPH> or <GRAPH:#> activates graph mode
* and requires $body parameter is HTML containing one of those values)
* inline : Whether to attach 'inline' (default for graph mode) or as 'attachment' (default for all others)
* encoding : Encoding type, normally base64
*/
function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments = '', $headers = '', $html = true) {
global $config, $cacti_locale, $mail_methods;
require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php');
require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php');
require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php');
$start_time = microtime(true);
// Create the PHPMailer instance
$mail = new PHPMailer\PHPMailer\PHPMailer;
// Set a reasonable timeout of 5 seconds
$timeout = read_config_option('settings_smtp_timeout');
if (empty($timeout) || $timeout < 0 || $timeout > 300) {
$mail->Timeout = 5;
} else {
$mail->Timeout = $timeout;
}
$langparts = explode('-', $cacti_locale);
if (file_exists($config['include_path'] . '/vendor/phpmailer/language/phpmailer.lang-' . $langparts[0] . '.php')) {
$mail->setLanguage($langparts[0], $config['include_path'] . '/vendor/phpmailer/language/');
}
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2) {
$how = 0;
}
if ($how == 0) {
$mail->isMail();
} elseif ($how == 1) {
$mail->Sendmail = read_config_option('settings_sendmail_path');
$mail->isSendmail();
} elseif ($how == 2) {
$mail->isSMTP();
$mail->Host = read_config_option('settings_smtp_host');
$mail->Port = read_config_option('settings_smtp_port');
if (read_config_option('settings_smtp_username') != '') {
$mail->SMTPAuth = true;
$mail->Username = read_config_option('settings_smtp_username');
if (read_config_option('settings_smtp_password') != '') {
$mail->Password = read_config_option('settings_smtp_password');
}
} else {
$mail->SMTPAuth = false;
}
$secure = read_config_option('settings_smtp_secure');
if (!empty($secure) && $secure != 'none') {
$mail->SMTPSecure = true;
if (substr_count($mail->Host, ':') == 0) {
$mail->Host = $secure . '://' . $mail->Host;
}
} else {
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
}
}
/* perform data substitution */
if (strpos($subject, '|date_time|') !== false) {
$date = read_config_option('date');
if (!empty($date)) {
$time = strtotime($date);
} else {
$time = time();
}
$subject = str_replace('|date_time|', date(CACTI_DATE_TIME_FORMAT, $time), $subject);
}
/*
* Set the from details using the variable passed in
* - if name is blank, use setting's name
* - if email is blank, use setting's email, otherwise default to
* cacti@<server> or cacti@cacti.net if no known server name
*/
$from = parse_email_details($from, 1);
// from name was empty, use value in settings
if (empty($from['name'])) {
$from['name'] = read_config_option('settings_from_name');
}
// from email was empty, use email in settings
if (empty($from['email'])) {
$from['email'] = read_config_option('settings_from_email');
}
if (empty($from['email'])) {
if (isset($_SERVER['HOSTNAME'])) {
$from['email'] = 'Cacti@' . $_SERVER['HOSTNAME'];
} else {
$from['email'] = 'Cacti@cacti.net';
}
if (empty($from['name'])) {
$from['name'] = 'Cacti';
}
}
// Sanity test the from email
if (!filter_var($from['email'], FILTER_VALIDATE_EMAIL)) {
return 'Bad email address format. Invalid from email address ' . $from['email'];
}
$fromText = add_email_details(array($from), $result, array($mail, 'setFrom'));
if ($result == false) {
return record_mailer_error($fromText, $mail->ErrorInfo);
}
// Convert $to variable to proper array structure
$to = parse_email_details($to);
$toText = add_email_details($to, $result, array($mail, 'addAddress'));
if ($result == false) {
return record_mailer_error($toText, $mail->ErrorInfo);
}
$cc = parse_email_details($cc);
$ccText = add_email_details($cc, $result, array($mail, 'addCC'));
if ($result == false) {
return record_mailer_error($ccText, $mail->ErrorInfo);
}
$bcc = parse_email_details($bcc);
$bccText = add_email_details($bcc, $result, array($mail, 'addBCC'));
if ($result == false) {
return record_mailer_error($bccText, $mail->ErrorInfo);
}
// This is a failsafe, should never happen now
if (!(cacti_sizeof($to) || cacti_sizeof($cc) || cacti_sizeof($bcc))) {
cacti_log('ERROR: No recipient address set!!', false, 'MAILER');
cacti_debug_backtrace('MAILER ERROR');
return __('Mailer Error: No recipient address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.');
}
$replyto = parse_email_details($replyto);
$replyText = add_email_details($replyto, $result, array($mail, 'addReplyTo'));
if ($result == false) {
return record_mailer_error($replyText, $mail->ErrorInfo);
}
$body = str_replace('<SUBJECT>', $subject, $body);
$body = str_replace('<TO>', $toText, $body);
$body = str_replace('<CC>', $ccText, $body);
$body = str_replace('<FROM>', $fromText, $body);
$body = str_replace('<REPLYTO>', $replyText, $body);
$body_text = str_replace('<SUBJECT>', $subject, $body_text);
$body_text = str_replace('<TO>', $toText, $body_text);
$body_text = str_replace('<CC>', $ccText, $body_text);
$body_text = str_replace('<FROM>', $fromText, $body_text);
$body_text = str_replace('<REPLYTO>', $replyText, $body_text);
// Set the subject
$mail->Subject = $subject;
// Support i18n
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
// Set the wordwrap limits
$wordwrap = read_config_option('settings_wordwrap');
if ($wordwrap == '') {
$wordwrap = 76;
} elseif ($wordwrap > 9999) {
$wordwrap = 9999;
} elseif ($wordwrap < 0) {
$wordwrap = 76;
}
$mail->WordWrap = $wordwrap;
$mail->setWordWrap();
if (!$html) {
$mail->ContentType = 'text/plain';
} else {
$mail->ContentType = 'text/html';
}
$i = 0;
// Handle Graph Attachments
if (!empty($attachments) && !is_array($attachments)) {
$attachments = array('attachment' => $attachments);
}
if (is_array($attachments) && cacti_sizeof($attachments)) {
$graph_mode = (substr_count($body, '<GRAPH>') > 0);
$graph_ids = (substr_count($body, '<GRAPH:') > 0);
$default_opts = array(
// MIME type to be set against the attachment
'mime_type' => '',
// Display name of the attachment
'filename' => '',
// String containing attachment for image-based attachments
'attachment' => '',
// Whether to attach inline or as attachment
'inline' => ($graph_mode || $graph_ids) ? 'inline' : 'attachment',
// Encoding type, normally base64
'encoding' => 'base64',
);
foreach($attachments as $attachment) {
if (!is_array($attachment)) {
$attachment = array('attachment' => $attachment);
}
foreach ($default_opts as $opt_name => $opt_default) {
if (!array_key_exists($opt_name, $attachment)) {
$attachment[$opt_name] = $opt_default;
}
}
if (!empty($attachment['attachment'])) {
/* get content id and create attachment */
$cid = getmypid() . '_' . $i . '@' . 'localhost';
if (empty($attachment['filename']) && file_exists($attachment['attachment'])) {
$attachment['filename'] = $attachment['attachment'];
}
/* attempt to attach */
if (!($graph_mode || $graph_ids)) {
if (!empty($attachment['attachment']) && @file_exists($attachment['attachment'])) {
$result = $mail->addAttachment($attachment['attachment'], $attachment['filename'], $attachment['encoding'], $attachment['mime_type'], $attachment['inline']);
} else {
$result = $mail->addStringAttachment($attachment['attachment'], $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']);
}
} else {
if (!empty($attachment['attachment']) && @file_exists($attachment['attachment'])) {
$result = $mail->addEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], $attachment['encoding'], $attachment['mime_type'], $attachment['inline']);
} else {
$result = $mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']);
}
}
if ($result == false) {
cacti_log('ERROR: ' . $mail->ErrorInfo, false, 'MAILER');
return $mail->ErrorInfo;
}
$i++;
if ($graph_mode) {
$body = str_replace('<GRAPH>', "<br><br><img src='cid:$cid'>", $body);
} elseif ($graph_ids) {
/* handle the body text */
switch ($attachment['inline']) {
case 'inline':
$body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', "<img src='cid:$cid' >", $body);
break;
case 'attachment':
$body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', '', $body);
break;
}
}
}
}
}
/* process custom headers */
if (is_array($headers) && cacti_sizeof($headers)) {
foreach($headers as $name => $value) {
$mail->addCustomHeader($name, $value);
}
}
// Set both html and non-html bodies
$brs = array('<br>', '<br />', '</br>');
if ($html) {
$body = $body . '<br>';
}
if ($body_text == '') {
$body_text = strip_tags(str_ireplace($brs, "\n", $body));
}
$mail->isHTML($html);
$mail->Body = ($html ? $body : $body_text);
if ($html && $body_text != '') {
$mail->AltBody = $body_text;
}
$result = $mail->send();
$error = $mail->ErrorInfo; //$result ? '' : $mail->ErrorInfo;
$method = $mail_methods[intval(read_config_option('settings_how'))];
$rtype = $result ? 'INFO' : 'WARNING';
$rmsg = $result ? 'successfully sent' : 'failed';
$end_time = microtime(true);
if ($error != '') {
$message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', bcc '%s', and took %2.2f seconds, Subject '%s'%s",
$rtype, $rmsg, $method, $fromText, $toText, $ccText, $bccText, ($end_time - $start_time), $subject,
", Error: $error");
} else {
$message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', bcc '%s', and took %2.2f seconds, Subject '%s'",
$rtype, $rmsg, $method, $fromText, $toText, $ccText, $bccText, ($end_time - $start_time), $subject);
}
cacti_log($message, false, 'MAILER');
if ($result == false) {
$backtrace = cacti_debug_backtrace($rtype);
if ($backtrace != '') {
cacti_log($backtrace, false, 'MAILER');
}
}
return $error;
}
function record_mailer_error($retError, $mailError) {
$errorInfo = empty($retError) ? $mailError : $retError;
cacti_log('ERROR: ' . $errorInfo, false, 'CMDPHP MAILER');
cacti_debug_backtrace('MAILER ERROR');
return $errorInfo;
}
function add_email_details($emails, &$result, callable $addFunc) {
$arrText = array();
foreach ($emails as $e) {
if (!empty($e['email'])) {
//if (is_callable($addFunc)) {
if (!empty($addFunc)) {
$result = $addFunc($e['email'], $e['name']);
if (!$result) {
return '';
}
}
$arrText[] = create_emailtext($e);
} elseif (!empty($e['name'])) {
$result = false;
return 'Bad email format, name but no address: ' . $e['name'];
}
}
$text = implode(',', $arrText);
//print "add_email_sw_details(): $text\n";
return $text;
}
function parse_email_details($emails, $max_records = 0, $details = array()) {
if (!is_array($emails)) {
$emails = array($emails);
}
$update = array();
foreach ($emails as $check_email) {
if (!empty($check_email)) {
if (!is_array($check_email)) {
$emails = explode(',', $check_email);
foreach($emails as $email) {
$email_array = split_emaildetail($email);
$details[$email_array['email']] = $email_array;
}
} else {
$has_name = array_key_exists('name', $check_email);
$has_email = array_key_exists('email', $check_email);
if ($has_name || $has_email) {
$name = $has_name ? $check_email['name'] : '';
$email = $has_email ? $check_email['email'] : '';
} else {
$name = array_key_exists(1, $check_email) ? $check_email[1] : '';
$email = array_key_exists(0, $check_email) ? $check_email[0] : '';
}
$details[trim(strtolower($email))] = array('name' => trim($name), 'email' => trim(strtolower($email)));
}
}
}
if ($max_records == 1) {
$detail = reset($details);
$results = is_array($detail) ? $detail : array();
} elseif ($max_records != 0 && $max_records < count($details)) {
$results = array();
foreach ($details as $d) {
$results[] = $d;
$max_records--;
if ($max_records == 0) {
break;
}
}
} else {
$results = $details;
}
return $results;
}
function split_emaildetail($email) {
$rname = '';
$rmail = '';
if (!is_array($email)) {
$email = trim($email);
$sPattern = '/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/i';
preg_match($sPattern, $email, $aMatch);
if (isset($aMatch[1])) {
$rname = trim($aMatch[1]);
}
if (isset($aMatch[2])) {
$rmail = trim($aMatch[2]);
}
} else {
$rmail = $email[0];
$rname = $email[1];
}
return array('name' => $rname, 'email' => strtolower($rmail));
}
function create_emailtext($e) {
if (empty($e['email'])) {
$text = '';
} else {
if (empty($e['name'])) {
$text = $e['email'];
} else {
$text = $e['name'] . ' <' . $e['email'] . '>';
}
}
return $text;
}
function ping_mail_server($host, $port, $user, $password, $timeout = 10, $secure = 'none') {
global $config;
require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php');
require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php');
require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php');
//Create a new SMTP instance
$smtp = new PHPMailer\PHPMailer\SMTP;
if (!empty($secure) && $secure != 'none') {
if (substr_count($host, ':') == 0) {
$host = $secure . '://' . $host;
}
}
//Enable connection-level debug output
$smtp->do_debug = 0;
//$smtp->do_debug = SMTP::DEBUG_LOWLEVEL;
$results = true;
try {
//Connect to an SMTP server
if ($smtp->connect($host, $port, $timeout)) {
//Say hello
if ($smtp->hello(gethostbyname(gethostname()))) { //Put your host name in here
//Authenticate
if ($user != '') {
if ($smtp->authenticate($user, $password)) {
$results = true;
} else {
throw new Exception(__('Authentication failed: %s', $smtp->getLastReply()));
}
}
} else {
throw new Exception(__('HELO failed: %s', $smtp->getLastReply()));
}
} else {
throw new Exception(__('Connect failed: %s', $smtp->getLastReply()));
}
} catch (Exception $e) {
$results = __('SMTP error: ') . $e->getMessage();
cacti_log($results);
}
//Whatever happened, close the connection.
$smtp->quit(true);
return $results;
}
function email_test() {
global $config;
$message = __('This is a test message generated from Cacti. This message was sent to test the configuration of your Mail Settings.') . '<br><br>';
$message .= __('Your email settings are currently set as follows') . '<br><br>';
$message .= '<b>' . __('Method') . '</b>: ';
print __('Checking Configuration...<br>');
$ping_results = true;
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2)
$how = 0;
if ($how == 0) {
$mail = __('PHP\'s Mailer Class');
} elseif ($how == 1) {
$mail = __('Sendmail') . '<br><b>' . __('Sendmail Path'). '</b>: ';
$sendmail = read_config_option('settings_sendmail_path');
$mail .= $sendmail;
} elseif ($how == 2) {
print __('Method: SMTP') . '<br>';
$mail = __('SMTP') . '<br>';
$smtp_host = read_config_option('settings_smtp_host');
$smtp_port = read_config_option('settings_smtp_port');
$smtp_username = read_config_option('settings_smtp_username');
$smtp_password = read_config_option('settings_smtp_password');
$smtp_secure = read_config_option('settings_smtp_secure');
$smtp_timeout = read_config_option('settings_smtp_timeout');
$mail .= "<b>" . __('Device') . "</b>: $smtp_host<br>";
$mail .= "<b>" . __('Port') . "</b>: $smtp_port<br>";
if ($smtp_username != '' && $smtp_password != '') {
$mail .= '<b>' . __('Authentication') . '</b>: true<br>';
$mail .= '<b>' . __('Username') . "</b>: $smtp_username<br>";
$mail .= '<b>' . __('Password') . '</b>: (' . __('Not Shown for Security Reasons') . ')<br>';
$mail .= '<b>' . __('Security') . "</b>: $smtp_secure<br>";
} else {
$mail .= '<b>' . __('Authentication') . '</b>: false<br>';
}
if (read_config_option('settings_ping_mail') == 0) {
$ping_results = ping_mail_server($smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_timeout, $smtp_secure);
print __('Ping Results:') . ' ' . ($ping_results == 1 ? __('Success'):$ping_results) . '<br>';
if ($ping_results != 1) {
$mail .= '<b>' . __('Ping Results') . '</b>: ' . $ping_results . '<br>';
} else {
$mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Success') . '<br>';
}
} else {
$ping_results = 1;
$mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Bypassed') . '<br>';
}
}
$message .= $mail;
$message .= '<br>';
$errors = '';
if ($ping_results == 1) {
print __('Creating Message Text...') . '<br><br>';
print "<center><table><tr><td>";
print "<table style='width:100%;'><tr><td>$message</td><tr></table></table></center><br>";
print __('Sending Message...') . '<br><br>';
$global_alert_address = read_config_option('settings_test_email');
$errors = send_mail($global_alert_address, '', __('Cacti Test Message'), $message, '', '', true);
if ($errors == '') {
$errors = __('Success!');
}
} else {
print __('Message Not Sent due to ping failure.'). '<br><br>';
}
print "<center><table><tr><td>";
print "<table><tr><td>$errors</td><tr></table></table></center>";
}
/**
* gethostbyaddr_wtimeout - This function provides a good method of performing
* a rapid lookup of a DNS entry for a host so long as you don't have to look far.
*/
function get_dns_from_ip ($ip, $dns, $timeout = 1000) {
/* random transaction number (for routers etc to get the reply back) */
$data = rand(10, 99);
/* trim it to 2 bytes */
$data = substr($data, 0, 2);
/* create request header */
$data .= "\1\0\0\1\0\0\0\0\0\0";
/* split IP into octets */
$octets = explode('.', $ip);
/* perform a quick error check */
if (cacti_count($octets) != 4) return 'ERROR';
/* needs a byte to indicate the length of each segment of the request */
for ($x=3; $x>=0; $x--) {
switch (strlen($octets[$x])) {
case 1: // 1 byte long segment
$data .= "\1"; break;
case 2: // 2 byte long segment
$data .= "\2"; break;
case 3: // 3 byte long segment
$data .= "\3"; break;
default: // segment is too big, invalid IP
return 'ERROR';
}
/* and the segment itself */
$data .= $octets[$x];
}
/* and the final bit of the request */
$data .= "\7in-addr\4arpa\0\0\x0C\0\1";
/* create UDP socket */
$handle = @fsockopen("udp://$dns", 53);
@stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000);
@stream_set_blocking($handle, 1);
/* send our request (and store request size so we can cheat later) */
$requestsize = @fwrite($handle, $data);
/* get the response */
$response = @fread($handle, 1000);
/* check to see if it timed out */
$info = @stream_get_meta_data($handle);
/* close the socket */
@fclose($handle);
if ($info['timed_out']) {
return 'timed_out';
}
/* more error handling */
if ($response == '') { return $ip; }
/* parse the response and find the response type */
$type = @unpack('s', substr($response, $requestsize+2));
if (isset($type[1]) && $type[1] == 0x0C00) {
/* set up our variables */
$host = '';
$len = 0;
/* set our pointer at the beginning of the hostname uses the request
size from earlier rather than work it out.
*/
$position = $requestsize + 12;
/* reconstruct the hostname */
do {
/* get segment size */
$len = unpack('c', substr($response, $position));
/* null terminated string, so length 0 = finished */
if ($len[1] == 0) {
/* return the hostname, without the trailing '.' */
return strtoupper(substr($host, 0, strlen($host) -1));
}
/* add the next segment to our host */
$host .= substr($response, $position+1, $len[1]) . '.';
/* move pointer on to the next segment */
$position += $len[1] + 1;
} while ($len != 0);
/* error - return the hostname we constructed (without the . on the end) */
return strtoupper($ip);
}
/* error - return the hostname */
return strtoupper($ip);
}
function poller_maintenance () {
global $config;
$command_string = cacti_escapeshellcmd(read_config_option('path_php_binary'));
// If its not set, just assume its in the path
if (empty($command_string) || trim($command_string) == '') {
$command_string = 'php';
}
$extra_args = ' -q ' . cacti_escapeshellarg($config['base_path'] . '/poller_maintenance.php');
exec_background($command_string, $extra_args);
}
function clog_admin() {
if (!isset($_SESSION['sess_clog_level'])) {
clog_authorized();
}
if ($_SESSION["sess_clog_level"] == CLOG_PERM_ADMIN) {
return true;
} else {
return false;
}
}
function clog_authorized() {
if (!isset($_SESSION['sess_clog_level'])) {
if (isset($_SESSION['sess_user_id'])) {
if (is_realm_allowed(18)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_ADMIN;
} else {
if (is_realm_allowed(19)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_USER;
} else {
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
} else {
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
if ($_SESSION['sess_clog_level'] == CLOG_PERM_USER) {
return true;
} elseif ($_SESSION['sess_clog_level'] == CLOG_PERM_ADMIN) {
return true;
} else {
return false;
}
}
function cacti_debug_backtrace($entry = '', $html = false, $record = true, $limit = 0, $skip = 0) {
global $config;
$skip = $skip >= 0 ? $skip : 1;
$limit = $limit > 0 ? ($limit + $skip) : 0;
$callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $limit);
while ($skip > 0) {
array_shift($callers);
$skip--;
}
$s='';
foreach ($callers as $c) {
if (isset($c['line'])) {
$line = '[' . $c['line'] . ']';
} else {
$line = '';
}
if (isset($c['file'])) {
$file = str_replace($config['base_path'], '', $c['file']) . $line;
} else {
$file = $line;
}
$func = $c['function'].'()';
if (isset($c['class'])) {
$func = $c['class'] . $c['type'] . $func;
}
$s = ($file != '' ? $file . ':':'') . "$func" . (empty($s) ? '' : ', ') . $s;
}
if (!empty($s)) {
$s = ' (' . $s . ')';
}
if ($record) {
if ($html) {
print "<table style='width:100%;text-align:center;'><tr><td>$s</td></tr></table>\n";
}
cacti_log(trim("$entry Backtrace: " . clean_up_lines($s)), false);
} else {
if (!empty($entry)) {
return trim("$entry Backtrace: " . clean_up_lines($s));
} else {
return trim(clean_up_lines($s));
}
}
}
/**
* calculate_percentiles - Given and array of numbers, calculate the Nth percentile,
* optionally, return an array of numbers containing elements required for
* a whisker chart.
*
* @param $data - an array of data
* @param $percentile - the Nth percentile to calculate. By default 95th.
* @param $whisker - if whisker is true, an array of values will be returned
* including 25th, median, 75th, and 90th percentiles.
*
* @return - either the Nth percentile, the elements for a whisker chart,
* or false if there is insufficient data to determine.
*/
function calculate_percentiles($data, $percentile = 95, $whisker = false) {
if ($percentile > 0 && $percentile < 1) {
$p = $percentile;
} elseif ($percentile > 1 && $percentile <= 100) {
$p = $percentile * .01;
} else {
return false;
}
if ($whisker) {
$tiles = array(
'25th' => 0.25,
'50th' => 0.50,
'75th' => 0.75,
'90th' => 0.90,
'95th' => 0.95,
);
} else {
$tiles = array(
'custom' => $p
);
}
$results = array();
$elements = cacti_sizeof($data);
/* sort the array to return */
sort($data);
foreach($tiles as $index => $p) {
/* calculate offsets into the array */
$allindex = ($elements - 1) * $p;
$intvalindex = floor($allindex);
$floatval = $allindex - $intvalindex;
if (!is_float($floatval)) {
$ptile = $data[$intvalindex];
} else {
if ($elements > $intvalindex + 1) {
$ptile = $floatval * ($data[$intvalindex + 1] - $data[$intvalindex]) + $data[$intvalindex];
} else {
$ptile = $data[$intvalindex];
}
}
if ($index == 'custom') {
return $ptile;
} else {
$results[$index] = $ptile;
}
}
return $results;
}
function get_timeinstate($host) {
$interval = read_config_option('poller_interval');
if ($host['availability_method'] == 0) {
$time = 0;
} elseif (isset($host['instate'])) {
$time = $host['instate'];
} elseif ($host['status_event_count'] > 0 && ($host['status'] == 1 || $host['status'] == 2 || $host['status'] == 5)) {
$time = $host['status_event_count'] * $interval;
} elseif (strtotime($host['status_rec_date']) < 943916400 && ($host['status'] == 0 || $host['status'] == 3)) {
$time = $host['total_polls'] * $interval;
} elseif (strtotime($host['status_rec_date']) > 943916400) {
$time = time() - strtotime($host['status_rec_date']);
} elseif ($host['snmp_sysUpTimeInstance'] > 0) {
$time = $host['snmp_sysUpTimeInstance']/100;
} else {
$time = 0;
}
if ($time > 2E13) {
$time = 0;
}
return ($time > 0) ? get_daysfromtime($time) : __('N/A');
}
function get_uptime($host) {
return ($host['snmp_sysUpTimeInstance'] > 0) ? get_daysfromtime(intval($host['snmp_sysUpTimeInstance']/100)) : __('N/A');
}
function get_daysfromtime($time, $secs = false, $pad = '', $format = DAYS_FORMAT_SHORT, $all = false) {
global $days_from_time_settings;
// Work around stricter typing in PHP 8.1.2+
if (is_float($time)) {
$time = intval(ceil($time));
}
// Ensure we use an existing format or we'll end up with no text at all
if (!isset($days_from_time_settings['text'][$format])) {
$format = DAYS_FORMAT_SHORT;
}
$mods = $days_from_time_settings['mods'];
$text = $days_from_time_settings['text'][$format];
$result = '';
foreach ($mods as $index => $mod) {
if ($mod > 0 || $secs) {
if ($time >= $mod) {
if ($mod < 1 || !is_numeric($mod)) {
$mod = 1;
}
$val = floor($time/$mod);
$time %= $mod;
} else {
$val = 0;
}
if ($all || $val > 0) {
$result .= padleft($pad, $val, 2) . $text['prefix'] . $text[$index] . $text['suffix'];
$all = true;
}
}
}
return trim($result,$text['suffix']);
}
function padleft($pad = '', $value = '', $min = 2) {
$result = "$value";
if (strlen($result) < $min && $pad != '') {
$padded = $pad . $result;
while ($padded != $result && strlen($result) < $min) {
$padded = $pad . $result;
}
$result = $padded;
}
return $result;
}
function get_classic_tabimage($text, $down = false) {
global $config, $dejavu_paths;
$images = array(
false => 'tab_template_blue.gif',
true => 'tab_template_red.gif'
);
if ($text == '') return false;
$text = strtolower($text);
$possibles = array(
array('DejaVuSans-Bold.ttf', 9, true),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 9, false),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 8, false),
array('DejaVuSansCondensed-Bold.ttf', 8, false),
array('DejaVuSans-Bold.ttf', 7, false),
array('DejaVuSansCondensed-Bold.ttf', 7, true),
);
$y = 30;
$x = 44;
$wlimit = 72;
$wrapsize = 12;
if (file_exists($config['base_path'] . '/images/' . $images[$down])) {
foreach ($dejavu_paths as $dejavupath) {
if (file_exists($dejavupath)) {
$font_path = $dejavupath;
}
}
$originalpath = getenv('GDFONTPATH');
putenv('GDFONTPATH=' . $font_path);
$template = imagecreatefromgif ($config['base_path'] . '/images/' . $images[$down]);
$w = imagesx($template);
$h = imagesy($template);
$tab = imagecreatetruecolor($w, $h);
imagecopy($tab, $template, 0, 0, 0, 0, $w, $h);
$txcol = imagecolorat($tab, 0, 0);
imagecolortransparent($tab,$txcol);
$white = imagecolorallocate($tab, 255, 255, 255);
$ttf_functions = function_exists('imagettftext') && function_exists('imagettfbbox');
if ($ttf_functions) {
foreach ($possibles as $variation) {
$font = $variation[0];
$fontsize = $variation[1];
$lines = array();
// if no wrapping is requested, or no wrapping is possible...
if ((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) {
$bounds = imagettfbbox($fontsize, 0, $font, $text);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$lines[] = array($text, $font, $fontsize, $realx, $y);
$maxw = $w;
} else {
$texts = explode("\n", wordwrap($text, $wrapsize), 2);
$line = 1;
$maxw = 0;
foreach ($texts as $txt) {
$bounds = imagettfbbox($fontsize, 0, $font, $txt);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$realy = $y - $h * $line + 3;
$lines[] = array($txt, $font, $fontsize, $realx, $realy);
if ($maxw < $w) {
$maxw = $w;
}
$line--;
}
}
if ($maxw<$wlimit) break;
}
} else {
while ($text > '') {
for ($fontid = 5; $fontid>0; $fontid--) {
$fontw = imagefontwidth($fontid);
$fonth = imagefontheight($fontid);
$realx = ($w - ($fontw * strlen($text)))/2;
$realy = ($h - $fonth - 5);
// Since we can't use FreeType, lets use a fixed location
$lines = array();
$lines[] = array($text, $fontid, 0, $realx, $realy);
if ($realx > 10 && $realy > 0) break;
}
if ($fontid == 0) {
$spacer = strrpos($text,' ');
if ($spacer === false) {
$spacer = strlen($text) - 1;
}
$text = substr($text,0,$spacer);
} else {
break;
}
}
}
foreach ($lines as $line) {
if ($ttf_functions) {
imagettftext($tab, $line[2], 0, intval($line[3]), intval($line[4]), $white, $line[1], $line[0]);
} else {
imagestring($tab, $line[1], intval($line[3]), intval($line[4]), $line[0], $white);
}
}
putenv('GDFONTPATH=' . $originalpath);
imagetruecolortopalette($tab, true, 256);
// generate the image an return the data directly
ob_start();
imagegif ($tab);
$image = ob_get_contents();
ob_end_clean();
return("data:image/gif;base64," . base64_encode($image));
} else {
return false;
}
}
function cacti_oid_numeric_format() {
if (function_exists('snmp_set_oid_output_format')) {
snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
} elseif (function_exists("snmp_set_oid_numeric_print")) {
snmp_set_oid_numeric_print(true);
}
}
function IgnoreErrorHandler($message) {
global $snmp_error;
$snmp_ignore = array(
'No response from',
'noSuchName',
'No Such Object',
'Error in packet',
'This name does not exist',
'End of MIB',
'Timeout',
'Unknown host',
'Connection timed out',
'Invalid object identifier',
'Name or service not known',
'USM generic error in file',
);
foreach ($snmp_ignore as $i) {
if (stripos($message, $i) !== false) {
$snmp_error = trim($message, "\\\n\t ");
return true;
}
}
$general_ignore = array(
'unable to read from socket', # ping.php line 387 socket refusal
'Maximum execution time of',
'transport read',
);
foreach ($general_ignore as $i) {
if (stripos($message, $i) !== false) {
return true;
}
}
return false;
}
function CactiErrorHandler($level, $message, $file, $line, $context = array()) {
global $phperrors;
if (defined('IN_CACTI_INSTALL')) {
return true;
}
if (IgnoreErrorHandler($message)) {
return true;
}
if (error_reporting() == 0) {
return true;
}
preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array);
$plugin = (is_array($output_array) && isset($output_array[1]) ? $output_array[1] : '');
if ($level !== null && isset($phperrors[$level])) {
$error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line";
} else {
$error = 'PHP Unknown Error' . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line";
}
switch ($level) {
case E_COMPILE_ERROR:
case E_CORE_ERROR:
case E_ERROR:
case E_PARSE:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR PARSE', false, true, 0, 1);
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $error));
}
break;
case E_RECOVERABLE_ERROR:
case E_USER_ERROR:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR', false, true, 0, 1);
break;
case E_COMPILE_WARNING:
case E_CORE_WARNING:
case E_USER_WARNING:
case E_WARNING:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR WARNING', false, true, 0, 1);
break;
case E_NOTICE:
case E_USER_NOTICE:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR NOTICE', false, true, 0, 1);
break;
case E_STRICT:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR STRICT', false, true, 0, 1);
break;
default:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR', false, true, 0, 1);
}
return false;
}
function CactiShutdownHandler() {
global $phperrors;
$error = error_get_last();
if (is_array($error)) {
if (isset($error['message']) && IgnoreErrorHandler($error['message'])) {
return true;
}
if (isset($error['type'])) {
switch ($error['type']) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_PARSE:
preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array);
$plugin = (isset($output_array[1]) ? $output_array[1] : '' );
if ($error['type'] !== null && isset($phperrors[$error['type']])) {
$message = 'PHP ' . $phperrors[$error['type']] .
($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] .
' in file: ' . $error['file'] . ' on line: ' . $error['line'];
} else {
$message = 'PHP Unknown Error' .
($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] .
' in file: ' . $error['file'] . ' on line: ' . $error['line'];
}
cacti_log($message, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR', false, true, 0, 1);
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $message));
}
}
}
}
}
/**
* enable_device_debug - Enables device debug for a device
* if it is disabled.
*
* @param $host_id - the device id to search for
*
* @return - void
*/
function enable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) === false) {
set_config_option('selective_device_debug', $device_debug . ',' . $host_id, true);
}
} else {
set_config_option('selective_device_debug', $host_id, true);
}
}
/**
* disable_device_debug - Disables device debug for a device
* if it is enabled.
*
* @param $host_id - the device id to search for
*
* @return - void
*/
function disable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
foreach($devices as $key => $device) {
if ($device == $host_id) {
unset($devices[$key]);
break;
}
}
set_config_option('selective_device_debug', implode(',', $devices), true);
}
}
/**
* is_device_debug_enabled - Determines if device debug is enabled
* for a device.
*
* @param $host_id - the device id to search for
*
* @return - boolean true or false
*/
function is_device_debug_enabled($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) !== false) {
return true;
}
}
return false;
}
/**
* call_remote_data_collector - Call the remote data collector with the correct URI
*
* @param - string - The hostname
* @param string - The URL to query
*
* @return - The results in raw form
*/
function call_remote_data_collector($poller_id, $url, $logtype = 'WEBUI') {
$hostname = db_fetch_cell_prepared('SELECT hostname
FROM poller
WHERE id = ?',
array($poller_id));
if (!is_ipaddress($hostname)) {
$ipaddress = gethostbyname($hostname);
if (!is_ipaddress($ipaddress)) {
if (debounce_run_notification('poller_down:' . $poller_id)) {
cacti_log(sprintf('WARNING: PollerID:%s has an invalid hostname:%s. It is not reachable via DNS!', $poller_id, $hostname), false, $logtype);
admin_email(__('Cacti System Warning'), __('WARNING: PollerID:%s has an invalid hostname:%s. Is it not reachable via DNS!', $poller_id, $hostname));
}
return '';
}
}
$fgc_contextoption = get_default_contextoption();
$fgc_context = stream_context_create($fgc_contextoption);
return file_get_contents(get_url_type() .'://' . $hostname . $url, false, $fgc_context);
}
/**
* get_url_type - Determines if remote communications are over
* http or https for remote services.
*
* @return - http or https
*/
function get_url_type() {
if (read_config_option('force_https') == 'on') {
return 'https';
} else {
return 'http';
}
}
/**
* get_default_contextoption - Sets default context options for self-signed SSL
* related protocols if necessary. Allows plugins to add additional header information
* to fulfill system setup related requirements like the usage of Web Single Login
* cookies for example.
*
* @param (int|bool) A numeric timeout value, or null if not set
*
* @return (array) An array to a context
*/
function get_default_contextoption($timeout = false) {
$fgc_contextoption = array();
if ($timeout === false) {
$timeout = read_config_option('remote_agent_timeout');
}
if (!is_numeric($timeout) || empty($timeout) || $timeout <= 0) {
$timeout = 5;
}
$protocol = get_url_type();
if (in_array($protocol, array('ssl', 'https', 'ftps'))) {
$fgc_contextoption = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
)
);
}
if ($protocol == 'https') {
$fgc_contextoption['https'] = array(
'timeout' => $timeout,
'ignore_errors' => true
);
} elseif ($protocol == 'http') {
$fgc_contextoption['http'] = array(
'timeout' => $timeout,
'ignore_errors' => true
);
}
$fgc_contextoption = api_plugin_hook_function('fgc_contextoption', $fgc_contextoption);
return $fgc_contextoption;
}
/**
* repair_system_data_input_methods - This utility will repair
* system data input methods when they are detected on the system
*
* @return - null
*/
function repair_system_data_input_methods($step = 'import') {
$system_hashes = array(
'3eb92bb845b9660a7445cf9740726522', // Get SNMP Data
'bf566c869ac6443b0c75d1c32b5a350e', // Get SNMP Data (Indexed)
'80e9e4c4191a5da189ae26d0e237f015', // Get Script Data (Indexed)
'332111d8b54ac8ce939af87a7eac0c06', // Get Script Server Data (Indexed)
);
$good_field_hashes = array(
'3eb92bb845b9660a7445cf9740726522' => array( // Get SNMP Data (1)
'92f5906c8dc0f964b41f4253df582c38', // IP Address
'012ccb1d3687d3edb29c002ea66e72da', // SNMP Version
'32285d5bf16e56c478f5e83f32cda9ef', // SNMP Community
'fc64b99742ec417cc424dbf8c7692d36', // SNMP Port
'ad14ac90641aed388139f6ba86a2e48b', // SNMP Username
'9c55a74bd571b4f00a96fd4b793278c6', // SNMP Password
'20832ce12f099c8e54140793a091af90', // SNMP Authentication Protocol
'c60c9aac1e1b3555ea0620b8bbfd82cb', // SNMP Privacy Passphrase
'feda162701240101bc74148415ef415a', // SNMP Privacy Protocol
'4276a5ec6e3fe33995129041b1909762' // SNMP OID
),
'bf566c869ac6443b0c75d1c32b5a350e' => array( // Get SNMP Data (Indexed) (2)
'617cdc8a230615e59f06f361ef6e7728', // IP Address
'b5c23f246559df38662c255f4aa21d6b', // SNMP Version
'acb449d1451e8a2a655c2c99d31142c7', // SNMP Community
'c1f36ee60c3dc98945556d57f26e475b', // SNMP Port
'f4facc5e2ca7ebee621f09bc6d9fc792', // SNMP Username
'1cc1493a6781af2c478fa4de971531cf', // SNMP Password
'2cf7129ad3ff819a7a7ac189bee48ce8', // SNMP Authentication Protocol
'6b13ac0a0194e171d241d4b06f913158', // SNMP Privacy Passphrase
'3a33d4fc65b8329ab2ac46a36da26b72', // SNMP Privacy Protocol
'6027a919c7c7731fbe095b6f53ab127b', // Index Type
'cbbe5c1ddfb264a6e5d509ce1c78c95f', // Index Value
'e6deda7be0f391399c5130e7c4a48b28' // Output Type ID
),
'80e9e4c4191a5da189ae26d0e237f015' => array( // Get Script Data (Indexed) 11
'd39556ecad6166701bfb0e28c5a11108', // Index Type
'3b7caa46eb809fc238de6ef18b6e10d5', // Index Value
'74af2e42dc12956c4817c2ef5d9983f9', // Output Type ID
'8ae57f09f787656bf4ac541e8bd12537' // Output Value
),
'332111d8b54ac8ce939af87a7eac0c06' => array( // Get Script Server Data (Indexed) 12
'172b4b0eacee4948c6479f587b62e512', // Index Type
'30fb5d5bcf3d66bb5abe88596f357c26', // Index Value
'31112c85ae4ff821d3b288336288818c', // Output Type ID
'5be8fa85472d89c621790b43510b5043' // Output Value
)
);
foreach($good_field_hashes as $hash => $field_hashes) {
$data_input_id = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array($hash));
if (!empty($data_input_id)) {
$bad_hashes = db_fetch_assoc_prepared('SELECT *
FROM data_input_fields
WHERE hash NOT IN ("' . implode('","', $field_hashes) . '")
AND hash != ""
AND data_input_id = ?',
array($data_input_id));
if (cacti_sizeof($bad_hashes)) {
cacti_log(strtoupper($step) . ' NOTE: Repairing ' . cacti_sizeof($bad_hashes) . ' Damaged data_input_fields', false);
foreach($bad_hashes as $bhash) {
$good_field_id = db_fetch_cell_prepared('SELECT id
FROM data_input_fields
WHERE hash != ?
AND data_input_id = ?
AND data_name = ?',
array($bhash['hash'], $data_input_id, $bhash['data_name']));
if (!empty($good_field_id)) {
cacti_log("Data Input ID $data_input_id Bad Field ID is " . $bhash['id'] . ", Good Field ID: " . $good_field_id, false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
cacti_log('Executing Data Input Data Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
// Data Input Data
$bad_mappings = db_fetch_assoc_prepared('SELECT *
FROM data_input_data
WHERE data_input_field_id = ?',
array($bhash['id']));
if (cacti_sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_input_fields', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_input_data
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($good_field_id, $mfid['data_template_data_id']));
if ($good_found > 0) {
cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('DELETE FROM data_input_data
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($mfid['data_input_field_id'], $mfid['data_template_data_id']));
} else {
cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('UPDATE data_input_data
SET data_input_field_id = ?
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($good_field_id, $mfid['data_input_field_id'], $mfid['data_template_data_id']));
}
}
} else {
cacti_log('No Bad Data Input Data Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
// Data Template RRD
cacti_log('Executing Data Template RRD Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);;
$bad_mappings = db_fetch_assoc_prepared('SELECT *
FROM data_template_rrd
WHERE data_input_field_id = ?',
array($bhash['id']));
if (cacti_sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_template_rrd', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_template_rrd
WHERE data_input_field_id = ?
AND id = ?',
array($good_field_id, $mfid['id']));
if ($good_found > 0) {
cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('DELETE FROM data_template_rrd
WHERE data_input_field_id = ?
AND id = ?',
array($mfid['data_input_field_id'], $mfid['id']));
} else {
cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('UPDATE data_template_rrd
SET data_input_field_id = ?
WHERE data_input_field_id = ?
AND id = ?',
array($good_field_id, $mfid['data_input_field_id'], $mfid['id']));
}
}
} else {
cacti_log('No Bad Data Template RRD Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
db_execute_prepared('DELETE FROM data_input_fields WHERE hash = ?', array($bhash['hash']));
} elseif ($bhash['hash'] == '35637c344d84d8aa3a4dc50e4a120b3f') {
$data_input_field_id = db_fetch_cell_prepared('SELECT *
FROM data_input_fields
WHERE hash = ?',
array('35637c344d84d8aa3a4dc50e4a120b3f'));
if ($data_input_field_id > 0) {
db_execute_prepared('DELETE FROM data_input_fields
WHERE id = ?',
array($data_input_field_id));
db_execute_prepared('DELETE FROM data_input_data
WHERE data_input_field_id = ?',
array($data_input_field_id));
}
} else {
cacti_log('WARNING: Could not find Cacti default matching hash for unknown system hash "' . $bhash['hash'] . '" for ' . $data_input_id . '. No repair performed.');
}
}
}
} else {
cacti_log("Could not find hash '" . $hash . "' for Data Input", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
}
}
if (isset($config['cacti_server_os']) && $config['cacti_server_os'] == 'win32' && !function_exists('posix_kill')) {
function posix_kill($pid, $signal = SIGTERM) {
if (!defined('SIGTERM')) {
define('SIGTERM', 15);
}
if (!defined('SIGKILL')) {
define('SIGKILL', 9);
}
if (!defined('SIGHUP')) {
define('SIGHUP', 1);
}
if (!defined('SIGINT')) {
define('SIGINT', 2);
}
$wmi = new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
$procs = $wmi->ExecQuery("SELECT ProcessId FROM Win32_Process WHERE ProcessId='" . $pid . "'");
if (cacti_sizeof($procs)) {
if ($signal == 0) {
return true; // The process is running
} elseif ($signal == SIGTERM || $signal == SIGINT || $signal == SIGKILL) {
foreach($procs as $proc) {
$proc->Terminate();
}
} elseif ($signal == SIGHUP) {
cacti_log("WARNING: SIGHUP Signal for pid: $pid is not supported on Windows", false, 'POLLER');
} else {
cacti_log("WARNING: Unknown Signal Number $signal in posix_kill", false, 'POLLER');
return false;
}
} elseif ($signal == 0) {
return false;
} else {
return true;
}
}
}
function is_ipaddress($ip_address = '') {
/* check for ipv4/v6 */
if (function_exists('filter_var')) {
if (filter_var($ip_address, FILTER_VALIDATE_IP) !== false) {
return true;
} else {
return false;
}
} elseif (inet_pton($ip_address) !== false) {
return true;
} else {
return false;
}
}
/**
* date_time_format create a format string for date/time
*
* @return string returns date time format
*/
function date_time_format() {
$datechar = array(
GDC_HYPHEN => '-',
GDC_SLASH => '/',
GDC_DOT => '.'
);
/* setup date format */
$date_fmt = read_config_option('default_date_format');
$dateCharSetting = read_config_option('default_datechar');
if (!isset($datechar[$dateCharSetting])) {
$dateCharSetting = GDC_SLASH;
}
$datecharacter = $datechar[$dateCharSetting];
switch ($date_fmt) {
case GD_MO_D_Y:
return 'm' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s';
case GD_MN_D_Y:
return 'M' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s';
case GD_D_MO_Y:
return 'd' . $datecharacter . 'm' . $datecharacter . 'Y H:i:s';
case GD_D_MN_Y:
return 'd' . $datecharacter . 'M' . $datecharacter . 'Y H:i:s';
case GD_Y_MO_D:
return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s';
case GD_Y_MN_D:
return 'Y' . $datecharacter . 'M' . $datecharacter . 'd H:i:s';
default:
return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s';
}
}
/**
* get_cacti_version Generic function to get the cacti version
*/
function get_cacti_version() {
static $version = '';
if ($version == '') {
$version = trim(db_fetch_cell('SELECT cacti FROM version LIMIT 1'));
}
return $version;
}
/**
* get_cacti_version_text Return the cacti version text including beta moniker
*/
function get_cacti_version_text($include_version = true) {
if ($include_version) {
return trim(__('Version %s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', constant('CACTI_VERSION_BETA')):'')));
} else {
return trim(__('%s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', constant('CACTI_VERSION_BETA')):'')));
}
}
/**
* get_cacti_cli_version() {
*/
function get_cacti_cli_version() {
$dbversion = get_cacti_version();
$version = get_cacti_version_text(false);
return $version . ' (DB: ' . $dbversion . ')';
}
/**
* cacti_version_compare - Compare Cacti version numbers
*/
function cacti_version_compare($version1, $version2, $operator = '>') {
if ($version1 == 'new_install') {
$version1 = CACTI_VERSION;
}
$length = max(cacti_sizeof(explode('.', $version1)), cacti_sizeof(explode('.', $version2)));
$version1 = version_to_decimal($version1, $length);
$version2 = version_to_decimal($version2, $length);
switch ($operator) {
case '<':
if ($version1 < $version2) {
return true;
}
break;
case '<=':
if ($version1 <= $version2) {
return true;
}
break;
case '>=':
if ($version1 >= $version2) {
return true;
}
break;
case '>':
if ($version1 > $version2) {
return true;
}
break;
case '==':
if ($version1 == $version2) {
return true;
}
break;
default:
return version_compare($version1, $version2, $operator);
}
return false;
}
/**
* version_to_decimal - convert version string to decimal
*/
function version_to_decimal($version, $length = 1) {
$newver = '';
$minor = '';
$parts = explode('.', $version);
foreach($parts as $part) {
if (is_numeric($part)) {
$part = substr('00' . $part, -2);
$newver .= $part;
} else {
$minor = substr($part, -1);
$major = substr($part, 0, strlen($part)-1);
$major = substr('00' . $major, -2);
$newver .= $major;
}
}
if (cacti_sizeof($parts) < $length) {
$i = cacti_sizeof($parts);
while($i < $length) {
$newver .= '00';
$i++;
}
}
if ($minor != '') {
$int = ord($minor);
} else {
$int = 0;
}
return @hexdec($newver) * 1000 + $int;
}
/**
* cacti_gethostinfo - obtains the dns information for a host
*/
function cacti_gethostinfo($hostname, $type = DNS_ALL) {
return dns_get_record($hostname, $type);
}
/**
* cacti_gethostbyname - a ip/ipv6 replacement for php's gethostbyname function
*/
function cacti_gethostbyname($hostname, $type = '') {
if ($type == '') {
$type = DNS_A + DNS_AAAA;
}
if ($type != DNS_AAAA) {
$host = gethostbyname($hostname);
if ($host !== $hostname) {
return $host;
}
}
$return = cacti_gethostinfo($hostname, $type);
if (cacti_sizeof($return)) {
foreach($return as $record) {
switch($record['type']) {
case 'A':
return $record['ip'];
break;
case 'AAAA':
return $record['ipv6'];
break;
}
}
}
return $hostname;
}
function get_nonsystem_data_input($data_input_id) {
global $hash_system_data_inputs;
$diid = db_fetch_cell_prepared('SELECT id FROM data_input
WHERE hash NOT IN ("' . implode('","', $hash_system_data_inputs) . '")
AND id = ?',
array($data_input_id));
return $diid;
}
function get_rrdtool_version($force = false) {
static $version = '';
if ($version == '') {
$version = str_replace('rrd-', '', str_replace('.x', '.0', read_config_option('rrdtool_version', $force) ?: read_default_config_option('rrdtool_version') ?: '1.4.0' ));
}
return $version;
}
function get_installed_rrdtool_version() {
global $config, $rrdtool_versions;
static $version = '';
if ($version == '') {
if ($config['cacti_server_os'] == 'win32') {
$shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v');
} else {
$shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v 2>&1');
}
$version = false;
if ($shell && preg_match('/^RRDtool ([0-9.]+) /', $shell, $matches)) {
foreach ($rrdtool_versions as $rrdtool_version => $rrdtool_version_text) {
if (cacti_version_compare($rrdtool_version, $matches[1], '<=')) {
$version = $rrdtool_version;
}
}
}
}
return $version;
}
function get_md5_hash($path) {
$md5 = 0;
if (db_table_exists('poller_resource_cache')) {
$md5 = db_fetch_cell_prepared('SELECT md5sum
FROM poller_resource_cache
WHERE `path` = ?',
array($path));
}
if (empty($md5)) {
if (file_exists($path)) {
$md5 = md5_file($path);
} elseif (file_exists(dirname(__FILE__) . '/../' . $path)) {
$md5 = md5_file(dirname(__FILE__) . '/../' . $path);
}
}
return $md5;
}
function get_include_relpath($path) {
global $config;
$basePath = rtrim($config['base_path'],'/') . '/';
$npath = '';
if (file_exists($path)) {
$npath = str_replace($basePath, '', $path);
} elseif (file_exists($basePath . $path)) {
$npath = $path;
} elseif (debounce_run_notification('missing:' . $path)) {
$npath = str_replace($basePath, '', $path);
cacti_log(sprintf('WARNING: Key Cacti Include File %s missing. Please locate and replace this file', $config['base_path'] . '/' . $npath), false, 'WEBUI');
admin_email(__('Cacti System Warning'), __('WARNING: Key Cacti Include File %s missing. Please locate and replace this file', $config['base_path'] . '/' . $npath));
}
return $npath;
}
function get_md5_include_js($path, $async = false) {
global $config;
$relpath = get_include_relpath($path);
if (empty($relpath)) {
return '';
}
if ($async) {
return '<script type=\'text/javascript\' src=\'' . $config['url_path'] . $relpath . '?' . get_md5_hash($path) . '\' async></script>' . PHP_EOL;
} else {
return '<script type=\'text/javascript\' src=\'' . $config['url_path'] . $relpath . '?' . get_md5_hash($path) . '\'></script>' . PHP_EOL;
}
}
function get_md5_include_css($path) {
global $config;
$relpath = get_include_relpath($path);
if (empty($relpath)) {
return '';
}
return '<link href=\''. $config['url_path'] . $relpath . '?' . get_md5_hash($relpath) . '\' type=\'text/css\' rel=\'stylesheet\'>' . PHP_EOL;
}
function is_resource_writable($path) {
if (empty($path)) {
return false;
}
if ($path[strlen($path)-1] == '/') {
return is_resource_writable($path . uniqid(mt_rand()) . '.tmp');
}
if (file_exists($path)) {
if (($f = @fopen($path, 'a'))) {
fclose($f);
return true;
}
return false;
}
if (($f = @fopen($path, 'w'))) {
fclose($f);
unlink($path);
return true;
}
return false;
}
function recursive_chown($path, $uid, $gid) {
$d = opendir($path);
while(($file = readdir($d)) !== false) {
if ($file != '.' && $file != '..') {
$fullpath = $path . '/' . $file ;
if (filetype($fullpath) == 'dir') {
return recursive_chown($fullpath, $uid, $gid);
}
$success = chown($fullpath, $uid);
if ($success) {
$success = chgrp($fullpath, $gid);
}
}
if (!$success) {
return false;
}
}
return true;
}
function get_validated_theme($theme, $defaultTheme) {
global $config;
if (isset($theme) && strlen($theme)) {
$themePath = $config['base_path'] . '/include/themes/' . $theme . '/main.css';
if (file_exists($themePath)) {
return $theme;
}
}
return $defaultTheme;
}
function get_validated_language($language, $defaultLanguage) {
if (isset($language) && strlen($language)) {
return $language;
}
return $defaultLanguage;
}
function get_running_user() {
global $config;
static $tmp_user = '';
if (empty($tmp_user)) {
if (function_exists('posix_geteuid')) {
$tmp_user = posix_getpwuid(posix_geteuid())['name'];
}
}
if (empty($tmp_user)) {
$tmp_file = tempnam(sys_get_temp_dir(), 'uid'); $f_owner = '';
if (is_resource_writable($tmp_file)) {
if (file_exists($tmp_file)) {
unlink($tmp_file);
}
file_put_contents($tmp_file, 'cacti');
$f_owner = fileowner($tmp_file);
$f_source = 'file';
if (file_exists($tmp_file)) {
unlink($tmp_file);
}
}
if (empty($f_owner) && function_exists('posix_getuid')) {
$f_owner = posix_getuid();
$f_source = 'posix';
}
if (!empty($f_owner) && function_exists('posix_getpwuid1')) {
$f_array = posix_getpwuid($f_owner);
if (isset($f_array['name'])) {
$tmp_user = $f_array['name'];
}
}
if (empty($tmp_user)) {
exec('id -nu', $o, $r);
if ($r == 0) {
$tmp_user = trim($o['0']);
}
}
/*** Code left here for future development, don't think it is right ***
*
if (empty($tmp_user) && !empty($f_owner) && is_readable('/etc/passwd'))
{
exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r);
if ($r == 0) {
$tmp_user = 'passwd-' . trim($o['0']);
}
}
*/
// Easy way first
if (empty($tmp_user)) {
$user = get_current_user();
if ($user != '') {
$tmp_user = $user;
}
}
// Fallback method
if (empty($tmp_user)) {
$user = getenv('USERNAME');
if ($user != '') {
$tmp_user = $user;
}
if (empty($tmp_user)) {
$user = getenv('USER');
if ($user != '') {
$tmp_user = $user;
}
}
}
}
return (empty($tmp_user) ? 'apache' : $tmp_user);
}
function get_debug_prefix() {
$dateTime = new DateTime('NOW');
$dateTime = $dateTime->format('Y-m-d H:i:s.u');
return sprintf('<[ %s | %7d ]> -- ', $dateTime, getmypid());
}
function get_client_addr() {
global $config, $allowed_proxy_headers;
$proxy_headers = (isset($config['proxy_headers']) ? $config['proxy_headers'] : []);
if ($proxy_headers === true) {
$proxy_headers = $allowed_proxy_headers;
} elseif (is_array($proxy_headers) && is_array($allowed_proxy_headers)) {
$proxy_headers = array_intersect($proxy_headers, $allowed_proxy_headers);
}
if (!is_array($proxy_headers)) {
$proxy_headers = [];
}
if (!in_array('REMOTE_ADDR', $proxy_headers)) {
$proxy_headers[] = 'REMOTE_ADDR';
}
$client_addr = false;
foreach ($proxy_headers as $header) {
if (!empty($_SERVER[$header])) {
$header_ips = explode(',', $_SERVER[$header]);
foreach ($header_ips as $header_ip) {
if (!empty($header_ip)) {
if (!filter_var($header_ip, FILTER_VALIDATE_IP)) {
cacti_log('ERROR: Invalid remote client IP Address found in header (' . $header . ').', false, 'AUTH', POLLER_VERBOSITY_DEBUG);
} else {
$client_addr = $header_ip;
cacti_log('DEBUG: Using remote client IP Address found in header (' . $header . '): ' . $client_addr . ' (' . $_SERVER[$header] . ')', false, 'AUTH', POLLER_VERBOSITY_DEBUG);
break 2;
}
}
}
}
}
return $client_addr;
}
/**
* get_cacti_base_tables - Extracts all the base Cacti tables from the
* cacti.sql file in the base Cacti directory.
*/
function get_cacti_base_tables() {
global $config;
$base_tables = array();
if (file_exists($config['base_path'] . '/cacti.sql')) {
$schema = file($config['base_path'] . '/cacti.sql');
} else {
return $base_tables;
}
if (cacti_sizeof($schema)) {
foreach($schema as $line) {
if (strpos($line, 'CREATE TABLE') !== false) {
$table = str_replace(array('CREATE TABLE', '`', '(', ' '), '', $line);
$base_tables[] = trim($table);
}
}
}
return $base_tables;
}
function cacti_pton($ipaddr) {
// Strip out the netmask, if there is one.
$subnet_pos = strpos($ipaddr, '/');
if ($subnet_pos) {
$subnet = substr($ipaddr, $subnet_pos+1);
$ipaddr = substr($ipaddr, 0, $subnet_pos);
} else {
$subnet = null; // No netmask present
}
// Convert address to packed format
$addr = @inet_pton($ipaddr);
if ($addr === false) {
return false;
}
// Maximum netmask length = same as packed address
$len = 8*strlen($addr);
if (!empty($subnet)) {
if (!is_numeric($subnet)) {
return false;
} elseif ($subnet > $len) {
return false;
}
}
if (!is_numeric($subnet)) {
$subnet=$len;
} else {
$subnet=(int)$subnet;
}
// Create a hex expression of the subnet mask
$mask=str_repeat('f',$subnet>>2);
switch($subnet&3) {
case 3:
$mask.='e';
break;
case 2:
$mask.='c'; break;
case 1:
$mask.='8'; break;
}
$mask=str_pad($mask,$len>>2,'0');
// Packed representation of netmask
$mask=pack('H*',$mask);
$result = array('ip' => $addr, 'subnet' => $mask);
return $result;
}
function cacti_ntop($addr) {
if (empty($addr)) {
return false;
}
if (is_array($addr)) {
foreach ($addr as $ip) {
$addr = $ip;
break;
}
}
return @inet_ntop($addr);
}
function cacti_ntoc($subnet, $ipv6 = false) {
$result = false;
$count = 0;
foreach(str_split($subnet) as $char) {
$i = ord($char);
while (($i & 128) == 128) {
$count++;
$i = ($i << 1) % 256;
}
}
return $count;
}
function cacti_ptoa($title, $addr) {
// Let's display it as hexadecimal format
foreach(str_split($addr) as $char) {
print str_pad(dechex(ord($char)),2,'0',STR_PAD_LEFT);
}
}
function cacti_sizeof($array) {
return ($array === false || !is_array($array)) ? 0 : sizeof($array);
}
function cacti_count($array) {
return ($array === false || !is_array($array)) ? 0 : count($array);
}
function is_function_enabled($name) {
return function_exists($name) &&
!in_array($name, array_map('trim', explode(', ', ini_get('disable_functions')))) &&
strtolower(ini_get('safe_mode')) != 1;
}
function is_page_ajax() {
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
return true;
}
return false;
}
function raise_ajax_permission_denied() {
if (is_page_ajax()) {
header('HTTP/1.1 401 ' . __('Permission Denied'));
print __('You are not permitted to access this section of Cacti.') . ' ' . __('If you feel that this is an error. Please contact your Cacti Administrator.');
exit;
}
}
/**
* cacti_session_start - Create a Cacti session from the settings set by the administrator
*
* @return - null
*/
function cacti_session_start() {
/** @var array */
global $config;
/* initialize php session */
if (!function_exists('session_name')) {
die('PHP Session Management is missing, please install PHP Session module');
}
session_name($config['cacti_session_name']);
if (session_status() === PHP_SESSION_NONE) {
$session_restart = '';
} else {
$session_restart = 're';
}
$session_result = session_start($config['cookie_options']);
if (!$session_result) {
cacti_log('Session "' . session_id() . '" ' . $session_restart . 'start failed! ' . cacti_debug_backtrace('', false, false, 0, 1), false, 'WARNING:');
}
}
/**
* cacti_session_close - Closes the open Cacti session if it is open
* it can be re-opened afterwards in the case after a long running query
*
* @return - null
*/
function cacti_session_close() {
session_write_close();
}
/**
* cacti_session_destroy - Destroys the login current session
*
* @return - null
*/
function cacti_session_destroy() {
session_unset();
session_destroy();
}
/**
* cacti_cookie_set - Allows for settings an arbitry cookie name and value
* used for CSRF protection.
*
* @return - null
*/
function cacti_cookie_set($session, $val) {
global $config;
if (isset($config['cookie_options']['cookie_domain'])) {
$domain = $config['cookie_options']['cookie_domain'];
} else {
$domain = '';
}
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$secure = true;
} else {
$secure = false;
}
if (version_compare(PHP_VERSION, '7.3', '>=')) {
$options = array(
'path' => $config['url_path'],
'expires' => time() + 3600,
'domain' => $domain,
'secure' => $secure,
'httponly' => true,
'samesite' => 'Strict'
);
setcookie($session, $val, $options);
} else {
setcookie($session, $val, time() + 3600, $config['url_path'], $domain, $secure, true);
}
}
/**
* cacti_cookie_logout - Clears the Cacti and the 'keep me logged in' cookies
*
* @return - null
*/
function cacti_cookie_logout() {
global $config;
if (isset($config['cookie_options']['cookie_domain'])) {
$domain = $config['cookie_options']['cookie_domain'];
} else {
$domain = '';
}
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$secure = true;
} else {
$secure = false;
}
if (version_compare(PHP_VERSION, '7.3', '>=')) {
$options = array(
'path' => $config['url_path'],
'expires' => time() - 3600,
'domain' => $domain,
'secure' => $secure,
'httponly' => true,
'samesite' => 'Strict'
);
setcookie(session_name(), '', $options);
setcookie('cacti_remembers', '', $options);
} else {
setcookie(session_name(), '', time() - 3600, $config['url_path'], $domain, $secure, true);
setcookie('cacti_remembers', '', time() - 3600, $config['url_path'], $domain, $secure, true);
}
unset($_COOKIE[$config['cacti_session_name']]);
}
/**
* cacti_cookie_session_set - Sets the cacti 'keep me logged in' cookie
*
* @return - null
*/
function cacti_cookie_session_set($user, $realm, $nssecret) {
global $config;
if (isset($config['cookie_options']['cookie_domain'])) {
$domain = $config['cookie_options']['cookie_domain'];
} else {
$domain = '';
}
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$secure = true;
} else {
$secure = false;
}
$_SESSION['cacti_remembers'] = true;
if (version_compare(PHP_VERSION, '7.3', '>=')) {
$options = array(
'path' => $config['url_path'],
'expires' => time() + (86400*30),
'domain' => $domain,
'secure' => $secure,
'httponly' => true,
'samesite' => 'Strict'
);
setcookie('cacti_remembers', $user . ',' . $realm . ',' . $nssecret, $options);
} else {
setcookie('cacti_remembers', $user . ',' . $realm . ',' . $nssecret, time() + (86400*30), $config['url_path'], $domain, $secure, true);
}
}
/**
* cacti_cookie_session_logout - Logs out of Cacti and the remember me session
*
* @return - null
*/
function cacti_cookie_session_logout() {
global $config;
if (isset($config['cookie_options']['cookie_domain'])) {
$domain = $config['cookie_options']['cookie_domain'];
} else {
$domain = '';
}
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$secure = true;
} else {
$secure = false;
}
if (version_compare(PHP_VERSION, '7.3', '>=')) {
$options = array(
'path' => $config['url_path'],
'expires' => time() - 3600,
'domain' => $domain,
'secure' => $secure,
'httponly' => true,
'samesite' => 'Strict'
);
setcookie('cacti_remembers', '', $options);
} else {
setcookie('cacti_remembers', '', time() - 3600, $config['url_path'], $domain, $secure, true);
}
}
/**
* cacti_browser_zone_set - Set the PHP timezone to the
* browsers timezone if enabled.
*
* @return - null
*/
function cacti_browser_zone_set() {
if (cacti_browser_zone_enabled()) {
if (isset($_SESSION['sess_browser_php_tz'])) {
ini_set('date.timezone', $_SESSION['sess_browser_php_tz']);
putenv('TZ=' . $_SESSION['sess_browser_system_tz']);
}
}
}
/**
* cacti_system_zone_set - Set the PHP timezone to the
* systems timezone.
*
* @return - null
*/
function cacti_system_zone_set() {
if (cacti_browser_zone_enabled()) {
if (isset($_SESSION['sess_php_tz'])) {
ini_set('date.timezone', $_SESSION['sess_php_tz']);
putenv('TZ=' . $_SESSION['sess_system_tz']);
}
}
}
function cacti_browser_zone_enabled() {
$system_setting = read_config_option('client_timezone_support');
if (empty($system_setting)) {
return false;
} else {
$user_setting = read_user_setting('client_timezone_support', '0');
if (empty($user_setting)) {
return false;
}
return true;
}
}
/**
* cacti_time_zone_set - Givin an offset in minutes, attempt
* to set a PHP date.timezone. There are some oddballs that
* we have to accomodate.
*
* @return - null
*/
function cacti_time_zone_set($gmt_offset) {
if (!cacti_browser_zone_enabled()) {
return;
}
$hours = floor($gmt_offset / 60);
$remaining = $gmt_offset % 60;
if (!isset($_SESSION['sess_php_tz'])) {
$_SESSION['sess_php_tz'] = ini_get('date.timezone');
$_SESSION['sess_system_tz'] = getenv('TZ');
}
$zone = timezone_name_from_abbr('', $gmt_offset);
if ($remaining == 0) {
putenv('TZ=GMT' . ($hours > 0 ? '-':'+') . abs($hours));
$sys_offset = 'GMT' . ($hours > 0 ? '-':'+') . abs($hours);
if ($zone !== false) {
$php_offset = $zone;
ini_set('date.timezone', $zone);
} else {
// Adding the rounding function as some timezones are Etc/GMT+5.5 which is
// not supported in PHP yet.
$php_offset = 'Etc/GMT' . ($hours > 0 ? '-':'+') . abs(round($hours));
ini_set('date.timezone', 'Etc/GMT' . ($hours > 0 ? '-':'+') . abs(round($hours)));
}
$_SESSION['sess_browser_system_tz'] = $sys_offset;
$_SESSION['sess_browser_php_tz'] = $php_offset;
} else {
$time = ($hours > 0 ? '-':'+') . abs($hours) . ':' . substr('00' . $remaining, -2);
if ($zone === false) {
switch($time) {
case '+3:30':
$zone = 'IRST';
break;
case '+4:30':
$zone = 'IRDT';
break;
case '+5:30':
$zone = 'IST';
break;
case '+5:45':
$zone = 'NPT';
break;
case '+6:30':
$zone = 'CCT';
break;
case '+9:30':
$zone = 'ACST';
break;
case '+10:30':
$zone = 'ACDT';
break;
case '+8:45':
$zone = 'ACWST';
break;
case '+12:45':
$zone = 'CHAST';
break;
case '+13:45':
$zone = 'CHADT';
break;
case '-3:30':
$zone = 'NST';
break;
case '-2:30':
$zone = 'NDT';
break;
case '-9:30':
$zone = 'MART';
break;
}
if ($zone !== false) {
$zone = timezone_name_from_abbr($zone);
}
}
$php_offset = $zone;
$sys_offset = 'GMT' . $time;
putenv('TZ=GMT' . $time);
if ($zone != '') {
ini_set('date.timezone', $zone);
}
$_SESSION['sess_browser_system_tz'] = $sys_offset;
$_SESSION['sess_browser_php_tz'] = $php_offset;
}
}
function debounce_run_notification($id, $frequency = 7200) {
$full = 'debounce_' . $id;
$key = substr($full, 0, 50);
if ($full !== $key) {
cacti_debug_backtrace("ERROR: debounce key was truncated from $full to $key");
}
/* debounce admin emails */
$last = read_config_option($key);
$now = time();
if (empty($last) || $now - $last > $frequency) {
set_config_option($key, $now);
return true;
}
return false;
}
function cacti_unserialize($strobj) {
if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
return unserialize($strobj, array('allowed_classes' => false));
} else {
return unserialize($strobj);
}
}
function cacti_format_ipv6_colon($address) {
if (!filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return $address;
}
if (strpos($address, '[') !== false) {
return $address;
}
if (strpos($address, ':') !== false) {
return '[' . $address . ']';
}
return($address);
}
|