-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate_files.php
More file actions
452 lines (381 loc) · 15 KB
/
migrate_files.php
File metadata and controls
452 lines (381 loc) · 15 KB
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
#!/usr/bin/env php
<?php
/**
* CDN File Migration Script
*
* This script migrates existing files in the img/ directory to the CDN database.
* It will:
* 1. Create database records for files without records
* 2. Generate thumbnails for JPG/JPEG/PNG files if they don't exist
* 3. Calculate MD5 hashes for all files
* 4. Update file creation dates
*
* Usage: php migrate_files.php
*/
// Load configuration
require_once __DIR__ . '/api/config.php';
require_once __DIR__ . '/api/database.php';
// Database connection
try {
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
DB_USER,
DB_PASS,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]
);
echo "✅ Database connection established\n";
} catch (PDOException $e) {
die("❌ Database connection failed: " . $e->getMessage() . "\n");
}
// Function to get file information
function getFileInfo($fileData) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_buffer($finfo, $fileData);
finfo_close($finfo);
// Check if it's an image
$isImage = strpos($mimeType, 'image/') === 0;
// Get extension from MIME type
$extension = getExtensionFromMime($mimeType);
return [
'mime_type' => $mimeType,
'is_image' => $isImage,
'extension' => $extension
];
}
function getExtensionFromMime($mimeType) {
$mimeToExt = [
'image/jpeg' => 'jpg',
'image/jpg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
'image/tiff' => 'tiff',
'image/svg+xml' => 'svg',
'image/x-icon' => 'ico',
'image/avif' => 'avif',
'image/heic' => 'heic',
'image/heif' => 'heif',
'video/mp4' => 'mp4',
'video/webm' => 'webm',
'video/avi' => 'avi',
'video/quicktime' => 'mov',
'video/x-msvideo' => 'avi',
'video/x-ms-wmv' => 'wmv',
'video/x-flv' => 'flv',
'video/x-matroska' => 'mkv',
'video/x-m4v' => 'm4v',
'video/3gpp' => '3gp',
'video/ogg' => 'ogv'
];
return $mimeToExt[$mimeType] ?? 'bin';
}
// Function to create thumbnail
function createThumbnail($imageData, $extension) {
$image = imagecreatefromstring($imageData);
if (!$image) {
throw new Exception('Failed to create image from data');
}
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
// Calculate thumbnail dimensions
if ($originalWidth > $originalHeight) {
$thumbWidth = MAX_THUMB_SIZE;
$thumbHeight = intval(($originalHeight * MAX_THUMB_SIZE) / $originalWidth);
} else {
$thumbHeight = MAX_THUMB_SIZE;
$thumbWidth = intval(($originalWidth * MAX_THUMB_SIZE) / $originalHeight);
}
// Create thumbnail
$thumbnail = imagecreatetruecolor($thumbWidth, $thumbHeight);
// Preserve transparency for PNG
if (strtolower($extension) === 'png') {
imagealphablending($thumbnail, false);
imagesavealpha($thumbnail, true);
$transparent = imagecolorallocatealpha($thumbnail, 255, 255, 255, 127);
imagefill($thumbnail, 0, 0, $transparent);
}
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $originalWidth, $originalHeight);
// Output to buffer
ob_start();
if (strtolower($extension) === 'jpg' || strtolower($extension) === 'jpeg') {
imagejpeg($thumbnail, null, JPEG_QUALITY);
} elseif (strtolower($extension) === 'png') {
imagepng($thumbnail, null, PNG_COMPRESSION);
} else {
imagepng($thumbnail, null, PNG_COMPRESSION);
}
$thumbnailData = ob_get_clean();
imagedestroy($image);
imagedestroy($thumbnail);
return $thumbnailData;
}
// Function to resize image if needed
function resizeImage($imageData, $extension) {
$image = imagecreatefromstring($imageData);
if (!$image) {
throw new Exception('Failed to create image from data');
}
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
// Calculate new dimensions
if ($originalWidth > $originalHeight) {
$newWidth = MAX_IMAGE_SIZE;
$newHeight = intval(($originalHeight * MAX_IMAGE_SIZE) / $originalWidth);
} else {
$newHeight = MAX_IMAGE_SIZE;
$newWidth = intval(($originalWidth * MAX_IMAGE_SIZE) / $originalHeight);
}
// Create resized image
$resized = imagecreatetruecolor($newWidth, $newHeight);
// Preserve transparency for PNG
if (strtolower($extension) === 'png') {
imagealphablending($resized, false);
imagesavealpha($resized, true);
$transparent = imagecolorallocatealpha($resized, 255, 255, 255, 127);
imagefill($resized, 0, 0, $transparent);
}
imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
// Output to buffer
ob_start();
if (strtolower($extension) === 'jpg' || strtolower($extension) === 'jpeg') {
imagejpeg($resized, null, JPEG_QUALITY);
} elseif (strtolower($extension) === 'png') {
imagepng($resized, null, PNG_COMPRESSION);
} else {
imagepng($resized, null, PNG_COMPRESSION);
}
$resizedData = ob_get_clean();
imagedestroy($image);
imagedestroy($resized);
return $resizedData;
}
// Check if img directory exists
if (!is_dir(IMAGES_DIR)) {
die("❌ Images directory not found: " . IMAGES_DIR . "\n");
}
// Create thumbs directory if it doesn't exist
if (!is_dir(THUMBS_DIR)) {
mkdir(THUMBS_DIR, 0755, true);
echo "📁 Created thumbs directory: " . THUMBS_DIR . "\n";
}
// Get all files in img directory
$files = glob(IMAGES_DIR . '*');
$totalFiles = count($files);
$processedFiles = 0;
$createdRecords = 0;
$updatedRecords = 0;
$createdThumbnails = 0;
$skippedRecords = 0;
echo "🚀 Starting migration of {$totalFiles} files...\n\n";
foreach ($files as $filePath) {
$filename = basename($filePath);
$processedFiles++;
echo "[{$processedFiles}/{$totalFiles}] Processing: {$filename}\n";
// Check if file exists and is readable
if (!is_file($filePath) || !is_readable($filePath)) {
echo " ⚠️ Skipping: File not readable\n";
continue;
}
// Get file information
$fileSize = filesize($filePath);
$fileTime = filemtime($filePath);
$createdDate = date('Y-m-d H:i:s', $fileTime);
// Determine file type and get dimensions
$fileData = file_get_contents($filePath);
$fileHash = md5($fileData); // Calculate MD5 hash
$fileTypeInfo = getFileInfo($fileData);
$isImage = $fileTypeInfo['is_image'];
$mimeType = $fileTypeInfo['mime_type'];
$extension = $fileTypeInfo['extension'];
// Check if extension is allowed
if (!in_array(strtolower($extension), ALLOWED_EXTENSIONS)) {
echo " ⚠️ Skipping: Extension '{$extension}' not allowed\n";
continue;
}
// Get image dimensions
$width = 0;
$height = 0;
$originalWidth = 0;
$originalHeight = 0;
if ($isImage) {
$imageInfo = getimagesizefromstring($fileData);
if ($imageInfo) {
$originalWidth = $imageInfo[0];
$originalHeight = $imageInfo[1];
// Check if image needs resizing
if ($originalWidth > MAX_IMAGE_SIZE || $originalHeight > MAX_IMAGE_SIZE) {
echo " 🔄 Resizing image from {$originalWidth}x{$originalHeight} to max " . MAX_IMAGE_SIZE . "px\n";
$resizedData = resizeImage($fileData, $extension);
file_put_contents($filePath, $resizedData);
$fileSize = strlen($resizedData);
$resizedInfo = getimagesizefromstring($resizedData);
if ($resizedInfo) {
$width = $resizedInfo[0];
$height = $resizedInfo[1];
}
} else {
$width = $originalWidth;
$height = $originalHeight;
}
}
}
// Check if database record exists by filename
$existingRecord = $pdo->query("SELECT * FROM cdn_files WHERE filename = '{$filename}'")->fetch();
// Check if file with same hash already exists
$existingHashRecord = $pdo->query("SELECT * FROM cdn_files WHERE file_hash = '{$fileHash}'")->fetch();
if (!$existingRecord && !$existingHashRecord) {
// Create new database record
echo " 📝 Creating database record...\n";
// Process thumbnail if needed
$thumbFilename = '';
$thumbWidth = 0;
$thumbHeight = 0;
$thumbSize = 0;
if (in_array(strtolower($extension), THUMBNAIL_EXTENSIONS) && $isImage) {
$thumbPath = THUMBS_DIR . $filename;
if (!file_exists($thumbPath)) {
echo " 🖼️ Creating thumbnail...\n";
$thumbData = createThumbnail($fileData, $extension);
file_put_contents($thumbPath, $thumbData);
$thumbSize = strlen($thumbData);
$createdThumbnails++;
// Get thumbnail dimensions
$thumbInfo = getimagesizefromstring($thumbData);
if ($thumbInfo) {
$thumbWidth = $thumbInfo[0];
$thumbHeight = $thumbInfo[1];
}
} else {
echo " ✅ Thumbnail already exists\n";
$thumbSize = filesize($thumbPath);
// Get thumbnail dimensions
$thumbInfo = getimagesize($thumbPath);
if ($thumbInfo) {
$thumbWidth = $thumbInfo[0];
$thumbHeight = $thumbInfo[1];
}
}
$thumbFilename = $filename;
}
// Insert new record with duplicate handling
try {
$stmt = $pdo->prepare("
INSERT INTO cdn_files (
filename, thumb_filename, file_hash, original_width, original_height,
width, height, thumb_width, thumb_height, file_size, thumb_size,
extension, mime_type
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$filename,
$thumbFilename,
$fileHash,
$originalWidth,
$originalHeight,
$width,
$height,
$thumbWidth,
$thumbHeight,
$fileSize,
$thumbSize,
$extension,
$mimeType
]);
$createdRecords++;
echo " ✅ Record created successfully\n";
} catch (PDOException $e) {
if ($e->getCode() == 23000 && strpos($e->getMessage(), 'Duplicate entry') !== false) {
echo " ⚠️ Record already exists (hash collision), skipping...\n";
$skippedRecords++;
} else {
throw $e; // Re-throw if it's not a duplicate key error
}
}
} elseif ($existingHashRecord && !$existingRecord) {
// File with same hash exists but different filename - update the existing record
echo " 🔄 File with same content exists, updating existing record...\n";
// Update the existing record with new filename and metadata
$stmt = $pdo->prepare("
UPDATE cdn_files SET
filename = ?,
updated_at = CURRENT_TIMESTAMP
WHERE file_hash = ?
");
$stmt->execute([$filename, $fileHash]);
$updatedRecords++;
echo " ✅ Record updated with new filename\n";
} else {
// Update existing record
echo " 🔄 Updating existing record...\n";
// Check if the hash we're trying to set already exists in another record
$hashExistsElsewhere = $pdo->query("SELECT COUNT(*) FROM cdn_files WHERE file_hash = '{$fileHash}' AND filename != '{$filename}'")->fetchColumn();
if ($hashExistsElsewhere > 0) {
echo " ⚠️ Hash already exists in another record, skipping hash update...\n";
// Only update timestamp, not the hash
$stmt = $pdo->prepare("
UPDATE cdn_files SET
updated_at = CURRENT_TIMESTAMP
WHERE filename = ?
");
$stmt->execute([$filename]);
} else {
// Update hash and timestamp
$stmt = $pdo->prepare("
UPDATE cdn_files SET
file_hash = ?,
updated_at = CURRENT_TIMESTAMP
WHERE filename = ?
");
$stmt->execute([$fileHash, $filename]);
}
// Create thumbnail if missing and applicable
if (in_array(strtolower($extension), THUMBNAIL_EXTENSIONS) && $isImage) {
$thumbPath = THUMBS_DIR . $filename;
if (!file_exists($thumbPath)) {
echo " 🖼️ Creating missing thumbnail...\n";
$thumbData = createThumbnail($fileData, $extension);
file_put_contents($thumbPath, $thumbData);
$thumbSize = strlen($thumbData);
$createdThumbnails++;
// Get thumbnail dimensions
$thumbInfo = getimagesizefromstring($thumbData);
if ($thumbInfo) {
$thumbWidth = $thumbInfo[0];
$thumbHeight = $thumbInfo[1];
}
// Update thumbnail info in database
$stmt = $pdo->prepare("
UPDATE cdn_files SET
thumb_filename = ?,
thumb_width = ?,
thumb_height = ?,
thumb_size = ?
WHERE filename = ?
");
$stmt->execute([$filename, $thumbWidth, $thumbHeight, $thumbSize, $filename]);
} else {
echo " ✅ Thumbnail already exists\n";
}
}
$updatedRecords++;
echo " ✅ Record updated successfully\n";
}
echo "\n";
}
// Summary
echo "🎉 Migration completed!\n";
echo "📊 Summary:\n";
echo " • Total files processed: {$processedFiles}\n";
echo " • New records created: {$createdRecords}\n";
echo " • Records updated: {$updatedRecords}\n";
echo " • Records skipped (duplicates): {$skippedRecords}\n";
echo " • Thumbnails created: {$createdThumbnails}\n";
echo " • Hash algorithm: MD5\n";
echo " • Timestamps: created_at/updated_at\n";
echo "\n✅ Migration script completed successfully!\n";
?>