<?php
declare(strict_types=1);
session_start();
if (empty($_SESSION['miter'])) {
header('Location: ../../index.php');
exit;
}
if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
header('Location: ../../../index.php?u=settings');
exit;
}
$file_tmp = $_FILES['avatar']['tmp_name'];
$orig_name = $_FILES['avatar']['name'];
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
$file_ext = strtolower(pathinfo($orig_name, PATHINFO_EXTENSION));
if (!in_array($file_ext, $allowed_extensions, true)) {
header('Location: ../../../index.php?u=settings');
exit;
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $finfo->file($file_tmp);
$allowed_mimes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mime_type, $allowed_mimes, true)) {
header('Location: ../../../index.php?u=settings');
exit;
}
$miter_avatar = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $orig_name);
if ($miter_avatar === '' || $miter_avatar === '.' || $miter_avatar === '..') {
header('Location: ../../../index.php?u=settings');
exit;
}
$target_dir = "../../../images/";
$target_file = $target_dir . $miter_avatar;
if (move_uploaded_file($file_tmp, $target_file)) {
$user_file = '../../../user/user.xml';
if (file_exists($user_file)) {
$internal_errors = libxml_use_internal_errors(true);
$avatar_file = simplexml_load_file($user_file);
if ($avatar_file !== false) {
$nodes = $avatar_file->xpath("user[@id='probe']");
if (!empty($nodes)) {
foreach ($nodes as $data) {
$data->avatar = $miter_avatar;
}
$avatar_file->asXML($user_file);
}
}
libxml_clear_errors();
libxml_use_internal_errors($internal_errors);
}
}
header("Location: ../../index.php?u=settings");
exit;