![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/soundstudiopro.com/private_html/ |
<?php
/**
* Backfill Track Images Script
* Downloads and stores all track images locally, removing external URL dependencies
*/
require_once 'config/database.php';
$pdo = getDBConnection();
if (!$pdo) {
die("â Database connection failed\n");
}
// Define the download function directly instead of including callback.php
// (callback.php outputs JSON which conflicts with HTML output)
function downloadAndStoreImage($imageUrl, $taskId) {
if (empty($imageUrl) || !filter_var($imageUrl, FILTER_VALIDATE_URL)) {
return null;
}
// Create image storage directory
$imageDir = 'uploads/track_covers/';
if (!is_dir($imageDir)) {
mkdir($imageDir, 0755, true);
}
// Generate filename
$extension = pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'jpg';
// Validate extension
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array(strtolower($extension), $allowedExtensions)) {
$extension = 'jpg'; // Default to jpg if extension is invalid
}
$filename = "track_{$taskId}_" . time() . ".{$extension}";
$localPath = $imageDir . $filename;
$webPath = '/uploads/track_covers/' . $filename;
// Skip if file already exists (check by task_id pattern)
$existingFiles = glob($imageDir . "track_{$taskId}_*");
if (!empty($existingFiles)) {
// Use the most recent existing file
$mostRecent = end($existingFiles);
return '/' . str_replace('\\', '/', $mostRecent);
}
// Download the file using cURL for better error handling
if (function_exists('curl_init')) {
$ch = curl_init($imageUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
$imageContent = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error || $httpCode !== 200 || $imageContent === false) {
error_log("Failed to download image from: $imageUrl (HTTP $httpCode, Error: $error)");
return null;
}
} else {
// Fallback to file_get_contents
$context = stream_context_create([
'http' => [
'timeout' => 60,
'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'follow_location' => true
]
]);
$imageContent = @file_get_contents($imageUrl, false, $context);
if ($imageContent === false) {
error_log("Failed to download image from: $imageUrl");
return null;
}
}
// Validate that it's actually an image
$imageInfo = @getimagesizefromstring($imageContent);
if ($imageInfo === false) {
error_log("Downloaded content is not a valid image: $imageUrl");
return null;
}
// Save the file
if (file_put_contents($localPath, $imageContent, LOCK_EX)) {
// Set proper permissions
chmod($localPath, 0644);
return $webPath;
} else {
error_log("Failed to save image to: $localPath");
return null;
}
}
echo "<!DOCTYPE html>
<html>
<head>
<title>Backfill Track Images</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
h1 { color: #333; }
.track-item { padding: 15px; margin: 10px 0; border: 1px solid #ddd; border-radius: 5px; background: #fafafa; }
.success { color: green; }
.error { color: red; }
.info { color: #666; }
.stats { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 20px 0; }
.stats h2 { margin-top: 0; }
</style>
</head>
<body>
<div class='container'>
<h1>đŧī¸ Backfill Track Images</h1>
<p>This script will download and store all track images locally, removing external URL dependencies.</p>
";
// Check if force_all is requested
$forceAll = isset($_GET['force_all']) && $_GET['force_all'] == '1';
// Get all tracks that might have images
$stmt = $pdo->prepare("
SELECT
id,
task_id,
title,
image_url,
metadata,
status
FROM music_tracks
WHERE status = 'complete'
ORDER BY created_at DESC
");
$stmt->execute();
$tracks = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stats = [
'total' => count($tracks),
'processed' => 0,
'downloaded' => 0,
'skipped' => 0,
'failed' => 0,
'updated' => 0,
'removed_external' => 0
];
echo "<div class='stats'>
<h2>Statistics</h2>
<p>Total tracks to process: <strong>{$stats['total']}</strong></p>
</div>";
foreach ($tracks as $track) {
$trackId = $track['id'];
$taskId = $track['task_id'];
$title = htmlspecialchars($track['title'] ?: 'Untitled Track');
$currentImageUrl = $track['image_url'];
$metadata = $track['metadata'];
echo "<div class='track-item'>";
echo "<h3>Track #{$trackId}: {$title}</h3>";
echo "<p class='info'>Task ID: {$taskId}</p>";
// Check if image_url is already local
$isLocal = false;
if (!empty($currentImageUrl)) {
if (strpos($currentImageUrl, 'http://') === 0 || strpos($currentImageUrl, 'https://') === 0) {
echo "<p class='error'>â External URL found: " . htmlspecialchars($currentImageUrl) . "</p>";
} else {
// Check if file exists
$localPath = ltrim($currentImageUrl, '/');
if (file_exists($localPath)) {
if (!$forceAll) {
echo "<p class='success'>â
Already has local image: {$currentImageUrl}</p>";
$isLocal = true;
$stats['skipped']++;
} else {
echo "<p class='info'>âšī¸ Has local image but force_all is enabled, will check for updates</p>";
}
} else {
echo "<p class='error'>â ī¸ Local path doesn't exist: {$currentImageUrl}</p>";
}
}
}
// Try to extract image URL from metadata if not found in image_url field
$imageUrlToDownload = null;
if (!$isLocal || $forceAll) {
if (!empty($currentImageUrl) && (strpos($currentImageUrl, 'http://') === 0 || strpos($currentImageUrl, 'https://') === 0)) {
$imageUrlToDownload = $currentImageUrl;
echo "<p class='info'>đĨ Will download from image_url field</p>";
} elseif (!empty($metadata)) {
$metadataArray = json_decode($metadata, true);
if (is_array($metadataArray)) {
// Check various possible locations in metadata
$possiblePaths = [
[['image_url'], 'metadata.image_url'],
[['cover_url'], 'metadata.cover_url'],
[['raw_callback', 'image_url'], 'metadata.raw_callback.image_url'],
[['raw_callback', 'cover_url'], 'metadata.raw_callback.cover_url'],
[['raw_callback', 'data', 'image_url'], 'metadata.raw_callback.data.image_url'],
[['raw_callback', 'data', 'data', 0, 'image_url'], 'metadata.raw_callback.data.data[0].image_url'],
[['raw_callback', 'data', 'data', 0, 'cover_url'], 'metadata.raw_callback.data.data[0].cover_url'],
];
foreach ($possiblePaths as $pathInfo) {
$path = $pathInfo[0];
$pathName = $pathInfo[1];
$value = $metadataArray;
foreach ($path as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
$value = null;
break;
}
}
if ($value && !empty($value) && (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0)) {
$imageUrlToDownload = $value;
echo "<p class='info'>đĨ Found image URL in {$pathName}</p>";
break;
}
}
}
}
// Also check task_results JSON file if no URL found yet
if (!$imageUrlToDownload) {
$taskResultFile = "task_results/{$taskId}.json";
if (file_exists($taskResultFile)) {
$taskResultContent = @file_get_contents($taskResultFile);
if ($taskResultContent) {
$taskResultData = @json_decode($taskResultContent, true);
if (is_array($taskResultData)) {
$possiblePaths = [
[['image_url'], 'task_results JSON: image_url'],
[['cover_url'], 'task_results JSON: cover_url'],
[['data', 'image_url'], 'task_results JSON: data.image_url'],
[['data', 'cover_url'], 'task_results JSON: data.cover_url'],
[['data', 'data', 0, 'image_url'], 'task_results JSON: data.data[0].image_url'],
[['data', 'data', 0, 'cover_url'], 'task_results JSON: data.data[0].cover_url'],
];
foreach ($possiblePaths as $pathInfo) {
$path = $pathInfo[0];
$pathName = $pathInfo[1];
$value = $taskResultData;
foreach ($path as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
$value = null;
break;
}
}
if ($value && !empty($value) && (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0)) {
$imageUrlToDownload = $value;
echo "<p class='info'>đĨ Found image URL in {$pathName}</p>";
break;
}
}
}
}
}
}
}
// Download and store the image
if ($imageUrlToDownload && (!$isLocal || $forceAll)) {
echo "<p class='info'>âŗ Downloading image from: " . htmlspecialchars($imageUrlToDownload) . "</p>";
$localImagePath = downloadAndStoreImage($imageUrlToDownload, $taskId);
if ($localImagePath) {
echo "<p class='success'>â
Downloaded and stored: {$localImagePath}</p>";
// Update database with local path
$updateStmt = $pdo->prepare("UPDATE music_tracks SET image_url = ? WHERE id = ?");
if ($updateStmt->execute([$localImagePath, $trackId])) {
echo "<p class='success'>â
Database updated with local path</p>";
$stats['updated']++;
} else {
echo "<p class='error'>â Failed to update database</p>";
}
$stats['downloaded']++;
} else {
echo "<p class='error'>â Failed to download image</p>";
$stats['failed']++;
// Remove external URL from database if download failed
if (!empty($currentImageUrl) && (strpos($currentImageUrl, 'http://') === 0 || strpos($currentImageUrl, 'https://') === 0)) {
$updateStmt = $pdo->prepare("UPDATE music_tracks SET image_url = NULL WHERE id = ?");
if ($updateStmt->execute([$trackId])) {
echo "<p class='info'>đī¸ Removed external URL from database</p>";
$stats['removed_external']++;
}
}
}
} elseif ((!$isLocal || $forceAll) && empty($imageUrlToDownload)) {
echo "<p class='info'>âšī¸ No image URL found to download (checked metadata and task_results)</p>";
if (!$forceAll) {
$stats['skipped']++;
}
}
$stats['processed']++;
echo "</div>";
// Flush output for real-time progress
if (ob_get_level() > 0) {
ob_flush();
}
flush();
}
echo "<div class='stats'>
<h2>Final Statistics</h2>
<p><strong>Total tracks:</strong> {$stats['total']}</p>
<p><strong>Processed:</strong> {$stats['processed']}</p>
<p class='success'><strong>Downloaded:</strong> {$stats['downloaded']}</p>
<p class='info'><strong>Skipped (already local):</strong> {$stats['skipped']}</p>
<p class='error'><strong>Failed:</strong> {$stats['failed']}</p>
<p class='success'><strong>Database updated:</strong> {$stats['updated']}</p>
<p class='info'><strong>External URLs removed:</strong> {$stats['removed_external']}</p>
</div>";
echo "</div></body></html>";
?>