core/api/php/core.php

378 lines
16 KiB
PHP
Raw Normal View History

2022-12-11 13:55:49 +05:00
<?php
2023-08-28 22:47:07 +05:00
class core
{
2022-12-11 13:55:49 +05:00
public static $settings = '';
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
08.12.2022
Наполняем базу городов, регионов и стран
---------------------------------------------------------------------- */
static function get_geo_api($ip)
{
2022-12-11 13:55:49 +05:00
$ch = curl_init('http://ip-api.com/json/' . $ip . '?lang=ru');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$res = curl_exec($ch);
curl_close($ch);
$res = json_decode($res, true);
2023-08-28 22:47:07 +05:00
return $res;
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
static function geo()
{
$res = self::get_geo_api($_SERVER['REMOTE_ADDR']);
2022-12-11 15:29:37 +05:00
$strana_id = \DB::getValue('SELECT `id` FROM `strana` WHERE `txt` = "' . $res['country'] . '"');
2023-08-28 22:47:07 +05:00
if (!$strana_id && $res['country'])
$strana_id = \DB::add("INSERT INTO `strana` (`txt`) VALUES (?)", array($res['country']));
2023-02-08 16:59:59 +05:00
$region_id = \DB::getValue('SELECT `id` FROM `region` WHERE `txt` = "' . $res['regionName'] . '" AND `strana_id` = ' . $strana_id);
2023-08-28 22:47:07 +05:00
if (!$region_id && $res['regionName'])
$region_id = \DB::add("INSERT INTO `region` (`txt`, `strana_id`) VALUES (?, ?)", array($res['regionName'], $strana_id));
$city_id = \DB::getValue('SELECT `id` FROM `city` WHERE `txt` = "' . $res['city'] . '" AND `strana_id` = ' . $strana_id . ' AND `region_id`=' . $region_id);
if (!$city_id && $res['city']) {
$city_id = \DB::add("INSERT INTO `city` (`txt`, `strana_id`, `region_id`) VALUES (?, ?, ?)", array($res['city'], $strana_id, $region_id));
$_SESSION['city'] = $city_id;
2022-12-17 18:15:09 +05:00
}
2023-08-28 22:47:07 +05:00
}
/* ----------------------------------------------------------------------
08.12.2022
Берем настройки модуля/сайта
---------------------------------------------------------------------- */
static function getSettings($set, $mod = 'global')
{
2023-01-14 21:17:46 +05:00
//echo 'SELECT `json` FROM `settings` WHERE `mod` = "' . $mod . '" LIMIT 1';
2022-12-17 18:15:09 +05:00
$txt = \DB::getValue('SELECT `json` FROM `settings` WHERE `mod` = "' . $mod . '" LIMIT 1');
2023-08-28 22:47:07 +05:00
$massiv = \json::from_j($txt);
2022-12-11 13:55:49 +05:00
return $massiv[$set];
2023-08-28 22:47:07 +05:00
}
/* ----------------------------------------------------------------------
02.04.2023
Все настройки модуля
---------------------------------------------------------------------- */
static function setSettingsMod($mod = 'global')
{
$json = \DB::getValue("SELECT `json` FROM `settings` WHERE `mod`=?", $mod);
// echo $json;
return \json::from_j($json);
}
/* ----------------------------------------------------------------------
08.12.2022
Авторизация по куки
---------------------------------------------------------------------- */
static function loginCookies()
{
if (@$_COOKIE['cookies'] && !@$_SESSION['user_id']) {
$res = \json::from_j(base64_decode($_COOKIE['cookies']));
2022-12-11 15:29:37 +05:00
$users = \DB::getAll('SELECT `dostup`, `act` FROM `users` WHERE `id` = "' . $res['user_id'] . '" AND `pwd`="' . $res['pwd'] . '" LIMIT 1');
2023-08-28 22:47:07 +05:00
if ($users[0]['dostup']) {
2022-12-11 13:55:49 +05:00
$_SESSION['user_id'] = $res['user_id'];
2022-12-17 18:15:09 +05:00
$_SESSION['dostup'] = $users[0]['dostup'];
2022-12-11 13:55:49 +05:00
}
}
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
09.12.2022
Получаем данные корзины
Выводим массив, в массиве cart - все содержимое корзины, в summ - итог корзины
---------------------------------------------------------------------- */
static function getCart()
{
$session_id = (@$_SESSION['user_id']) ? @$_SESSION['user_id'] : session_id();
$cart = \DB::getAll("SELECT * FROM `cart` WHERE `user_id`=? AND `order` IS NULL", $session_id);
2022-12-24 21:12:23 +05:00
$summ = 0;
//Получаем название товаров и цены
2023-08-28 22:47:07 +05:00
for ($i = 0; $i < count($cart); $i++) {
$t = \DB::getRow("SELECT `title`, `cena` FROM `tovar` WHERE `id`=? LIMIT 1", $cart[$i]['tovar_id']);
2023-07-12 20:02:20 +05:00
//$cart[$i]['title'] = \DB::getValue( "SELECT `title` FROM `tovar` WHERE `id`=? LIMIT 1", $cart[$i]['tovar_id'] );
$cart[$i]['title'] = $t['title'];
$cart[$i]['cena'] = $t['cena'];
2023-08-28 22:47:07 +05:00
$cart[$i]['img'] = \DB::getValue("SELECT `filename` FROM `tovar_img` WHERE `tovar_id`=? LIMIT 1", $cart[$i]['tovar_id']);
2023-07-12 20:02:20 +05:00
//$cart[$i]['cena'] = \DB::getValue( "SELECT `cena` FROM `tovar_price_history` WHERE `tovar_id`=? ORDER BY `t` DESC LIMIT 1", $cart[$i]['tovar_id'] );
2022-12-24 21:12:23 +05:00
$cart[$i]['st'] = $cart[$i]['kolvo'] * $cart[$i]['cena'];
$summ = $summ + $cart[$i]['st'];
2022-12-11 13:55:49 +05:00
}
2022-12-24 21:12:23 +05:00
$result['cart'] = $cart;
$result['summ'] = $summ;
return $result;
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
20.12.2022
Получаем данные об основной организации пользователя
---------------------------------------------------------------------- */
static function getUserMainOrg($user_id)
{
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
09.12.2022
IP
---------------------------------------------------------------------- */
static function detect_ip()
{
$ip = false;
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) and preg_match("#^[0-9.]+$#", $_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_X_REAL_IP"]) and preg_match("#^[0-9.]+$#", $_SERVER["HTTP_X_REAL_IP"])) {
$ip = $_SERVER["HTTP_X_REAL_IP"];
} else if (preg_match("#^[0-9.]+$#", $_SERVER["REMOTE_ADDR"])) {
$ip = $_SERVER["REMOTE_ADDR"];
}
return $ip;
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
09.12.2022
Авторизация
---------------------------------------------------------------------- */
private static function redirectAfterLogin($dostup)
{
if ($dostup == 'a' || $dostup == 'm')
header('Location: /admin/');
if ($dostup == 'u')
header('Location: /' . self::getSettings('default_mod_auth') . '/');
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
static function login()
{
$user = \DB::getAll('SELECT `id`, `dostup` FROM `users` WHERE `email` = ? AND `pwd`=? LIMIT 1', array($_POST['email'], md5($_POST['pwd'])));
if ($user[0]['dostup']) {
2022-12-17 18:15:09 +05:00
$_SESSION['dostup'] = $user[0]['dostup'];
2022-12-11 13:55:49 +05:00
$_SESSION['user_id'] = $user[0]['id'];
}
2023-08-28 22:47:07 +05:00
if ($_POST['remember'] == 'on' && $user[0]['dostup']) {
2022-12-11 13:55:49 +05:00
$_SESSION['pwd'] = md5($_POST['pwd']);
2023-08-28 22:47:07 +05:00
$cookies = base64_encode(\json::to_j($_SESSION));
2022-12-11 13:55:49 +05:00
$tri_mes = time() + 31536000;
2023-08-28 22:47:07 +05:00
setcookie('cookies', $cookies, $tri_mes, '/', $_SERVER['SERVER_NAME']);
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
self::redirectAfterLogin($user[0]['dostup']);
2022-12-11 13:55:49 +05:00
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
12.12.2022
Получаем данные о пользователе
---------------------------------------------------------------------- */
static function getUserInfo($id)
{
2023-08-14 09:15:58 +05:00
//echo 'SELECT * FROM `users` WHERE `id` = ' . $id . ' LIMIT 1';
2023-08-28 22:47:07 +05:00
$user = \DB::getAll('SELECT `fio` FROM `users` WHERE `id` = ? LIMIT 1', $id);
2022-12-17 18:15:09 +05:00
return $user;
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
13.12.2022
Шифровальщик
---------------------------------------------------------------------- */
2023-07-12 20:02:20 +05:00
/*static function crypt ( $String, $act='crypt', $pwd ) {
2022-12-17 18:15:09 +05:00
if ($act=='crypt')$String=base64_encode($String);
$Salt='BGuxLWQtKweKEMV4';
$StrLen = strlen($String);
$Seq = $Password;
$Gamma = '';
while (strlen($Gamma)<$StrLen){
$Seq = pack("H*",sha1($Gamma.$Seq.$Salt));
$Gamma.=substr($Seq,0,8);
}
$result = $String^$Gamma;
if ($act=='decrypt')$String=base64_decode($String);
return $result;
2023-07-12 20:02:20 +05:00
}*/
2022-12-17 18:15:09 +05:00
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
15.12.2022
Генератор паролей
---------------------------------------------------------------------- */
static function genpassword($number = 10)
{
$arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
$pass = "";
for ($i = 0; $i < $number; $i++) {
$index = rand(0, count($arr) - 1);
2022-12-17 18:15:09 +05:00
$pass .= $arr[$index];
2023-08-28 22:47:07 +05:00
}
2022-12-17 18:15:09 +05:00
return $pass;
2023-01-07 18:55:55 +05:00
}
2023-08-28 22:47:07 +05:00
/* ----------------------------------------------------------------------
28.12.2022
Получаем мета-теги - для модулей не имеющих свои теги (используется в /main)
---------------------------------------------------------------------- */
static function getMeta($mod, $id = 0)
{
$massiv = \DB::getAll('SELECT * FROM `meta` WHERE `id` = ? AND `mod`=? LIMIT 1', array($id, $mod));
if (count($massiv) == 0)
\DB::add("INSERT INTO `meta` (`id`, `mod`) VALUES (?, ?)", array($id, $mod));
$res = $massiv[0];
return $res;
}
/* ----------------------------------------------------------------------
03.01.2023
Хлебные крошки
---------------------------------------------------------------------- */
static function getBreadcrumb($table, $category)
{
$p = $category;
$i = 0;
while ($p != 0) {
$massiv = \DB::getAll("SELECT `id`, `title`, `category` FROM `" . $table . "` WHERE `id`=? LIMIT 1", $p);
$res[$i]['id'] = $massiv[0]['id'];
$res[$i]['title'] = $massiv[0]['title'];
$i++;
$p = $massiv[0]['category'];
}
if (@$res)
return array_reverse($res);
}
/* ----------------------------------------------------------------------
02.02.2023
Архиватор и разорхиватор
---------------------------------------------------------------------- */
static function zip($txt)
{
return base64_encode(gzcompress($txt, 9));
}
static function unzip($txt)
{
return gzuncompress(base64_decode($txt));
}
/* ----------------------------------------------------------------------
27.02.2023
Проверяем ид или ид сессии пользователя (для Интернет-магазина)
---------------------------------------------------------------------- */
static function checkMe()
{
return ($_SESSION['user_id']) ? $_SESSION['user_id'] : session_id();
}
/* ----------------------------------------------------------------------
07.02.2023
Добавляем в корзину
---------------------------------------------------------------------- */
static function addToCart($tovar_id, $kolvo = 1)
{
$user_id = self::checkMe();
// $session_id = \core::checkMe();
2023-03-11 21:03:29 +05:00
//Получаем количество, если есть...
2023-08-28 22:47:07 +05:00
$kolvo = \DB::getValue("SELECT `kolvo` FROM `cart` WHERE `user_id`=? AND `tovar_id`=?", array($user_id, $_POST['pages_id']));
if ($kolvo) {
$kolvo = $kolvo + $_POST['kolvo'];
\DB::set("UPDATE `cart` SET `kolvo`=? WHERE `user_id`=? AND `tovar_id`=?", array($kolvo, $user_id, $_POST['pages_id']));
} else
$insert_id = \DB::add("INSERT INTO `cart` (`t`, `tovar_id`, `user_id`, `kolvo`) VALUES(?, ?, ?, ?)", array(time(), $_POST['pages_id'], $user_id, $_POST['kolvo']));
2023-03-11 21:03:29 +05:00
//Суммируем содержимое корзины и выводим в js
$summ = 0;
2023-08-28 22:47:07 +05:00
$cart = \DB::getAll("SELECT `tovar_id`, `kolvo` FROM `cart` WHERE `user_id`=?", $user_id);
for ($i = 0; $i < count($cart); $i++) {
$cena = \DB::getValue("SELECT `cena` FROM `tovar_price_history` WHERE `tovar_id`=? AND `status`=1", $cart[$i]['tovar_id']);
2023-03-11 21:03:29 +05:00
$m = $cena * $cart[$i]['kolvo'];
$summ = $summ + $m;
}
return $summ;
2023-08-28 22:47:07 +05:00
}
/* ----------------------------------------------------------------------
07.03.2023
Делаем превьюшку
---------------------------------------------------------------------- */
static function imgPreview($src, $dst, $w = 800, $h = 600)
{
$tmp = self::genpassword(10);
exec("convert -define jpeg:size=640x480 " . $src . " -thumbnail '800x600>' -background white -gravity center -extent 800x600 " . $dst);
}
/* ----------------------------------------------------------------------
17.03.2023
Получаем получаем последню цену
---------------------------------------------------------------------- */
static function GetLostPrice($tovar_id)
{
return \DB::getValue("SELECT `cena` FROM `tovar_price_history` WHERE `tovar_id`=? AND `status`=1 ORDER BY `t` DESC LIMIT 1", $tovar_id);
}
/* ----------------------------------------------------------------------
06.07.2023
Поиск текста по строке
---------------------------------------------------------------------- */
static function findtxt($txt, $find)
{
$r = (stripos($txt, $find) === false) ? 0 : 1;
/*
$pos1 = stripos($txt, $find);
if ($pos1 === false) return 0;
else
return 1;*/
return $r;
}
/* ----------------------------------------------------------------------
08.07.2023
Уникализирует массив, документация:
https://snipp.ru/php/array-unique-multi
---------------------------------------------------------------------- */
static function array_unique_key($array, $key)
{
$tmp = $key_array = array();
$i = 0;
foreach ($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$tmp[$i] = $val;
}
$i++;
}
return $tmp;
}
/* ----------------------------------------------------------------------
26.08.2023
Загружаем фотки в таблицу img
---------------------------------------------------------------------- */
static function upload_img($content_type, $content_id, $clear = 0)
{
@mkdir('img/' . $_SERVER['SERVER_NAME'] . '/' . $content_type, 0700);
@mkdir('img/' . $_SERVER['SERVER_NAME'] . '/' . $content_type . '/' . $content_id, 0700);
if ($_FILES['file']['tmp_name']) {
if (preg_match('/[.](jpg)|(jpeg)|(JPG)|(JPEG)$/', $_FILES['file']['name'])) {
$img_name = self::genpassword(30);
$source = $_FILES['file']['tmp_name'];
$target_original = 'img/' . $_SERVER['SERVER_NAME'] . '/' . $content_type . '/' . $content_id . '/' . $img_name . '.jpg';
copy($source, $target_original);
\DB::add("INSERT INTO `img` (`filename`, `content_type`, `content_id`) VALUES (?, ?, ?)", array($img_name, $content_type, $content_id));
if ($clear == 1) {
//удаляем мусор
$hlam = \DB::getAll("SELECT * FROM `img` WHERE `content_type`=? AND `content_id`=? AND `filename`<>?", array($content_type, $content_id, $img_name));
for ($i = 0; $i < count($hlam); $i++)
unlink('img/' . $_SERVER['SERVER_NAME'] . '/' . $content_type .'/' . $content_id . '/' . $hlam[$i]['filename'] . '.jpg');
\DB::set("DELETE FROM `img` WHERE `content_type`=? AND `content_id`=? AND `filename`<>?", array($content_type, $content_id, $img_name));
}
$res['img'] = $img_name;
echo \json::to_j($res);
}
}
}
2023-07-12 20:02:20 +05:00
}
?>