Skip to content

Instantly share code, notes, and snippets.

@serrrgggeee
Created November 7, 2017 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serrrgggeee/11478fc881ec5de8d5b3bfb37e35d120 to your computer and use it in GitHub Desktop.
Save serrrgggeee/11478fc881ec5de8d5b3bfb37e35d120 to your computer and use it in GitHub Desktop.
<?php
namespace App\Classes;
use Illuminate\Http\Request;
use Auth;
use File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Mail;
use Session;
use App\Modules\Admin\Models\Modules;
use App\Modules\Admin\Models\Right;
use App\Classes\DynamicModel;
class Base
{
public function __construct(Request $request)
{
// parent::__construct();
$this->request = $request->all();
$this->requests = $request;
$this->dynamic = new DynamicModel();
}
public static $partnersURI = [
"/"
];
// авторизованный пользователь
public static $user;
//авторизация пользователя, true или false
public static $authenticate;
/**
* инициация авторизированного пользователя, будет доступен везде в Base::$user
*/
static public function init()
{
self::$user = Auth::user();
self::$authenticate = Auth::check();
}
static $month = [
'01' => 'Январь',
'02' => 'Февраль',
'03' => 'Март',
'04' => 'Апрель',
'05' => 'Май',
'06' => 'Июнь',
'07' => 'Июль',
'08' => 'Август',
'09' => 'Сентябрь',
'10' => 'Октябрь',
'11' => 'Ноябрь',
'12' => 'Декабрь'
];
/**
* редирект назад с сообщением об ошибке
* @param $message - сообщение об ошике
* @return mixed
*/
public static function wrong($message)
{
Session::flash('error', $message);
return redirect()->back();
}
/**
* редирект назад с сообщением
* @param $message - сообщение
* @return mixed
*/
public static function back($message)
{
Session::flash('info', $message);
return redirect()->back();
}
/**
* редирект с сообщением
* @param $url - путь редиректа
* @param $message - сообщение
* @return mixed
*/
public static function redirect($url, $message)
{
Session::flash('info', $message);
return redirect($url);
}
/**
* формируем склонения
* @param $number - число, для которого формируем
* @param $after - массив склонений, например ['день','дня','дней']
* @return string - возвращаем склонение
*/
public static function plural($number, $after)
{
$cases = array(2, 0, 1, 1, 1, 2);
return $number . ' ' . $after[($number % 100 > 4 && $number % 100 < 20) ? 2 : $cases[min($number % 10, 5)]];
}
/**
* замена порядкового номера массива на значение из массива
* @param $name
* @param $arr
* @return array
*/
public static function revertToKey($name, $arr)
{
$nevArr = [];
foreach ($arr as $v) {
$nevArr[$v[$name]] = $v;
}
return $nevArr;
}
/**
* создаёт массив значений
* @param $name
* @param $arr
* @return array
*/
public static function getArrayVal($name, $arr)
{
$nevArr = [];
foreach ($arr as $v) {
$nevArr[] = $v[$name];
}
return $nevArr;
}
/**
* модули|модуль и сразу присваиваем права
* @param $keySearch - ключ
* @param $name - с чем сверять
* @param $list - игнорировать parent и оставить массив одномерным
* @return mixed
* admin - если тип юзера (admin) то права будут полные, всегда
* r - просмотр
* x - редактирование
* w - добавление
* d - удаление
*/
public static function getModuleByPath($name_module) {
$path = 'Modules/'.ucfirst($name_module).'/migrate.json';
$path = app_path($path);
$module_param = json_decode(file_get_contents($path), true);
return $module_param;
}
public static function getModule($keySearch = "link_module", $name = null, $list = false)
{
$name = substr($name, 0, -1);
$module = self::getModuleByPath($name);
if(Auth::user()->usertype == 'admin')
{
$module = array_merge($module, ['r' => 1, 'x' => 1, 'w' => 1, 'd' => 1]);
$m = explode('=>', $module['name_module']);
if(isset($m[1]) && !$list) {
$module['name_module'] = $m[1];
$module['m'][$module['parent']][] = $v; //спросить
unset($module);
} else {
$module['k'] = trim($m[0]);
}
if(!$module['active']) unset($module[$key]);
} else {
foreach($module as $key => $v) {
// print_r(Auth::user()->id);
$right = DynamicModel::t('right')
->select('id_menu','r', 'x', 'w', 'd')
->where('id_user', 3)
->whereIn('id_menu', array($v['id']))
->groupBy('id')
->get()
->toArray();
$right = Base::revertToKey("id_menu", $right);
if(!isset($module[$key][$keySearch])) {
continue;
}
if($name === $module[$key][$keySearch] || !$name) {
if(Auth::user()->usertype == 'admin')
{
$module[$key] = array_merge($v, ['r' => 1, 'x' => 1, 'w' => 1, 'd' => 1]);
} else {
if(!isset($right[$v['id']])) {
$module[$key] = array_merge($v, ['r' => 0, 'x' => 0, 'w' => 0, 'd' => 0]);
} else {
$module[$key] = array_merge($v, $right[$v['id']]);
}
}
$m = explode('=>', $v['name_module']);
if(isset($m[1]) && !$name && !$list) {
$module[$key]['name_module'] = $m[1];
$module['m']['order'] = 0;
$module['m'][$v['parent']][] = $module[$key];
unset($module[$key]);
} else {
$module[$key]['k'] = trim($m[0]);
}
} else {
unset($module[$key]);
}
if(!$v['active']) unset($module[$key]);
}
$module_m = [];
if(!$name && !$list) {
$module_m = isset($module['m']) ? $module['m'] : [];
unset($module['m']);
}
// sorting to order
usort($module, function($a, $b){
return $a['order'] <=> $b['order'];
});
if(!$name && !$list){
$module = array_merge($module, ['m' => $module_m]);
}
}
return $module;
}
public static function getModules($keySearch = "link_module", $list = false)
{
// $module = config('admin.module');
$modules = array(self::getModuleByPath('Blog'), self::getModuleByPath('Content'), self::getModuleByPath('Admin'));
if(Auth::user()->usertype == 'admin')
{
foreach($modules as $key => $v) {
if(!isset($modules[$key][$keySearch])) {
continue;
}
$modules[$key] = array_merge($v, ['r' => 1, 'x' => 1, 'w' => 1, 'd' => 1]);
$m = explode('=>', $v['name_module']);
if(isset($m[1]) && !$name && !$list) {
$v['name_module'] = $m[1];
$modules['m'][$v['parent']][] = $v; //спросить
unset($modules[$key]);
} else {
$modules[$key]['k'] = trim($m[0]);
}
if(!$v['active']) unset($modules[$key]);
}
} else {
foreach($modules as $key => $v) {
// print_r(Auth::user()->id);
$right = DynamicModel::t('right')
->select('id_menu','r', 'x', 'w', 'd')
->where('id_user', 3)
->whereIn('id_menu', array($v['id']))
->groupBy('id')
->get()
->toArray();
$right = Base::revertToKey("id_menu", $right);
if(!isset($modules[$key][$keySearch])) {
continue;
}
if(!isset($right[$v['id']])) {
$modules[$key] = array_merge($v, ['r' => 0, 'x' => 0, 'w' => 0, 'd' => 0]);
} else {
$modules[$key] = array_merge($v, $right[$v['id']]);
}
$m = explode('=>', $v['name_module']);
if(isset($m[1]) && !$name && !$list) {
$modules[$key]['name_module'] = $m[1];
$modules['m']['order'] = 0;
$modules['m'][$v['parent']][] = $modules[$key];
unset($modules[$key]);
} else {
$modules[$key]['k'] = trim($m[0]);
}
if(!$v['active']) unset($modules[$key]);
}
$module_m = [];
if(!$list) {
$module_m = isset($modules['m']) ? $modules['m'] : [];
unset($modules['m']);
}
// sorting to order
usort($modules, function($a, $b){
return $a['order'] <=> $b['order'];
});
if(!$list){
$modules = array_merge($modules, ['m' => $module_m]);
}
}
return $modules;
}
/**
* Отправляет письмо
* @param $layout - шаблон письма
* @param $user - модель пользователя
* @param $password - пароль пользователя
*/
public static function mail($layout, $user, $password)
{
Mail::send('emails.' . $layout, ['user' => $user, 'password' => $password], function ($m) use ($user) {
$m->from('igorian.ru@mail.ru', 'Служба техподдержки');
$m->to($user->email, $user->name)->subject('Создание аккаунта');
});
}
/**
* логирование внутренних ошибок
* $err - ошибка, класс Exception
* @param \Exception $err
*/
public static function logError(\Exception $err)
{
$file = '../storage/logs/system-error.log';
error_log('Date: ' . date('Y-m-d H:m:s', time()) . "\n", 3, $file);
error_log('Error message: ' . $err->getMessage() . "\n", 3, $file);
error_log('File: ' . $err->getFile() . "\n", 3, $file);
error_log('Line: ' . $err->getLine() . "\n\n", 3, $file);
}
/**
* @param \Exception $err
* @return \Illuminate\View\View
*/
public static function errorPage(\Exception $err)
{
Log::error('Error: ' . $err->getMessage());
Log::error('File: ' . $err->getFile() . ' at line ' . $err->getLine());
return self::view("admin::dashboard.index");
}
/**
* формируем вьюху, с обязательными параметрами
* @param $url - путь вьюхи
* @param array $args - аргументы
* @param $url
* @param array $args
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public static function view($url, $args = [])
{
if(Auth::user())
{
$args['segment3'] = \Request::segment(3);
$args['left_menu'] = Base::getModules();
}
$args['version'] = '4.2.0';
return view($url, $args);
}
/**
* is JSON
* @param $string
* @return bool
*/
static function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
/**
* формируем вьюху, с обязательными параметрами
* @param $url - путь вьюхи
* @param array $args - аргументы
* @param $url
* @param array $args
* @param string $menu_mame
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function view_s($url, $args = [], $menu_mame = 'menu')
{
$args['menu'] = $this->get_cat($menu_mame, ['active' => 1]);
// $args['menu'] = $this->getMenu($menu_mame, ['active' => 1]);
/**/
// при использовании языков идёт смещение сегментов урла
if(\App::getLocale() == $this->requests->segment(1)) {
$segment1 = $this->requests->segment(2);
$segment2 = $this->requests->segment(3);
$segment3 = $this->requests->segment(4);
} else {
$segment1 = $this->requests->segment(1);
$segment2 = $this->requests->segment(2);
$segment3 = $this->requests->segment(3);
}
if($segment3 && $segment1 != 'm') {
$args['data'] = $this->dynamic->t('str')->where(['active' => 1, 'cat' => $segment3])->get()->toArray();
} else {
if(isset($args['field']))
{
if($segment2 == '') {
$text = htmlspecialchars(urldecode($segment1));
} else {
$text = htmlspecialchars(urldecode($segment2));
}
if($segment1 == 'm' && $segment3) $text = htmlspecialchars(urldecode($segment3));
$menu = $this->dynamic->t($menu_mame)->where(['active' => 1, 'translation' => $text])->first();
$args['data'] = $this
->dynamic
->t('str')
->where(['active' => 1, $args['field'] => $text])
->get()
->toArray();
if(empty($args['data'])) $args['data'][0] = $menu;
} else {
if($segment2) {
$menu = $this->dynamic->t($menu_mame)->where(['active' => 1, 'id' => $segment2])->first();
$args['data'] = $this
->dynamic
->t('str')
->where(['active' => 1, 'cat' => $segment2])
->get()
->toArray();
if(empty($args['data'])) {
$args['data'][0] = $menu;
}
} else {
$menu = $this->dynamic->t($menu_mame)->where(['active' => 1, 'translation' => $segment1])->first();
if(!empty($menu)) {
$args['data'] = $this
->dynamic
->t('str')
->where(['active' => 1, 'cat' => $menu->id])
->get()
->toArray();
}
if(empty($args['data'])) {
$args['data'][0] = $menu;
}
}
}
}
if(!empty($args['data']))
{
if($this->is_json($args['data'][0]['title'])) {
$args['meta']['title'] = json_decode($args['data'][0]['title'], true)[\App::getLocale()] ?? '';
$args['meta']['description'] = json_decode($args['data'][0]['description'], true)[\App::getLocale()] ?? '';
$args['meta']['keywords'] = json_decode($args['data'][0]['keywords'], true)[\App::getLocale()] ?? '';
} else {
$args['meta']['title'] = $args['data'][0]['title'];
$args['meta']['description'] = $args['data'][0]['description'];
$args['meta']['keywords'] = $args['data'][0]['keywords'];
}
}
if(isset($args['meta'])) {
if(!$segment1)
$segment1 = 'main';
$dat = $this->dynamic->t('seo')->where(['name' => $segment1])->get()->toArray();
if(!empty($dat))
{
$args['meta']['title'] = $dat[0]['title'];
$args['meta']['description'] = $dat[0]['description'];
$args['meta']['keywords'] = $dat[0]['keywords'];
}
}
$param = $this->dynamic->t('params')->select('params.*', 'little_description as key')->get();
foreach ($param as $key => $p )
$args['params'][$p->name] = $p->toArray();
if(isset($args['meta_c']))
$args['meta'] = $args['meta_c'];
return view($url, $args);
}
/**
* @param $message
* @return \Symfony\Component\HttpFoundation\Response
*/
public static function returnJSON($message)
{
return response()->json(['message' => $message]);
}
/**
* @param $arr
* @param int $cat
* @param int $i
* @param int $w
* @param $s
* @param string $menu
* @return string
*/
public function view_cat($arr,$cat = 0, $i = 0, $w = 0, $s, $menu = '')
{
if(empty($arr[$cat])) {
return $menu;
}
if($cat != 0) {
$r = 'display:';
} else {
$r = '';
}
if(isset($arr[$cat][$i]['cat'])) {
$f = $arr[$cat][$i]['cat'];
} else {
$f = '';
}
if($w == 1)
{
echo '<ul class=" top-menu-s">';
}
//перебираем в цикле массив и выводим на экран
for($i = 0; $i < count($arr[$cat]);$i++)
{
$arr[$cat][$i]['an_link'] = explode('?v=off', $arr[$cat][$i]['an_link'])[0];
if($arr[$cat][$i]['cat'] > 0 || $arr[$cat][$i]['an_link'] == $s)
{
if($arr[$cat][$i]['an_link'] != $s)
{
if($arr[$cat][$i]['sys_cat'] != '')
{
$l = '/'.$s.'/'.$arr[$cat][$i]['sys_cat'].'';
} else {
$l = '/'.$s.'/page/'.$arr[$cat][$i]['id'].'';
}
if($arr[$cat][$i]['an_link'] != '') {
$l = $arr[$cat][$i]['an_link'];
}
if($i == 0) {
$cl = 'first';
} else {
if($i+1 == count($arr[$cat])) {
$cl = 'last';
} else {
$cl = '';
}
}
echo '<li role="presentation"><a href="'.$l.'" class="'.$cl.'">'
.$arr[$cat][$i]['name'].'</a>';
//рекурсия - проверяем нет ли дочерних категорий
$this->view_cat($arr,$arr[$cat][$i]['id'], $i, 1, $s, $menu);
echo '</li>';
} else {
//рекурсия - проверяем нет ли дочерних категорий
$this->view_cat($arr,$arr[$cat][$i]['id'], $i, 0, $s, $menu);
}
}
}
if($w == 1)
{
echo '</ul>';
}
}
public function _menu_site_select($where = [], $array = null, $cat = 0, $parent = 0, $level = 0, $table = 'menus')
{
if(!$array)
$array = $this->dynamic->t($table)->where($where)->get()->toArray();
$l = array('', '---', '-------', '-----------', '--------------', '-----------------', '----------------------');
$return = '';
$left = $l[$level];
foreach ($array as $item) {
if ($cat == $item['id']) {
$t = 'selected';
} else {
$t = '';
}
if (!isset($item['cat']) or $item['cat'] != $parent) continue;
$return .= '<option value="' . $item['id'] . '" ' . $t . '> ' . $left . ' ' . $item['name'] . '</option>';
$return .= $this->_menu_site_select($where, $array, $cat, $item['id'], $level + 1);//вывод вложенных записей
}
return $return . '';
}
function get_cat_c($where, $cat = '', $table = 'menu')
{
$Mod = new DynamicModel();
$array = $Mod->t($table)
->where($where)
->get()->toArray();
if (!$array) {
return NULL;
}
$arr_cat = array();
//В цикле формируем массив
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
//Формируем массив, где ключами являются адишники на родительские категории
if (empty($arr_cat[$row['cat']])) {
$arr_cat[$row['cat']] = array();
}
$arr_cat[$row['cat']][] = $row['id'];
}
$arr = array();
if(isset($arr_cat[$cat]))
{
$arr = array_merge($arr, $arr_cat[$cat]);
for($i = 0; $i < count($arr_cat[$cat]); $i++)
{
if(isset($arr_cat[$cat][$i]))
{
for($ii = 0; $ii < count($arr_cat[$cat][$i]); $ii++)
{
$id = $arr_cat[$cat][$i];
if(isset($arr_cat[$id]))
{
if(isset($arr_cat[$id][$ii]))
{
for($iii = 0; $iii < count($arr_cat[$id][$ii]); $iii++)
{
$id2 = $arr_cat[$id][$ii];
if(isset($arr_cat[$id2]))
{
$arr = array_merge($arr, $arr_cat[$id2]);
} /*else {
$arr = array_push($arr, $arr_cat[$id2][$iii]);
}*/
}
} else {
$arr = array_push($arr, $arr_cat[$id][$ii]);
}
$arr = array_merge($arr, $arr_cat[$id]);
}/* else {
$arr = array_push($arr, $arr_cat[$id]);
}*/
}
} else {
$arr = array_push($arr, $arr_cat[$cat][$i]);
}
}
} else {
$arr = [$cat];
}
return $arr;
}
/**
* проверка/получение прав пользователя
* @param null $table
* @return mixed
*/
public function right($table = null)
{
if($table) {
$segment3 = $table;
} else {
$segment3 = $this->requests->segment(3);
$segment2 = $this->requests->segment(2);
if(!$segment3 || $segment2 == 'settings') {
$segment3 = $segment2;
}
}
return $this->getModule("link_module", $segment3);
}
/**
* проверка/получение прав пользователя
* @param null $table
* @return mixed
*/
public function right_form($table = null)
{
if($table) {
$segment3 = $table;
} else {
$segment3 = $this->requests->segment(4);
$segment2 = $this->requests->segment(2);
if(!$segment3 || $segment2 == 'settings') {
$segment3 = $segment2;
}
}
return $this->getModule("link_module", $segment3);
}
/**
* формируем массив меню для вывода деревом
* @param null $table
* @param array $where
* @param string $order
* @param string $sort
* @return array|null
*/
public function get_cat($table = null, $where = [], $order = 'order', $sort = 'ASC')
{
if(!$table) { $table = 'contents';}
$Mod = new DynamicModel();
try {
$data = $Mod->t($table)->where([])->orderBy($order)->get();
} catch(\Illuminate\Database\QueryException $ex){
// dd($ex->getMessage());
return NULL;
}
if (!$data) {
return NULL;
}
$arr_cat = array();
if (!empty($data)) {
//В цикле формируем массив
for ($i = 0; $i < count($data); $i++) {
$row = $data[$i];
//Формируем массив, где ключами являются адишники на родительские категории
if (empty($arr_cat[$row['cat']])) {
$arr_cat[$row['cat']] = array();
}
$arr_cat[] = $row->toArray();
}
//возвращаем массив
return $data->toArray();
} else {
return [];
}
}
public function get_article($table = null, $where = [], $order = 'order', $sort = 'ASC', $pagination)
{
$m2m = $table."many2manys";
$order = $m2m.'.'.$order;
try {
if($pagination) {
$data = $this->dynamic->t($m2m)->join($table, $m2m.'.article_id', '=', $table.'.id' )->where($where)->orderBy($order)->paginate($pagination);
} else {
$data = $this->dynamic->t($m2m)->join($table, $m2m.'.article_id', '=', $table.'.id' )->where($where)->orderBy($order)->get();
}
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
return NULL;
}
if (!$data) {
return NULL;
}
if (!empty($data)) {
return $data->toArray();
} else {
return [];
}
}
static function module_var($module) {
$data['link_module'] = $module["link_module"];
$data['link'] = '/admin/update/'.$module["link_module"];
return $data;
}
public function get_active_article($cat, $table, $id = 0, $site = null, $pagination = null) {
$where = ['cat_id' => $id, 'cat' => $cat];
$articles_cat = $this->get_article($table, $where, $order = 'order', $sort = 'ASC', $pagination);
$data = [];
$article = [];
if($site) {
return $articles_cat;
} else {
return $data;
}
}
/**
* получение праметров категории модула
* @param $page
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
static function module_type_param($cat, $module) {
return $module[$cat];
}
private function getM2M($table, $cat, $id) {
$where = ['cat_id' => $id, 'cat' => $cat];
$table = $table."many2manys";
return $this->dynamic->t($table)->where($where)->get()->toArray();
}
/**
* проверка прав
* @return bool
*/
public function right_check()
{
$right = $this->right();
if(empty($right)) {
// создане прав
} else {
$seg = $this->requests->segments()[1];
$r = true;
switch ($seg) {
case 'index':
// добавление
if(!$right['r']) {
$r = false;
}
break;
case 'update':
if(isset($this->requests->segments()[3]))
{
// редактирование
if(!$right['x']) {
$r = false;
}
} else {
// добавлени
if(!$right['w']) {
$r = false;
}
}
break;
case 'delete':
// удаление
if(!$right['d']) {
$r = false;
}
break;
default:
$r = true;
}
if(!$r) {
abort(503, 'Недостаточно прав');
} else {
return $r;
}
}
} /**
* проверка прав
* @return bool
*/
public function right_check_form()
{
$right = $this->right_form();
if(empty($right)) {
// создане прав
} else {
$seg = $this->requests->segments()[1];
$r = true;
switch ($seg) {
case 'index':
// добавление
if(!$right['r']) {
$r = false;
}
break;
case 'update':
if(isset($this->requests->segments()[3]))
{
// редактирование
if(!$right['x']) {
$r = false;
}
} else {
// добавлени
if(!$right['w']) {
$r = false;
}
}
break;
case 'delete':
// удаление
if(!$right['d']) {
$r = false;
}
break;
default:
$r = true;
}
if(!$r) {
abort(503, 'Недостаточно прав');
} else {
return $r;
}
}
}
/**
* function for transform to one-dimensional array
* @param $arr
* @return array|bool
*/
public function makeSingleArray($arr)
{
if (!is_array($arr)) return false;
$tmp = array();
$arr = (isset($arr['offer'][0])) ? $arr['offer'] : [$arr['offer']];
foreach ($arr as $val) {
$tmp[] = $this->_makeSingleArray($val, '');
}
return $tmp;
}
public function _makeSingleArray($arr, $key_arr = '')
{
if (!is_array($arr)) return false;
$tmp = array();
$i = 0;
foreach ($arr as $key => $val) {
if (is_array($val) && isset($val[0]) == false) {
$tmp = array_merge($tmp, $this->_makeSingleArray($val, $key));
} else {
$key_arr_p = ($key_arr && !$i) ? '_' . $key_arr : '';
$tmp[$key . $key_arr_p] = $val;
}
$i++;
}
return $tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment