prokat/api/php/core.php
2025-06-16 18:28:08 +05:00

870 lines
38 KiB
PHP
Executable File
Raw Permalink 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
class core
{
public static $settings = '';
public static $token = ''; // str
static function element_to_obj($element)
{
@$obj = array("tag" => @$element->tagName);
foreach (@$element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
} else {
$obj["children"][] = self::element_to_obj($subElement);
}
}
return $obj;
}
static function html_to_obj($html)
{
$dom = new DOMDocument();
// $dom->loadHTML($html);
@$dom->loadHTML(mb_convert_encoding(@$html, 'HTML-ENTITIES', 'UTF-8'));
return self::element_to_obj($dom->documentElement);
}
static function getAllImgJson($content_id, $content_type, $json, $w = IMG_PRV_W, $h = IMG_PRV_H)
{
$m = self::j($json);
$c = count($m);
for ($i = 0; $i < $c; $i++) {
//Проверяем существование в кеше
$f = 'cache/img/' . $m[$i]['filename'] . '-' . $w . '-' . $h . '.webp';
//if (filesize($f) == 0)
// $err = 1;
$img[$i] = (file_exists($f)) ? '/' . $f : '/img2/' . strtolower($m[$i]['tip']) . '-' . $m[$i]['filename'] . '-' . $w . '-' . $h . '-1-tovar-' . $content_id;
}
/*if ($err)
return $err;
else*/
return $img;
}
/* ----------------------------------------------------------------------
17.06.2024
Получаем все картинки
Параметры:
$content_id - ид в таблице content или content_category
$content_type - вид контента tovar, page
$w, $h - размер картинки
Возвращает одномерный массив с результатами
---------------------------------------------------------------------- */
static function getAllImg($content_id, $content_type, $j = '', $w = IMG_PRV_W, $h = IMG_PRV_H)
{
if ($j) {
$filename = self::j($j);
/*for ($i=0; $i<$c; $i++){
[$i]['filename']=$m[$i]['filename'];
}*/
} else {
if (class_exists('DBmysql'))
$filename = \DBmysql::getAll("SELECT `filename` FROM `img` WHERE `site`=? AND `content_id`=? AND `content_type`=?", [$_SERVER['SERVER_NAME'], $content_id, $content_type]);
else
$filename = \DB::getAll("SELECT `filename` FROM `img` WHERE `site`=? AND `content_id`=? AND `content_type`=?", [$_SERVER['SERVER_NAME'], $content_id, $content_type]);
}
$c = count($filename);
for ($i = 0; $i < $c; $i++) {
if (!$filename[$i]['filename']) {
$img[$i] = 'https://static.yurecnt.ru/img/nofoto/no_skin.png';
} else {
$f = 'cache/img/' . $filename[$i]['filename'] . '-' . $w . '-' . $h . '.webp';
$img[$i] = (file_exists($f)) ? '/' . $f : '/img/' . $filename[$i]['filename'] . '-' . $w . '-' . $h . '-1';
if ($content_type == 'tovar' && class_exists('DBmysql')) {
$images[$i]['filename'] = $filename[$i]['filename'];
$images[$i]['tip'] = \DBmysql::getValue("SELECT `tip` FROM `img` WHERE `filename`=? LIMIT 1", $filename[$i]['filename']);
}
}
}
if ($content_type == 'tovar' && class_exists('DBmysql') && !$j)
\DBmysql::set("UPDATE `tovar` SET `images`=? WHERE `id`=?", [self::j($images), $content_id]);
return $img;
}
/* ----------------------------------------------------------------------
17.06.2024
Получаем первую картинку
Параметры:
$content_id - ид в таблице content или content_category
$content_type - вид контента tovar, page
$w, $h - размер картинки
Возвращает либо что картинки нет, путь к файлу кеша картинки или на модуль генерации картинок
---------------------------------------------------------------------- */
static function getFirstImg($content_id, $content_type, $w = IMG_PRV_W, $h = IMG_PRV_H)
{
//костыль
if (class_exists('DBmysql')) {
$filename = \DBmysql::getValue("SELECT `filename` FROM `img` WHERE `site`=? AND `content_id`=? AND `content_type`=? LIMIT 1", [$_SERVER['SERVER_NAME'], $content_id, $content_type]);
} else {
$filename = \DB::getValue("SELECT `filename` FROM `img` WHERE `site`=? AND `content_id`=? AND `content_type`=? LIMIT 1", [$_SERVER['SERVER_NAME'], $content_id, $content_type]);
}
if (!$filename) {
$img = 'https://static.yurecnt.ru/img/nofoto/no_skin.png';
} else {
$f = 'cache/img/' . $filename . '-' . $w . '-' . $h . '.webp';
$img = (file_exists($f)) ? '/' . $f : '/img/' . $filename . '-' . $w . '-' . $h . '-1';
}
return $img;
}
static function getFirstImgJSON($content_id, $content_type, $j, $w = IMG_PRV_W, $h = IMG_PRV_H)
{
$m = self::j($j);
$filename = $m[0]['filename'];
if (!$filename) {
$img = 'https://static.yurecnt.ru/img/nofoto/no_skin.png';
} else {
$f = 'cache/img/' . $filename . '-' . $w . '-' . $h . '.webp';
$img = (file_exists($f)) ? '/' . $f : '/img/' . $filename . '-' . $w . '-' . $h . '-1';
}
return $img;
}
static function getFirstImg2($fm = 'https://static.yurecnt.ru/img/nofoto/no_skin.png', $type = 'jpg', $w = IMG_PRV_W, $h = IMG_PRV_H)
{
$f = 'cache/img/' . $fm . '-' . $w . '-' . $h . '.webp';
$img = (file_exists($f)) ? '/' . $f : '/img/' . $fm . '-' . $w . '-' . $h . '-1';
return $img;
}
/* ----------------------------------------------------------------------
11.06.2024
Динамическая дозагрузка контента
---------------------------------------------------------------------- */
static function dinamicLoadContent($content_type = 'tovar_category', $parent = 0, $limit = 12)
{
$list = ($_SESSION['dostup'] == 'a') ? \DBmysql::getAll("SELECT `id`, `title`, `artikul`, `cena`, `images` FROM `" . $content_type . "` WHERE `category`=? AND `site`=? LIMIT " . $limit, [$parent, $_SERVER['SERVER_NAME']]) : \DBmysql::getAll("SELECT `id`, `title`, `artikul`, `cena`, `images` FROM `" . $content_type . "` WHERE `category`=? AND `status`=1 AND `site`=? LIMIT " . $limit, [$parent, $_SERVER['SERVER_NAME']]);
$c = count($list);
for ($i = 0; $i < $c; $i++)
$list[$i]['img'] = ($list[$i]['images']) ? \core::getFirstImgJSON($list[$i]['id'], 'tovar', $list[$i]['images']) : \core::getFirstImg($list[$i]['id'], 'tovar');
$res['list'] = $list;
// $res['count'] = \DBmysql::getValue("SELECT COUNT(*) FROM `" . $content_type . "` WHERE `category`=? AND `status`=1 AND `site`=? LIMIT " . $limit, [$parent, $_SERVER['SERVER_NAME']]);
return $res;
}
/* ----------------------------------------------------------------------
08.06.2024
Универсальный выбор под-категорий
---------------------------------------------------------------------- */
static function getGetSubCategories($content_type = 'tovar_category', $parent = 0, $limit = 12, $needImg = true, $fixImg = true, $sort = 'title')
{
require 'api/php/get_sub_categories/index.php';
return $categoryList;
}
static function getContentList($limit = 12, $content_type = 'page', $sort = 0, $content_category = 0)
{
/* --------------------------
Функция извлекает контент однотипно для всего движка
Вынимает title, json, reyt, see, t
$sort:
0 - Содержимое категории
1 - Новое
2 - Популярное
3 - Последнее в категории
------------------------------ */
switch ($sort) {
case '0':
$sql = 'SELECT `id`, `title`, `json`, `reyt`, `see`,`time` FROM `content` WHERE `status`=1 AND `content_type`="' . $content_type . '" AND `site`="' . $_SERVER['SERVER_NAME'] . '" AND `category`="' . $content_category . '" ORDER BY `id` LIMIT ' . $limit;
break;
case '1':
$sql = 'SELECT `id`, `title`, `json`, `reyt`, `see`,`time` FROM `content` WHERE `status`=1 AND `content_type`="' . $content_type . '" AND `site`="' . $_SERVER['SERVER_NAME'] . '" ORDER BY `id` DESC LIMIT ' . $limit;
break;
case '2':
$sql = 'SELECT `id`, `title`, `json`, `reyt`, `see`,`time` FROM `content` WHERE `status`=1 AND `content_type`="' . $content_type . '" AND `site`="' . $_SERVER['SERVER_NAME'] . '" ORDER BY `see` DESC LIMIT ' . $limit;
break;
case '3':
$sql = 'SELECT `id`, `title`, `json`, `reyt`, `see`,`time` FROM `content` WHERE `status`=1 AND `content_type`="' . $content_type . '" AND `site`="' . $_SERVER['SERVER_NAME'] . '" AND `category`="' . $content_category . '" ORDER BY `id` DESC LIMIT ' . $limit;
break;
default:
}
// if ($_SERVER['SERVER_NAME']=='yurecnt.ru')
//$content = \DB::getAll($sql);
//else
$content = \DBmysql::getAll($sql);
$count = count($content);
for ($i = 0; $i < $count; $i++) {
$content[$i]['img'] = self::getFirstImg($content[$i]['id'], $content_type);
$content[$i]['massiv'] = \core::j($content[$i]['json']);
}
return $content;
}
static function formatFileSize($size)
{
$a = array("B", "KB", "MB", "GB", "TB", "PB");
$pos = 0;
while ($size >= 1024) {
$size /= 1024;
$pos++;
}
return round($size, 2) . " " . $a[$pos];
}
/* ----------------------------------------------------------------------
30.11.2023
Получаем данные из таблицы content
---------------------------------------------------------------------- */
static function getContent($id, $contentType)
{
//Проверяем, вдруг поиск по алиасу $table=(\core::findtxt($url, '.html')==1) ? 'alias' : 'id';
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (self::findtxt($url, '.html') == 1) {
$res['row'] = \DBmysql::getRow("SELECT * FROM `content` WHERE `json` LIKE '%" . $_GET['id'] . "%' AND `status`=1 AND `site`=? AND `content_type`=? LIMIT 1", [$_SERVER['SERVER_NAME'], $contentType]);
} else {
$res['row'] = \DBmysql::getRow("SELECT * FROM `content` WHERE `id`=? AND `status`=1 AND `site`=? AND `content_type`=? LIMIT 1", [$_GET['id'], $_SERVER['SERVER_NAME'], $contentType]);
}
$res['json'] = self::j($res['row']['json']);
$res['row']['filename'] = \DBmysql::getValue("SELECT `filename` FROM `img` WHERE `content_id`=? AND `content_type`=? AND `site`=? LIMIT 1", [$res['row']['id'], $contentType, $_SERVER['SERVER_NAME']]);
$f = 'cache/img/' . $res['row']['filename'] . '-' . IMG_MAIN_W . '-' . IMG_MAIN_H . '.webp';
if (file_exists($f))
$res['row']['cache'] = '/' . $f;
\DBmysql::set("UPDATE `content` SET `see`=? WHERE `id`=?", [$res['row']['see'] + 1, $id]);
return $res;
}
/* ----------------------------------------------------------------------
30.11.2023
Работаем с json
---------------------------------------------------------------------- */
static function j($a)
{
return (is_array($a)) ? json_encode($a, JSON_UNESCAPED_UNICODE) : json_decode($a, true);
}
/* ----------------------------------------------------------------------
30.11.2023
Запускаем любой фоновый процесс в фоне
---------------------------------------------------------------------- */
static function run($command, $outputFile = '/dev/null')
{
return shell_exec(sprintf('%s > %s 2>&1 & echo $!', $command, $outputFile));
}
/* ----------------------------------------------------------------------
18.11.2023
Берем категории контента
---------------------------------------------------------------------- */
static function getContentCategory($content_type = 'page', $start = 0, $limit = 30, $category = 0)
{
$category = ($category) ? $category : 0;
return \DB::getAll("SELECT * FROM `content_category` WHERE `site`=? AND `content_type`=? AND `category`=? LIMIT ?, ?", [$_SERVER['SERVER_NAME'], $content_type, $category, $start, $limit]);
}
/* ----------------------------------------------------------------------
08.12.2022
Наполняем базу городов, регионов и стран
---------------------------------------------------------------------- */
static function get_geo_api($ip)
{
$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);
return $res;
}
static function geo()
{
$res = self::get_geo_api($_SERVER['REMOTE_ADDR']);
$strana_id = \DB::getValue('SELECT `id` FROM `strana` WHERE `txt` = "' . @$res['country'] . '"');
if (!$strana_id && @$res['country'])
$strana_id = \DB::add("INSERT INTO `strana` (`txt`) VALUES (?)", [$res['country']]);
@$region_id = \DB::getValue("SELECT `id` FROM `region` WHERE `txt` = ? AND `strana_id` = ?", [@$res['regionName'], $strana_id]);
if (!@$region_id && @$res['regionName'])
$region_id = \DB::add("INSERT INTO `region` (`txt`, `strana_id`) VALUES (?, ?)", [$res['regionName'], $strana_id]);
$city_id = \DB::getValue("SELECT `id` FROM `city` WHERE `txt` = ? AND `strana_id` = ? AND `region_id`=?", [@$res['city'], $strana_id, $region_id]);
if (!@$city_id && @$res['city']) {
$city_id = \DB::add("INSERT INTO `city` (`txt`, `strana_id`, `region_id`) VALUES (?, ?, ?)", [$res['city'], $strana_id, $region_id]);
@$_SESSION['city'] = @$city_id;
}
}
static function getAllSettings($mod = 'global')
{
return \json::from_j(\DB::getValue('SELECT `json` FROM `settings` WHERE `mod` = "' . $mod . '" LIMIT 1'));
}
/* ----------------------------------------------------------------------
08.12.2022
Берем настройки модуля/сайта
---------------------------------------------------------------------- */
static function getSettings($set, $mod = 'global', $all = 0)
{
//echo 'SELECT `json` FROM `settings` WHERE `mod` = "' . $mod . '" LIMIT 1';
$txt = \DBmysql::getValue('SELECT `json` FROM `settings` WHERE `mod` = "' . $mod . '" LIMIT 1');
$massiv = self::j($txt);
if ($all == 0)
return $massiv[$set];
else
return $massiv;
}
/* ----------------------------------------------------------------------
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 = self::j(base64_decode($_COOKIE['cookies']));
$users = \DBmysql::getRow('SELECT * FROM `users` WHERE `id` = "' . $res['user_id'] . '" AND `pwd`="' . $res['pwd'] . '" LIMIT 1');
if ($users['dostup']) {
$_SESSION['user_id'] = $res['user_id'];
$_SESSION['dostup'] = $users['dostup'];
}
}
}
/* ----------------------------------------------------------------------
09.12.2022
Получаем данные корзины
Выводим массив, в массиве cart - все содержимое корзины, в summ - итог корзины
---------------------------------------------------------------------- */
static function getCart()
{
$session_id = (@$_SESSION['user_id']) ? @$_SESSION['user_id'] : session_id();
$cart = \DBmysql::getAll("SELECT * FROM `cart` WHERE `user_id`=? AND `order` IS NULL AND `site`=?", [$session_id, $_SERVER['SERVER_NAME']]);
$summ = 0;
$c = count($cart);
//Получаем название товаров и цены
for ($i = 0; $i < $c; $i++) {
$t = \DBmysql::getRow("SELECT `title`, `cena`, `images` FROM `tovar` WHERE `id`=? LIMIT 1", $cart[$i]['tovar_id']);
$cart[$i]['title'] = $t['title'];
$cart[$i]['cena'] = $t['cena'];
$cart[$i]['img'] = \DBmysql::getValue("SELECT `filename` FROM `img` WHERE `content_id`=? LIMIT 1", $cart[$i]['tovar_id']);
$cart[$i]['st'] = $cart[$i]['kolvo'] * $cart[$i]['cena'];
$summ = $summ + $cart[$i]['st'];
}
$result['cart'] = $cart;
$result['summ'] = $summ;
return $result;
}
/* ----------------------------------------------------------------------
20.12.2022
Получаем данные об основной организации пользователя
---------------------------------------------------------------------- */
static function getUserMainOrg($user_id)
{
}
/* ----------------------------------------------------------------------
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;
}
/* ----------------------------------------------------------------------
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') . '/');
}
static function login()
{
$user = \DBmysql::getRow('SELECT `id`, `dostup`, token FROM `users` WHERE `email` = ? AND `pwd`=? LIMIT 1', [$_POST['email'], md5($_POST['pwd'])]);
if ($user['dostup']) {
$_SESSION['dostup'] = $user['dostup'];
$_SESSION['user_id'] = $user['id'];
if (!$user['token'] && !$_SESSION['token']) {
$user['token'] = md5(md5(time()));
// \DB::set("UPDATE `users` SET `token`=? WHERE `id`=?", $user['token']);
}
}
$tri_mes = time() + 31536000;
setcookie('token', $user['token'], $tri_mes, '/', $_SERVER['SERVER_NAME']);
if ($_POST['remember'] == 'on' && $user['dostup']) {
$_SESSION['pwd'] = md5($_POST['pwd']);
$cookies = base64_encode(self::j($_SESSION));
setcookie('cookies', $cookies, $tri_mes, '/', $_SERVER['SERVER_NAME']);
}
self::redirectAfterLogin($user['dostup']);
}
/* ----------------------------------------------------------------------
12.12.2022
Получаем данные о пользователе
---------------------------------------------------------------------- */
static function getUserInfo($id)
{
//echo 'SELECT * FROM `users` WHERE `id` = ' . $id . ' LIMIT 1';
$user = \DBmysql::getAll('SELECT `fio` FROM `users` WHERE `id` = ? LIMIT 1', $id);
return $user;
}
/* ----------------------------------------------------------------------
13.12.2022
Шифровальщик
---------------------------------------------------------------------- */
/*static function crypt ( $String, $act='crypt', $pwd ) {
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;
}*/
/* ----------------------------------------------------------------------
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);
$pass .= $arr[$index];
}
return $pass;
}
/* ----------------------------------------------------------------------
16.05.2024
Генератор токена пользователя - по нему складываем товар в корзину
---------------------------------------------------------------------- */
static function setToken()
{
$token = self::genpassword(40);
if (!$_COOKIE['token']) {
setcookie('token', $token, time() + 31536000, '/', $_SERVER['SERVER_NAME']);
return $token;
} else
return $_COOKIE['token'];
}
/* ----------------------------------------------------------------------
28.12.2022
Получаем мета-теги - для модулей не имеющих свои теги (используется в /main)
---------------------------------------------------------------------- */
static function getMeta($mod, $id = 0)
{
$massiv = \DB::getAll('SELECT * FROM `meta` WHERE `id` = ? AND `mod`=? LIMIT 1', [$id, $mod]);
if (count($massiv) == 0)
\DB::add("INSERT INTO `meta` (`id`, `mod`) VALUES (?, ?)", [$id, $mod]);
$res = $massiv[0];
return $res;
}
/* ----------------------------------------------------------------------
03.01.2023
Хлебные крошки
---------------------------------------------------------------------- */
static function getBreadcrumb($table, $category)
{
$p = $category;
$i = 0;
while ($p != 0) {
$massiv = \DBmysql::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();
//Получаем количество, если есть...
$kolvo = \DB::getValue("SELECT `kolvo` FROM `cart` WHERE `user_id`=? AND `tovar_id`=?", [$user_id, $_POST['pages_id']]);
if ($kolvo) {
$kolvo = $kolvo + $_POST['kolvo'];
\DB::set("UPDATE `cart` SET `kolvo`=? WHERE `user_id`=? AND `tovar_id`=?", [$kolvo, $user_id, $_POST['pages_id']]);
} else
$insert_id = \DB::add("INSERT INTO `cart` (`t`, `tovar_id`, `user_id`, `kolvo`) VALUES(?, ?, ?, ?)", [time(), $_POST['pages_id'], $user_id, $_POST['kolvo']]);
//Суммируем содержимое корзины и выводим в js
$summ = 0;
$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']);
$m = $cena * $cart[$i]['kolvo'];
$summ = $summ + $m;
}
return $summ;
}
/* ----------------------------------------------------------------------
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)
{
return (stripos($txt, $find) === false) ? 0 : 1;
}
/* ----------------------------------------------------------------------
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`, `site`) VALUES (?, ?, ?,?)", [$img_name, $content_type, $content_id, $_SERVER['SERVER_NAME']]);
if ($clear == 1) {
//удаляем мусор
$hlam = \DB::getAll("SELECT * FROM `img` WHERE `content_type`=? AND `content_id`=? AND `filename`<>?", [$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`<>?", [$content_type, $content_id, $img_name]);
}
$res['img'] = $img_name;
echo \json::to_j($res);
}
}
}
/* ----------------------------------------------------------------------
11.09.2023
Выдает хтмл по ссылке
---------------------------------------------------------------------- */
static function get_page($link)
{
$agent = 'Mozilla/5.0 (compatible; YandexBot/3.0)';
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$dir = dirname(__FILE__);
$config['cookie_file'] = $dir . '/cookies/' . md5(@$_SERVER['REMOTE_ADDR']) . '.txt';
curl_setopt($ch, CURLOPT_COOKIEFILE, $config['cookie_file']);
curl_setopt($ch, CURLOPT_COOKIEJAR, $config['cookie_file']);
curl_setopt($ch, CURLOPT_COOKIE, "PMBC=96152e8e9a0168a731539c5e52c6b39a; PHPSESSID=jl0i13pn3157qca807jgp0jqa7; ServerName=WoW+Circle+3.3.5a+x5; serverId=1");
$response_data = curl_exec($ch);
if (curl_errno($ch) > 0) {
echo ('Ошибка curl: ' . curl_error($ch));
}
$http_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($http_code == 200)
$r['html'] = $response_data;
$r['code'] = $http_code;
return $r;
}
static function print_see_to_likes($content_id, $content_type, $user_id)
{
$user_id = ($user_id) ? $user_id : self::checkMe();
$id = \DB::getValue("SELECT `id` FROM `likes` WHERE `user_id`=? AND `content_id`=? AND `content_type`=? AND `tip`=? LIMIT 1", [$user_id, $content_id, $content_type, 'see']);
if (!$id)
\DB::add("INSERT INTO `likes` (`user_id`, `content_id`, `content_type`, `t`, `tip`) VALUES (?, ?, ?, ?, ?)", [$user_id, $content_id, $content_type, time(), 'see']);
}
/* ----------------------------------------------------------------------
17.12.2023
Собираем ключевые слова с яндекс-метрики
---------------------------------------------------------------------- */
static function getKeyWordsFromYAME($counter = '21950635', $token = 'y0_AgAAAAABiU4jAAn8iwAAAADkWpkSbFJu1kVDTGCi5DQIA4h6RaMwKpA')
{
$mod = ($_GET['mod']) ? $_GET['mod'] : 'main';
$id = ($_GET['id']) ? $_GET['id'] : 0;
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; // . $_SERVER['REQUEST_URI']
$params = [
'ids' => $counter,
'metrics' => 'ym:s:visits',
'dimensions' => 'ym:s:searchPhrase',
'date1' => '365daysAgo',
'date2' => 'today',
'filters' => "ym:pv:URL=='" . $url . "'"
];
$ch = curl_init('https://api-metrika.yandex.net/stat/v1/data?' . urldecode(http_build_query($params)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: OAuth ' . $token));
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);
$words = [];
foreach ($res['data'] as $row) {
$words[] = $row['dimensions'][0]['name'];
}
return $words;
}
static function server_parse($socket, $response, $line = __LINE__)
{
global $config;
while (substr($server_response, 3, 1) != ' ') {
if (!($server_response = fgets($socket, 256))) {
if ($config['smtp_debug'])
echo "<p>Проблемы с отправкой почты!</p>$response<br>$line<br>";
return false;
}
}
if (!(substr($server_response, 0, 3) == $response)) {
if ($config['smtp_debug'])
echo "<p>Проблемы с отправкой почты!</p>$response<br>$line<br>";
return false;
}
return true;
}
/* Отправлялка через сторонний смтп */
static function sendemail($mail_to = E_ADMIN_EMAIL, $subject, $message, $headers = '')
{
$subject = mb_convert_encoding($subject, "windows-1251", "utf-8");//iconv('UTF-8', 'Windows-1251', $subject);
$message = mb_convert_encoding($message, "windows-1251", "utf-8");//iconv('UTF-8', 'Windows-1251', $message);
//$message = iconv('utf-8//IGNORE', 'windows-1251//IGNORE', $message);
$SEND = "Date: " . date("D, d M Y H:i:s") . " UT\r\n";
$SEND .= 'Subject: =?' . 'windows-1251' . '?B?' . base64_encode($subject) . "=?=\r\n";
if ($headers)
$SEND .= $headers . "\r\n\r\n";
else {
$SEND .= "Reply-To: " . E_SMTP_USER . "\r\n";
$SEND .= "MIME-Version: 1.0\r\n";
$SEND .= "Content-Type: text/html; charset=\"" . 'windows-1251' . "\"\r\n";
$SEND .= "Content-Transfer-Encoding: 8bit\r\n";
$SEND .= "From: \"" . $_SERVER['SERVER_NAME'] . "\" <" . E_SMTP_USER . ">\r\n";
$SEND .= "To: $mail_to <$mail_to>\r\n";
$SEND .= "X-Priority: 3\r\n\r\n";
}
$SEND .= $message . "\r\n";
if (!$socket = fsockopen(E_SMTP, E_SMTP_PORT, $errno, $errstr, 30)) {
if (E_SMTP_D)
echo $errno . "&lt;br&gt;" . $errstr;
return false;
}
if (!self::server_parse($socket, "220", __LINE__))
return false;
fputs($socket, "HELO " . E_SMTP . "\r\n");
if (!self::server_parse($socket, "250", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не могу отправить HELO!</p>';
fclose($socket);
return false;
}
fputs($socket, "AUTH LOGIN\r\n");
if (!self::server_parse($socket, "334", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не могу найти ответ на запрос авторизаци.</p>';
fclose($socket);
return false;
}
fputs($socket, base64_encode(E_SMTP_USER) . "\r\n");
if (!self::server_parse($socket, "334", __LINE__)) {
if (E_SMTP_D)
echo '<p>Логин авторизации не был принят сервером!</p>';
fclose($socket);
return false;
}
fputs($socket, base64_encode(E_SMTP_PWD) . "\r\n");
if (!self::server_parse($socket, "235", __LINE__)) {
if (E_SMTP_D)
echo '<p>Пароль не был принят сервером как верный! Ошибка авторизации!</p>';
fclose($socket);
return false;
}
fputs($socket, "MAIL FROM: <" . E_SMTP_USER . ">\r\n");
if (!self::server_parse($socket, "250", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не могу отправить комманду MAIL FROM: </p>';
fclose($socket);
return false;
}
fputs($socket, "RCPT TO: <" . $mail_to . ">\r\n");
if (!self::server_parse($socket, "250", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не могу отправить комманду RCPT TO: </p>';
fclose($socket);
return false;
}
fputs($socket, "DATA\r\n");
if (!self::server_parse($socket, "354", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не могу отправить комманду DATA</p>';
fclose($socket);
return false;
}
fputs($socket, $SEND . "\r\n.\r\n");
if (!self::server_parse($socket, "250", __LINE__)) {
if (E_SMTP_D)
echo '<p>Не смог отправить тело письма. Письмо не было отправленно!</p>';
fclose($socket);
return false;
}
fputs($socket, "QUIT\r\n");
fclose($socket);
return TRUE;
}
}
?>