// Debug header
header('X-Debug: Active-'.time());
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
header('Content-Type: text/html; charset=utf-8');
// Hata ayıklama için
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('DEBUG_MODE', true);
// Debug başlangıç mesajı ve bilgisi
echo "
DEBUG MODE ACTIVE - ".date('Y-m-d H:i:s')."
";
echo "IP: " . $_SERVER['REMOTE_ADDR'] . "
";
echo "USER AGENT: " . $_SERVER['HTTP_USER_AGENT'] . "
";
echo "REQUEST METHOD: " . $_SERVER['REQUEST_METHOD'] . "
";
echo "POST Data:
" . print_r($_POST, true) . "
";
echo "
";
// Çıktı tamponlamasını başlat
ob_start();
// Debug fonksiyonu - direkt HTML yorum olarak göster
function debug_log($message) {
echo "\n";
}
// Domain normalizasyon fonksiyonu
function normalize_domain($domain) {
// Protokolü kaldır (http://, https://)
$domain = preg_replace('#^https?://#', '', $domain);
// Alt alan adlarını kontrol et ve ana domain'i al
$parts = explode('.', $domain);
// IP adresi kontrolü
if (count($parts) == 4 && is_numeric($parts[0]) && is_numeric($parts[1]) &&
is_numeric($parts[2]) && is_numeric($parts[3])) {
return $domain; // IP adresi ise değiştirme
}
// Domain uzunluğu kontrolü
if (count($parts) <= 2) {
return $domain; // Zaten ana domain
}
// www. ile başlıyorsa kaldır
if ($parts[0] === 'www') {
array_shift($parts);
return implode('.', $parts);
}
// Son iki parçayı al (ana domain + TLD)
// Örneğin mail.durantoprokash.com -> durantoprokash.com
return $parts[count($parts) - 2] . '.' . $parts[count($parts) - 1];
}
// Log fonksiyonu - debug modunda tüm logları kaydet ve HTML yorum olarak göster
function api_log($message, $is_error = false) {
$log_file = dirname(__FILE__) . '/api_log.txt';
$date = date('Y-m-d H:i:s');
$log_message = "[$date] " . ($is_error ? "[ERROR] " : "[INFO] ") . $message . "\n";
file_put_contents($log_file, $log_message, FILE_APPEND);
if (defined('DEBUG_MODE') && DEBUG_MODE) {
if ($is_error) {
error_log($message);
}
// Debug bilgisini ekranda göster
echo "
";
echo ($is_error ? "ERROR: " : "INFO: ") . htmlspecialchars($message);
echo "
";
}
}
// Use a different name to avoid redeclaring built-in error_log
function custom_error_log($message, $type = 0, $destination = '', $headers = '') {
if ($type === 0) {
debug_log($message);
return true;
}
return error_log($message, $type, $destination, $headers);
}
// Detaylı hata yakalama
set_error_handler(function($errno, $errstr, $errfile, $errline) {
$error_message = "PHP Error [$errno]: $errstr in $errfile on line $errline";
api_log($error_message, true);
return false;
});
set_exception_handler(function($e) {
$error_message = "Uncaught Exception: " . $e->getMessage() . "\nStack trace: " . $e->getTraceAsString();
api_log($error_message, true);
// Çıktı tamponlamasını temizle ve JSON header'ı ayarla
ob_clean();
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'message' => 'Internal server error',
'debug' => [
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
]
]);
exit;
});
// Rate limiting kontrolü
function checkRateLimit($ip, $limit = 300) {
$cache_file = sys_get_temp_dir() . '/rate_' . md5($ip);
if (file_exists($cache_file)) {
$data = json_decode(file_get_contents($cache_file), true);
if ($data['count'] > $limit && (time() - $data['time']) < 3600) {
return false;
}
if ((time() - $data['time']) > 3600) {
$data = ['count' => 1, 'time' => time()];
} else {
$data['count']++;
}
} else {
$data = ['count' => 1, 'time' => time()];
}
file_put_contents($cache_file, json_encode($data));
return true;
}
// IP ve rate limit kontrolü
if (!checkRateLimit($_SERVER['REMOTE_ADDR'])) {
http_response_code(429);
ob_end_clean();
echo '
Too Many Requests
';
exit;
}
// Domain kontrolü
if (!isset($_POST['domain'])) {
api_log("Error: Domain missing", true);
ob_end_clean();
echo '
Error: Domain parameter is required
';
exit;
}
// Kullanılan değişkenleri tanımla
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$client_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
// Eski curl kodunu tespit et
$is_old_client = 0;
if (isset($_POST['backlink_token'])) {
$is_old_client = 1;
} else if (!empty($user_agent) && (strpos($user_agent, 'WordPress') !== false ||
strpos($user_agent, 'WP') !== false) ||
(!empty($referrer) && (strpos($referrer, '/wp-content/') !== false ||
strpos($referrer, '/wp-includes/') !== false))) {
// WordPress sitelerinden gelen istekler muhtemelen eski curl kodunu kullanıyor
$is_old_client = 1;
}
// Domain'i normalize et
$original_domain = base64_decode($_POST['domain']);
$normalized_domain = normalize_domain($original_domain);
// Domain normalize sonuçlarını ekranda göster
echo "
";
echo "Original Domain: " . htmlspecialchars($original_domain) . "
";
echo "Normalized Domain: " . htmlspecialchars($normalized_domain) . "
";
echo "
";
// Veritabanı bağlantısı
try {
// Veritabanı bağlantısı
$db = new PDO(
"mysql:host=localhost;dbname=sche_v2;charset=utf8mb4",
"sche_bombom",
"bombom",
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_FOUND_ROWS => true
]
);
// Veritabanına debug bilgilerini kaydet
try {
$stmt = $db->prepare("
INSERT INTO backlink_requests (
domain,
ip_address,
user_agent,
referrer,
is_old_client,
request_data,
created_at
) VALUES (?, ?, ?, ?, ?, ?, NOW())
");
$request_data = json_encode($_POST);
$stmt->execute([
$normalized_domain,
$client_ip,
$user_agent,
$referrer,
$is_old_client,
$request_data
]);
api_log("API request logged to database for domain: " . $original_domain . " (normalized: " . $normalized_domain . "), is_old_client: " . $is_old_client);
} catch (Exception $e) {
api_log("Error logging API request: " . $e->getMessage(), true);
}
$domain = filter_var(base64_decode($_POST['domain']), FILTER_SANITIZE_URL);
if (!$domain) {
api_log("Error: Invalid domain format: " . $_POST['domain'], true);
ob_end_clean();
echo '
Error: Invalid domain format
';
exit;
}
// Domain'i normalize et
$domain = normalize_domain($domain);
// Domain formatını kontrol et (daha esnek regex)
if (!preg_match('/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i', $domain)) {
api_log("Error: Invalid domain structure: " . $domain, true);
ob_end_clean();
echo '
Error: Invalid domain structure
';
exit;
}
// Eski token sistemi için kontrol
if (isset($_POST['backlink_token'])) {
// Eski token ile gelen istekleri normal işle
api_log("Request with old token system from domain: " . $domain);
}
// Cache temizleme isteği kontrolü
if (isset($_POST['clear_cache']) && $_POST['clear_cache'] === '1') {
// Çıktı tamponlamasını temizle ve JSON header'ı ayarla
ob_clean();
header('Content-Type: application/json; charset=utf-8');
// Admin token kontrolü - eski sistem için uyumluluk
$raw_domain = base64_decode($_POST['domain']);
$received_token = $_POST['admin_token'] ?? '';
$received_date = $_POST['date'] ?? date('Ymd');
$backlink_token = $_POST['backlink_token'] ?? '';
// Debug bilgileri
error_log("Raw Domain: " . $raw_domain);
error_log("Received Token: " . $received_token);
error_log("Received Date: " . $received_date);
error_log("Backlink Token: " . $backlink_token);
// Beklenen token'ı oluştur
$expected_token = hash('sha256', $raw_domain . $received_date . 'schemapi_' . $received_date);
error_log("Expected Token: " . $expected_token);
// Token kontrolü - eski sistem için esneklik
if (!hash_equals($expected_token, $received_token) && !$backlink_token) {
error_log("Token mismatch for domain: " . $raw_domain);
error_log("Expected: " . $expected_token);
error_log("Received: " . $received_token);
ob_end_clean();
echo '
Unauthorized request - Token mismatch
';
exit;
}
$result = [
'success' => true,
'cleared_plugins' => [],
'message' => '',
'debug' => [
'domain' => $domain,
'wp_url' => $wp_url,
'api_status' => $api_http_code,
'site_status' => $wp_http_code,
'detected_plugins' => [],
'errors' => []
]
];
try {
// WordPress sitesine istek gönder
$wp_url = "https://" . $domain;
// Debug bilgilerini logla
error_log("Starting cache clear operation for domain: " . $domain);
error_log("WordPress URL: " . $wp_url);
// WordPress site kontrolü için CURL ayarları
$curl_options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SchemapiBot/1.0; +https://schemapi.com/bot)',
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Connection: keep-alive',
'Cache-Control: no-cache',
'Pragma: no-cache'
]
];
// İlk olarak WordPress API'sini kontrol et
$ch = curl_init();
$api_url = rtrim($wp_url, '/') . "/wp-json/";
curl_setopt_array($ch, $curl_options + [CURLOPT_URL => $api_url]);
$api_response = curl_exec($ch);
$curl_error = curl_error($ch);
$api_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($api_response === false) {
error_log("WordPress API connection error: " . $curl_error);
// API hatası durumunda ana siteye devam et
}
$api_header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$api_headers = substr($api_response, 0, $api_header_size);
$api_body = substr($api_response, $api_header_size);
curl_close($ch);
// Ana sayfayı kontrol et
$ch = curl_init();
curl_setopt_array($ch, $curl_options + [CURLOPT_URL => $wp_url]);
$wp_response = curl_exec($ch);
$curl_error = curl_error($ch);
$wp_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($wp_response === false) {
throw new Exception("WordPress site connection failed: " . $curl_error);
}
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($wp_response, 0, $header_size);
$body = substr($wp_response, $header_size);
curl_close($ch);
// Debug için header ve body bilgilerini logla
error_log("Main site response - HTTP Code: " . $wp_http_code);
error_log("Main site headers: " . $headers);
error_log("Main site body (first 1000 chars): " . substr($body, 0, 1000));
$cleared_count = 0;
// Cache sistemleri tanımlaması
$cache_systems = [
'WP Super Cache' => [
'detect' => function($headers, $body) {
return (
stripos($body, 'wp-super-cache') !== false ||
stripos($body, '/wp-content/plugins/wp-super-cache/') !== false ||
stripos($body, '/wp-content/cache/supercache/') !== false ||
stripos($body, 'WP_CACHE') !== false ||
stripos($body, 'wp-cache-config.php') !== false ||
stripos($body, 'wpsupercache') !== false ||
stripos($body, 'wp_cache') !== false ||
stripos($headers, 'x-super-cache') !== false
);
},
'clear' => function($url) {
return [
['method' => 'GET', 'url' => $url . '/wp-admin/admin-ajax.php?action=wp_cache_clear'],
['method' => 'GET', 'url' => $url . '/?wp_cache_clear=1'],
['method' => 'GET', 'url' => $url . '/wp-admin/options-general.php?page=wpsupercache&wp_delete_cache=1'],
['method' => 'GET', 'url' => $url . '/wp-content/cache/supercache/'],
['method' => 'GET', 'url' => $url . '/wp-content/cache/page_enhanced/'],
['method' => 'GET', 'url' => $url . '/wp-content/cache/wp-cache-config.php']
];
}
],
// ... existing code for other cache systems ...
];
// Cache temizleme fonksiyonunu güncelle
function clearCache($url, $clear_info) {
$success = false;
$error_messages = [];
$curl_options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SchemapiBot/1.0; +https://schemapi.com/bot)',
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Connection: keep-alive',
'Cache-Control: no-cache',
'Pragma: no-cache'
]
];
error_log("Attempting to clear cache for URL: " . $url);
if (is_array($clear_info) && isset($clear_info[0])) {
foreach ($clear_info as $info) {
error_log("Processing cache clear request: " . print_r($info, true));
$ch = curl_init();
$opts = $curl_options;
$opts[CURLOPT_URL] = $info['url'];
$opts[CURLOPT_CUSTOMREQUEST] = $info['method'];
if (isset($info['headers'])) {
$headers = [];
foreach ($info['headers'] as $key => $value) {
$headers[] = "$key: $value";
}
$opts[CURLOPT_HTTPHEADER] = array_merge($opts[CURLOPT_HTTPHEADER], $headers);
}
curl_setopt_array($ch, $opts);
$start_time = microtime(true);
$response = curl_exec($ch);
$exec_time = microtime(true) - $start_time;
$curl_error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
error_log(sprintf(
"Cache clear request completed - URL: %s, HTTP Code: %d, Time: %.2fs, Error: %s",
$info['url'],
$http_code,
$exec_time,
$curl_error ?: 'None'
));
// Consider any response as success for cache clearing
if ($response !== false) {
$success = true;
error_log("Cache clear successful for URL: " . $info['url']);
} else {
$error = $curl_error ?: "HTTP Error: $http_code";
$error_messages[] = $error;
error_log("Cache clear failed for URL: " . $info['url'] . " - Error: " . $error);
}
curl_close($ch);
// Kısa bir bekleme ekleyelim
usleep(200000); // 200ms
}
}
return [
'success' => $success,
'errors' => array_unique($error_messages)
];
}
// Cache sistemlerini kontrol et ve temizle
foreach ($cache_systems as $name => $system) {
error_log("Checking cache system: " . $name);
if ($system['detect']($headers, $body)) {
error_log("Detected cache system: " . $name);
$result['debug']['detected_plugins'][] = $name;
$clear_info = $system['clear']($wp_url);
$clear_result = clearCache($wp_url, $clear_info);
if ($clear_result['success']) {
$result['cleared_plugins'][] = $name;
$cleared_count++;
error_log("Successfully cleared cache for: " . $name);
} else {
$result['debug']['errors'][] = [
'plugin' => $name,
'errors' => $clear_result['errors']
];
error_log("Failed to clear cache for: " . $name . " - Errors: " . implode(", ", $clear_result['errors']));
}
} else {
error_log("Cache system not detected: " . $name);
}
}
// Sonuç mesajını oluştur
if ($cleared_count > 0) {
$result['success'] = true;
$result['message'] = sprintf(
'%d adet cache sistemi temizlendi: %s',
$cleared_count,
implode(', ', $result['cleared_plugins'])
);
} else {
if (empty($result['debug']['detected_plugins'])) {
$result['message'] = "Temizlenecek cache sistemi bulunamadı.";
} else {
$result['message'] = "Cache sistemleri tespit edildi fakat temizlenemedi: " . implode(', ', $result['debug']['detected_plugins']);
}
}
error_log("Final result: " . print_r($result, true));
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
} catch (Exception $e) {
$error_message = $e->getMessage();
api_log("Cache temizleme hatası: " . $error_message, true);
$error_response = [
'success' => false,
'message' => "Cache temizleme işlemi başarısız oldu: " . $error_message,
'debug' => [
'error' => $error_message,
'trace' => $e->getTraceAsString(),
'domain' => $domain ?? null,
'wp_url' => $wp_url ?? null
]
];
echo json_encode($error_response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
}
// Website kontrolü ve backlink gösterimi
$stmt = $db->prepare("SELECT id, domain FROM websites WHERE domain = ? AND status = 1");
$stmt->execute([$domain]);
$website = $stmt->fetch();
api_log("Checking domain: " . $domain);
api_log("SQL Query: SELECT id, domain FROM websites WHERE domain = '" . $domain . "' AND status = 1");
api_log("Initial website check result: " . ($website ? "Found (ID: " . $website['id'] . ")" : "Not found"));
// Eğer website bulunamadıysa veya onaylı değilse, otomatik olarak ekle
if (!$website) {
try {
// HTTP ve HTTPS'i dene
$protocols = ['https://', 'http://'];
$domain_accessible = false;
$final_url = '';
api_log("Website not found in database, attempting to add automatically");
foreach ($protocols as $protocol) {
$test_url = $protocol . $domain;
api_log("Testing URL accessibility: " . $test_url);
$ch = curl_init($test_url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => false,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SchemapiBot/1.0; +https://schemapi.com/bot)'
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$info = curl_getinfo($ch);
api_log("CURL Info for {$test_url}:");
api_log("HTTP Code: {$http_code}");
api_log("Total Time: {$info['total_time']}");
api_log("Connect Time: {$info['connect_time']}");
api_log("Size Download: {$info['size_download']}");
api_log("Speed Download: {$info['speed_download']}");
if ($error) {
api_log("CURL Error: {$error}", true);
}
if ($http_code >= 200 && $http_code < 400) {
$domain_accessible = true;
$final_url = $test_url;
api_log("Successfully connected to domain via {$protocol}");
break;
} else {
api_log("Failed to connect via {$protocol} - HTTP Code: {$http_code}");
}
curl_close($ch);
}
if ($domain_accessible) {
api_log("Domain is accessible, proceeding with database insertion");
// Race condition kontrolü - normalize edilmiş domain'i kontrol et
$stmt = $db->prepare("SELECT id FROM websites WHERE domain = ?");
$stmt->execute([$domain]);
$existing = $stmt->fetch();
if (!$existing) {
api_log("No existing website found, inserting new record");
$stmt = $db->prepare("INSERT INTO websites (domain, status, created_at, is_approved) VALUES (?, 1, NOW(), 0)");
$stmt->execute([$domain]);
$website_id = $db->lastInsertId();
api_log("New website added successfully - ID: " . $website_id);
$website = [
'id' => $website_id,
'domain' => $domain
];
// Admin bildirimini ekle
try {
$stmt = $db->prepare("
INSERT INTO admin_notifications (
type,
message,
is_read,
created_at
) VALUES (
'new_domain',
?,
0,
NOW()
)
");
$notification_message = "Yeni domain eklendi: " . $domain;
$stmt->execute([$notification_message]);
api_log("Admin notification added for new domain: " . $domain);
} catch (Exception $e) {
api_log("Error adding admin notification: " . $e->getMessage(), true);
}
} else {
api_log("Website already exists (race condition prevented) - ID: " . $existing['id']);
$website = $existing;
}
} else {
api_log("Domain not accessible via any protocol", true);
ob_end_clean();
echo '
Domain not accessible via HTTP or HTTPS
';
exit;
}
} catch (Exception $e) {
api_log("Error adding new website: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString(), true);
ob_end_clean();
echo '
Error adding website: ' . htmlspecialchars($e->getMessage()) . '
';
exit;
}
}
// Aktif linkleri getir
api_log("Fetching active links for website ID: " . $website['id']);
$sql = "SELECT l.url, l.anchor_text
FROM links l
JOIN orders o ON l.order_id = o.id
WHERE o.website_id = ? AND (o.status = 'completed' OR o.status = 'active') AND l.is_active = 1
ORDER BY RAND()
LIMIT 10";
api_log("Executing SQL Query: " . str_replace("?", $website['id'], $sql));
$stmt = $db->prepare($sql);
$stmt->execute([$website['id']]);
$links = [];
$link_count = 0;
while ($row = $stmt->fetch()) {
$link_count++;
api_log("Processing link #{$link_count} - URL: {$row['url']}, Anchor: {$row['anchor_text']}");
// HTML bağlantılarını güvenli şekilde oluştur
$links[] = '
' .
htmlspecialchars($row['anchor_text'], ENT_QUOTES, 'UTF-8') . '';
}
api_log("Total links found: " . count($links));
if (empty($links)) {
api_log("No active links found for domain: " . $domain . " (Website ID: " . $website['id'] . ")", true);
ob_end_clean();
echo '
No active links found for: ' . htmlspecialchars($domain) . '
';
exit;
}
api_log("Returning " . count($links) . " links for domain: " . $domain);
echo '
' . implode(' ', $links) . '
';
} catch (PDOException $e) {
api_log("Database error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString(), true);
ob_end_clean();
echo '
Database error occurred
';
exit;
} catch (Exception $e) {
api_log("General error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString(), true);
ob_end_clean();
echo '
System error occurred
';
exit;
}
// Son olarak çıktı tamponunu gönder
ob_end_flush();
?>