Files
BiveEngine/engine/Main/trait.files.php
2025-12-24 19:19:01 +03:00

121 lines
4.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// Работа с файлами
defined('ROOT_DIR') || exit;
trait Files {
// Получить файл по ID
public function file_get($file_id)
{
$keys = $this->db_query("SELECT * FROM `bive_files` WHERE `id` = ?", array($file_id), true);
if(!count($keys)) return false;
return $keys[0];
}
// Удалить файл по его ID
public function file_delete($file_id): bool
{
$db_file = $this->file_get($file_id);
if(!$db_file) return false;
$file_path = ROOT_DIR . SLASH . STORAGE_DIR_NAME . "/files/" . $db_file["file_name"];
unlink($file_path);
$this->db_query("DELETE FROM `bive_files` WHERE `id` = ?", array($file_id), true);
return true;
}
// Проверить есть ли файл по его ID
public function file_has($file_id): bool
{
$db_file = $this->file_get($file_id);
if($db_file === false) return false;
$file_path = ROOT_DIR . SLASH . STORAGE_DIR_NAME . "/files/" . $db_file["file_name"];
return file_exists($file_path);
}
// Получить ссылку на файл по ID
public function file_get_link($file_id)
{
$db_file = $this->file_get($file_id);
if($db_file === false) return false;
return $this->router_get_root_uri() . "/" . STORAGE_DIR_NAME . "/files/" . $db_file["file_name"];
}
// Сохранить файл и вернуть его ID в базе
public function files_save($file, $max_size = 5242880, $file_types = array("jpeg", "jpg", "png", "svg", "webp"))
{
if(!isset($file) || $file["error"] != 0) return false;
$storage = $this->get_storage_dir();
$file_name = $file["name"];
$file_size = $file["size"];
$file_type = strtolower(pathinfo(SLASH . $file_name, PATHINFO_EXTENSION));
if ($file_size > $max_size) {
$this->alerts_add("Размер файла превышает минимально допустимый.", "error", "file");
return false;
}
$db_name = $this->files_create_name() . "." . $file_type;
$targetDir = $storage . SLASH . "files" . SLASH; // Директория для сохранения загруженных файлов
$targetFile = $targetDir . basename($db_name); // Полный путь до файла
if(!in_array($file_type, $file_types)) {
$this->alerts_add("Недопустимое расширение файла.", "error", "file");
return false;
}
if (move_uploaded_file($file["tmp_name"], $targetFile)) {
return $this->files_db_add($db_name, $file_size, $file_type, $targetFile);
} else {
$this->alerts_add("Произошла ошибка при загрузке файла.", "error", "file");
return false;
}
}
// Сохранить файлы по имени поля
public function files_save_by_name($name, $max_size = 5242880, $file_types = array("jpeg", "jpg", "png", "svg", "webp"))
{
if(!isset($_FILES[$name]) || $_FILES[$name]["error"] != 0) return false;
return $this->files_save($_FILES[$name], $max_size, $file_types);
}
// Добавление файла в базу данных
public function files_db_add($file_name, $weight, $mime_type, $path)
{
global $b;
return $b->db_insert("INSERT INTO `bive_files`(`path`, `mime_type`, `weight`, `file_name`) VALUES (?, ?, ?, ?)", array($path, $mime_type, $weight, $file_name));
}
// Форматирование файлов под поле
public function files_field_formate($name)
{
$file = $_FILES[$name];
if(!isset($file)) return false;
if(is_string($file["name"])) return $file;
$fields = array();
$this->files_field_formate_recurse($file, $fields);
return $fields;
}
// Рекурсивная функция форматирования файлов
private function files_field_formate_recurse($files_array, &$fields, $prop = null)
{
foreach ($files_array as $prop_key => $prop_value) {
if(is_array($prop_value)){
if($prop) $this->files_field_formate_recurse($prop_value,$fields[$prop_key], $prop);
else $this->files_field_formate_recurse($prop_value,$fields, $prop_key);
} else {
$fields[$prop_key][$prop] = $prop_value;
}
}
}
// Рандомное название для файла
public function files_create_name()
{
return bin2hex(random_bytes(16));
}
}