Логирование методов пользователя

This commit is contained in:
rsgrinko committed 2022-04-19 00:10:36 +03:00
1 parent d77a8fc3c4
commit 893e1056fc
8 files changed
+274 -23

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
use Core\Models\User;
require_once __DIR__ . '/../../core/bootstrap.php';
$userId = User::getUserId();
$userId = User::getCurrentUserId();
if(!empty($userId)) {
$USER = new User($userId);
+2 -2
View File
@@ -3,7 +3,7 @@
use Core\Models\User;
require_once __DIR__ . '/bootstrap.php';
if (!User::isUser() and $_SERVER['REQUEST_URI'] !== '/login.php') {
if (!User::isAuthorized() and $_SERVER['REQUEST_URI'] !== '/login.php') {
header('Location: login.php');
die();
}
@@ -34,7 +34,7 @@
<header>
<div class="headerwrapper">
<div class="header-left">
<a href="index.html" class="logo">
<a href="index.php" class="logo">
<img src="//<?=$_SERVER['SERVER_NAME']; ?>/admin/styles/images/logo.png" alt=""/>
</a>
<div class="pull-right">
+1 -1
View File
@@ -4,7 +4,7 @@
require_once __DIR__ . '/inc/bootstrap.php';
if (User::isUser()) {
if (User::isAuthorized()) {
$auth = true;
} else {
$auth = false;
+1 -1
View File
@@ -11,7 +11,7 @@
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
/**
* Путь до диреткории с логами
* Путь до директории с логами
*/
define('LOG_PATH', $_SERVER['DOCUMENT_ROOT'] . '/core/log');
+146
View File
@@ -0,0 +1,146 @@
<?php
namespace Core\Helpers;
/**
* Класс для отправки E-mail
*/
class Mail
{
/**
* От кого
*/
public $fromEmail = '';
public $fromName = '';
/**
* Кому
*/
public $toEmail = '';
public $toName = '';
/**
* Тема
*/
public $subject = '';
/**
* Текст
*/
public $body = '';
/**
* Массив заголовков файлов
*/
private $_files = [];
/**
* От кого
*/
public function setFrom($email, $name = null)
{
$this->fromEmail = $email;
$this->fromName = $name;
}
/**
* Кому
*/
public function setTo($email, $name = null)
{
$this->toEmail = $email;
$this->toName = $name;
}
/**
* Тема
*/
public function setSubject($subject = null)
{
$this->subject = $subject;
}
/**
* Тело письма
*/
public function setBody($body = null)
{
$this->body = $body;
}
/**
* Добавление файла к письму
*/
public function addFile($filename)
{
if (is_file($filename)) {
$name = basename($filename);
$fp = fopen($filename, 'rb');
$file = fread($fp, filesize($filename));
fclose($fp);
$this->_files[] = [
'Content-Type: application/octet-stream; name="' . $name . '"',
'Content-Transfer-Encoding: base64',
'Content-Disposition: attachment; filename="' . $name . '"',
'',
chunk_split(base64_encode($file)),
];
}
}
/**
* Отправка
*/
public function send()
{
if (empty($this->toEmail)) {
return false;
}
$from = (empty($this->fromName)) ? $this->fromEmail : '=?UTF-8?B?' . base64_encode($this->fromName) . '?= <' . $this->fromEmail . '>';
$array_to = [];
foreach (explode(',', $this->toEmail) as $row) {
$row = trim($row);
if (!empty($row)) {
$array_to[] = (empty($this->toName)) ? $row : '=?UTF-8?B?' . base64_encode($this->toName) . '?= <' . $row . '>';
}
}
$subject = (empty($this->subject)) ? 'No subject' : $this->subject;
$body = $this->body;
$boundary = md5(uniqid(time()));
$headers = [
'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
'Content-Transfer-Encoding: 7bit',
'MIME-Version: 1.0',
'From: ' . $from,
'Date: ' . date('r'),
];
$message = [
'--' . $boundary,
'Content-Type: text/html; charset=UTF-8',
'Content-Transfer-Encoding: base64',
'',
chunk_split(base64_encode($body)),
];
if (!empty($this->_files)) {
foreach ($this->_files as $row) {
$message = array_merge($message, ['', '--' . $boundary], $row);
}
}
$message[] = '';
$message[] = '--' . $boundary . '--';
$res = [];
foreach ($array_to as $to) {
$res[] = mb_send_mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));
}
return $res;
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace Core\Helpers;
/**
* Класс для работы с Zip архивами
*/
class Zip
{
/**
* Создание архива из файла или папки
*
* @param string $source Архивируемый файл или папка
* @param string $destination Расположение созданного архива
*
* @return bool
*/
public static function createArchive(string $source, string $destination): bool
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new \ZipArchive();
if (!$zip->open($destination, \ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', DIRECTORY_SEPARATOR, realpath($source));
$source = str_replace('/', DIRECTORY_SEPARATOR, $source);
if (is_dir($source) === true) {
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
$file = str_replace('/', DIRECTORY_SEPARATOR, $file);
if ($file == '.' || $file == '..' || empty($file) || $file == DIRECTORY_SEPARATOR) {
continue;
}
// Пропускаем "." и ".."
if (in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1), ['.', '..'])) {
continue;
}
$file = realpath($file);
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
$file = str_replace('/', DIRECTORY_SEPARATOR, $file);
if (is_dir($file) === true) {
$d = str_replace($source . DIRECTORY_SEPARATOR, '', $file);
if (empty($d)) {
continue;
}
$zip->addEmptyDir($d);
} elseif (is_file($file) === true) {
$zip->addFromString(
str_replace($source . DIRECTORY_SEPARATOR, '', $file),
file_get_contents($file)
);
}
}
} elseif (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
/**
* Распаковка архива
*
* @param string $source Путь к архиву
* @param string $destination Путь распаковки
*
* @return bool
*/
public static function extractArchive(string $source, string $destination): bool
{
$zip = new \ZipArchive;
if ($zip->open($source)) {
$zip->extractTo($destination);
$zip->close();
return true;
} else {
return false;
}
}
}
+18 -14
View File
@@ -9,7 +9,7 @@
use Core\CoreException;
use Core\Models\DB;
use Core\Helpers\Cache;
use Core\Helpers\{Cache, Log};
class User
{
@@ -88,7 +88,7 @@
*/
public function getLogin(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['login'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['login'] : null;
}
/**
@@ -98,7 +98,7 @@
*/
public function getEmail(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['email'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['email'] : null;
}
/**
@@ -108,7 +108,7 @@
*/
public function getName(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['name'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['name'] : null;
}
/**
@@ -118,7 +118,7 @@
*/
public function getImage(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['image'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['image'] : null;
}
/**
@@ -128,7 +128,7 @@
*/
public function getToken(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['token'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['token'] : null;
}
/**
@@ -138,7 +138,7 @@
*/
public function getLastActive(): ?string
{
return self::getAllUserData() ? self::getAllUserData()['last_active'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['last_active'] : null;
}
/**
@@ -146,9 +146,9 @@
*
* @return int|null
*/
public static function getId(): ?int
public function getId(): ?int
{
return self::getAllUserData() ? self::getAllUserData()['id'] : null;
return $this->getAllUserData() ? $this->getAllUserData()['id'] : null;
}
/**
@@ -168,6 +168,7 @@
$res = (DB::getInstance())->query('SELECT * FROM `' . self::TABLE . '` ORDER BY `id` ' . $sort . ' LIMIT ' . $limit);
Cache::set($cacheId, $res);
}
Log::logToFile(__METHOD__, 'User.log', func_get_args());
return $res;
}
@@ -180,7 +181,7 @@
{
$newToken = self::generateGUID();
(DB::getInstance())->update(self::TABLE, ['id' => $this->id], ['token' => $newToken]);
Log::logToFile('Создан токен ' . $newToken, 'User.log');
return $newToken;
}
@@ -207,7 +208,6 @@
public static function isTokenExists(string $token): bool
{
$result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]);
if ($result) {
return true;
} else {
@@ -226,7 +226,6 @@
public static function getUserByToken(string $token): ?self
{
$result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]);
if ($result) {
return (new self($result['id']));
} else {
@@ -267,6 +266,7 @@
*/
public static function registration(string $login, string $password, string $email, string $level = 'user', string $name = '', string $image = ''): int
{
Log::logToFile(__METHOD__, 'User.log', func_get_args());
$userId = (DB::getInstance())->addItem(self::TABLE, [
'login' => $login,
'password' => md5(self::$cryptoSalt . $password),
@@ -345,6 +345,7 @@
setcookie('userLogin', $result['login'], time() + 3600 * 24);
setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24);
}
Log::logToFile(__METHOD__, 'User.log', func_get_args());
return true;
} else {
return false;
@@ -362,6 +363,7 @@
*/
public static function securityAuthorize(string $login, string $password, bool $remember = false): bool
{
Log::logToFile(__METHOD__, 'User.log', func_get_args());
$result = (DB::getInstance())->getItem(self::TABLE, ['login' => $login, 'password' => md5(self::$cryptoSalt . $password)], true);
if ($result) {
$_SESSION['id'] = $result['id'];
@@ -388,7 +390,7 @@
*/
public static function getCurrentUserId(): ?int
{
if (self::isUser()) {
if (self::isAuthorized()) {
return $_SESSION['id'];
} else {
return null;
@@ -399,8 +401,9 @@
* Проверка на пользователя
*
* @return bool
* @throws CoreException
*/
public static function isUser(): bool
public static function isAuthorized(): bool
{
if (!empty($_COOKIE['userId'])
&& !empty($_COOKIE['userLogin'])
@@ -448,6 +451,7 @@
*/
public static function logout(): void
{
Log::logToFile(__METHOD__, 'User.log', func_get_args());
$_SESSION['id'] = '';
$_SESSION['authorize'] = '';
$_SESSION['login'] = '';
+13 -4
View File
@@ -3,11 +3,16 @@
use Core\CoreException;
use Core\ExternalServices\Telegram;
use Core\Models\User;
use Core\Helpers\{SystemFunctions, Cache, Log};
use Core\Helpers\{SystemFunctions, Cache, Log, Mail, Zip};
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
/*$userId = User::registration('test', '12345', 'support@it-stories.ru', 'user', 'Тестировщик', 'http://samag.ru/uploads/5222447.png');
$user = new User($userId);*/
Telegram::init('5232660453:AAGfMWu6EcRfBGSSURJsEEvGPmAqhCyzYHU', './');
//$userId = User::registration('test', '12345', 'support@it-stories.ru', 'user', 'Тестировщик', 'http://samag.ru/uploads/5222447.png');
/*$user = new User($userId);*/
$userId = 2;//User::getUserId();
try {
@@ -17,11 +22,15 @@
} catch (CoreException $e) {
echo $e->showTrace();
}
die('stoped');
echo '<br><br>';
Zip::createArchive(LOG_PATH . '/', ROOT_PATH . '/core/cache/temp.zip');
Telegram::sendDocument(412790359, ROOT_PATH . '/core/cache/temp.zip');
unlink(ROOT_PATH . '/core/cache/temp.zip');
if(User::isUser()) {
if (User::isAuthorized()) {
echo SystemFunctions::arrayToTable($user->getAllUserData(), 'Информация о пользователе');
}