39728-vm/patch_import.php
2026-04-19 14:31:28 +00:00

70 lines
3.0 KiB
PHP

<?php
$content = file_get_contents('stock.php');
$search = <<<'REPLACE'
if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
$pdo = db();
$file = fopen($_FILES['csv_file']['tmp_name'], 'r');
$bom = fread($file, 3);
if ($bom !== "") rewind($file);
$header = fgetcsv($file);
$imported = 0; $updated = 0;
$pdo->beginTransaction();
try {
$stmtInsert = $pdo->prepare("INSERT INTO items (sku, name, price, cost_price, base_stock, vat, category_id, supplier_id, unit_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmtUpdate = $pdo->prepare("UPDATE items SET name=?, price=?, cost_price=?, base_stock=?, vat=?, category_id=?, supplier_id=?, unit_id=? WHERE sku=?");
$stmtCheck = $pdo->prepare("SELECT id FROM items WHERE sku=?");
while (($row = fgetcsv($file)) !== false) {
REPLACE;
$replace = <<<'REPLACE'
if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
$pdo = db();
$file_path = $_FILES['csv_file']['tmp_name'];
$raw_content = file_get_contents($file_path);
// Prevent ZIP / XLSX
if (str_starts_with($raw_content, 'PK')) {
header('Location: stock.php?import_error=' . urlencode('يرجى حفظ الملف بصيغة CSV وليس كملف إكسل (XLSX)'));
exit;
}
// Remove UTF-8 BOM if present
if (str_starts_with($raw_content, "\xEF\xBB\xBF")) {
$raw_content = substr($raw_content, 3);
}
// Fix encoding for Windows-1256 (common in Arabic Excel exports)
if (!mb_check_encoding($raw_content, 'UTF-8')) {
$raw_content = mb_convert_encoding($raw_content, 'UTF-8', 'Windows-1256');
}
// Determine delimiter by checking first line
$first_line = strtok($raw_content, "\r\n");
$delimiter = ',';
if ($first_line !== false && substr_count($first_line, ';') > substr_count($first_line, ',')) {
$delimiter = ';';
}
$clean_file = tmpfile();
fwrite($clean_file, $raw_content);
rewind($clean_file);
$header = fgetcsv($clean_file, 0, $delimiter);
$imported = 0; $updated = 0;
$pdo->beginTransaction();
try {
$stmtInsert = $pdo->prepare("INSERT INTO items (sku, name, price, cost_price, base_stock, vat, category_id, supplier_id, unit_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmtUpdate = $pdo->prepare("UPDATE items SET name=?, price=?, cost_price=?, base_stock=?, vat=?, category_id=?, supplier_id=?, unit_id=? WHERE sku=?");
$stmtCheck = $pdo->prepare("SELECT id FROM items WHERE sku=?");
while (($row = fgetcsv($clean_file, 0, $delimiter)) !== false) {
REPLACE;
if (strpos($content, $search) !== false) {
$content = str_replace($search, $replace, $content);
file_put_contents('stock.php', $content);
echo "Replaced successfully.\n";
} else {
echo "Search string not found.\n";
}