HEX
Server: Apache
System: Linux server3230.server-vps.com 5.15.0-46-generic #49-Ubuntu SMP Thu Aug 4 18:03:25 UTC 2022 x86_64
User: lzgqnjwu (1002)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: //proc/1126/cwd/backend/controllers/BotFilesController.php
<?php

namespace backend\controllers;

use common\models\Bot;
use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\web\NotFoundHttpException;

/**
 * Контроллер для завантаження прайс-листів для ботів
 */
class BotFilesController extends Controller
{
    /**
     * Завантаження файлів прайс-листа для бота
     */
    public function actionUpload($bot_id)
    {
        $bot = $this->findBot($bot_id);
        
        // Створюємо папку для файлів бота
        $botStoragePath = Yii::getAlias('@storage/web/source/bot_' . $bot_id);
        if (!is_dir($botStoragePath)) {
            mkdir($botStoragePath, 0755, true);
        }
        
        $uploadedFiles = [];
        $errors = [];
        
        // Обробка Ukraine_Pricelist
        $pricelistFile = UploadedFile::getInstanceByName('pricelist_file');
        if ($pricelistFile) {
            $extension = strtolower($pricelistFile->extension);
            
            if (in_array($extension, ['xlsx', 'xls'])) {
                $fileName = 'Ukraine_Pricelist.' . $extension;
                $filePath = $botStoragePath . '/' . $fileName;
                
                if ($pricelistFile->saveAs($filePath)) {
                    $uploadedFiles[] = $fileName;
                    
                    // Видаляємо старий CSV якщо є (буде реконвертовано автоматично)
                    $csvPath = $botStoragePath . '/Ukraine_Pricelist.csv';
                    if (file_exists($csvPath)) {
                        unlink($csvPath);
                    }
                } else {
                    $errors[] = 'Не вдалося зберегти прайс-лист';
                }
            } else {
                $errors[] = 'Прайс-лист: дозволені тільки .xlsx або .xls файли';
            }
        }
        
        // Обробка Sklad
        $skladFile = UploadedFile::getInstanceByName('sklad_file');
        if ($skladFile) {
            $extension = strtolower($skladFile->extension);
            
            if (in_array($extension, ['xlsx', 'xls'])) {
                $fileName = 'Sklad.' . $extension;
                $filePath = $botStoragePath . '/' . $fileName;
                
                if ($skladFile->saveAs($filePath)) {
                    $uploadedFiles[] = $fileName;
                    
                    // Видаляємо старий CSV
                    $csvPath = $botStoragePath . '/Sklad.csv';
                    if (file_exists($csvPath)) {
                        unlink($csvPath);
                    }
                } else {
                    $errors[] = 'Не вдалося зберегти файл складу';
                }
            } else {
                $errors[] = 'Склад: дозволені тільки .xlsx або .xls файли';
            }
        }
        
        // Формуємо відповідь
        if (!empty($uploadedFiles)) {
            Yii::$app->session->setFlash('success', 
                'Файли завантажено: ' . implode(', ', $uploadedFiles)
            );
        }
        
        if (!empty($errors)) {
            Yii::$app->session->setFlash('error', implode('<br>', $errors));
        }
        
        if (empty($uploadedFiles) && empty($errors)) {
            Yii::$app->session->setFlash('warning', 'Файли не вибрано');
        }
        
        return $this->redirect(['/bot/update', 'id' => $bot_id]);
    }
    
    /**
     * Видалення файлів бота
     */
    public function actionDelete($bot_id, $file_type)
    {
        $bot = $this->findBot($bot_id);
        $botStoragePath = Yii::getAlias('@storage/web/source/bot_' . $bot_id);
        
        $deleted = false;
        
        if ($file_type === 'pricelist') {
            // Видаляємо прайс-лист
            foreach (['xlsx', 'xls', 'csv'] as $ext) {
                $filePath = $botStoragePath . '/Ukraine_Pricelist.' . $ext;
                if (file_exists($filePath)) {
                    unlink($filePath);
                    $deleted = true;
                }
            }
        } elseif ($file_type === 'sklad') {
            // Видаляємо склад
            foreach (['xlsx', 'xls', 'csv'] as $ext) {
                $filePath = $botStoragePath . '/Sklad.' . $ext;
                if (file_exists($filePath)) {
                    unlink($filePath);
                    $deleted = true;
                }
            }
        }
        
        if ($deleted) {
            Yii::$app->session->setFlash('success', 'Файл видалено');
        } else {
            Yii::$app->session->setFlash('warning', 'Файл не знайдено');
        }
        
        return $this->redirect(['/bot/update', 'id' => $bot_id]);
    }
    
    /**
     * Отримання інформації про завантажені файли
     */
    public function actionInfo($bot_id)
    {
        $bot = $this->findBot($bot_id);
        $botStoragePath = Yii::getAlias('@storage/web/source/bot_' . $bot_id);
        
        $files = [];
        
        // Перевіряємо прайс-лист
        foreach (['xlsx', 'xls'] as $ext) {
            $filePath = $botStoragePath . '/Ukraine_Pricelist.' . $ext;
            if (file_exists($filePath)) {
                $files['pricelist'] = [
                    'name' => 'Ukraine_Pricelist.' . $ext,
                    'size' => filesize($filePath),
                    'date' => date('Y-m-d H:i:s', filemtime($filePath))
                ];
                break;
            }
        }
        
        // Перевіряємо склад
        foreach (['xlsx', 'xls'] as $ext) {
            $filePath = $botStoragePath . '/Sklad.' . $ext;
            if (file_exists($filePath)) {
                $files['sklad'] = [
                    'name' => 'Sklad.' . $ext,
                    'size' => filesize($filePath),
                    'date' => date('Y-m-d H:i:s', filemtime($filePath))
                ];
                break;
            }
        }
        
        return $this->asJson($files);
    }
    
    /**
     * Знаходить бота або кидає 404
     */
    protected function findBot($id)
    {
        if (($model = Bot::findOne($id)) !== null) {
            return $model;
        }
        
        throw new NotFoundHttpException('Бот не знайдено');
    }
}