This commit is contained in:
indeferend
2021-05-23 06:26:34 +05:00
commit df825e3d2f
56 changed files with 24076 additions and 0 deletions

9
CLASSES/blog.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
class blog_model
{
}

206
CLASSES/core/LE_FS.php Normal file
View File

@@ -0,0 +1,206 @@
<?php
/** @var \DB $db*/
if(!defined("I")) die;
//работа с файлами
class LE_FS
{
//+++добавить рекурсивное добавление родительских...
public static function create_folder ($path,$permissions=0755)
{
if(!is_dir($path)) mkdir($path, $permissions);
}
public static function clear_folder($path)
{
$path = rtrim($path,"/")."/";
if (!is_dir($path) || !($handle = opendir($path))) return;
while(false !== ($f = readdir($handle)))
{
if($f == "." || $f == "..") continue;
$obj=$path.$f;
if (is_file($obj))
unlink($obj);
elseif (is_dir($obj))
LE_FS::clear_folder($obj);
}
closedir($handle);
}
//рекурсивное копирование папки LE_FS::copy_folder($src, $dest);
public static function copy_folder($src, $dest) {
if (stripos($src,".DS_Store")>0) return false;
if ( is_dir( $src ) ) {
if (!file_exists($dest)) mkdir($dest, 0777, true);
$d = dir( $src );
while ( false !== ( $entry = $d->read() ) ) {
if ( $entry != '.' && $entry != '..' )
LE_FS::copy_folder( "$src/$entry", "$dest/$entry");
}
$d->close();
}
elseif (!file_exists($dest))
{
copy($src, $dest);
echo 'copy file <b>'.$src.'</b> to <b>'.$dest."</b>\n<br>";
}
}
public static function dir_files($dir,$func=false)
{
if (!$dir||empty($dir)||!is_dir($dir)) return 1;
if($func===false) return 2;
$d = dir( $dir );
while ( false !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) continue;
$func($entry);
}
$d->close();
}
//LE_FS::save_from_post($inp=['f_name'=>,'path'=>])
public static function SAVE_POST($inp,$debug=false)
{
$f_name = (isset($inp['f_name'])) ? $inp['f_name'] : 'file';
if (!isset($inp['path']) || !is_dir($inp['path'])) return false;
$inp['path'] = rtrim($inp['path']);
// echo $inp['path'];
if (!isset($_FILES[$f_name])) return false;
$F = $_FILES[$f_name];
// echo_arr($F);
$SAVE_FILE = function($path,$index=false) use (&$F,&$debug)
{
$f_inf=[];
if ($index!==false)
{
if (!isset($F["tmp_name"][$index])) return false;
$f_inf['tmp_name'] = $tmp_name = $F["tmp_name"][$index];
$f_inf['name'] = $file_name = $F["name"][$index];
$f_inf['type'] = $F["type"][$index];
$f_inf['size'] = $F["size"][$index];
}
else
{
if (!isset($F["tmp_name"])) return false;
$f_inf['tmp_name'] = $tmp_name = $F["tmp_name"];
$f_inf['name'] = $file_name = $F["name"];
$f_inf['type'] = $F["type"];
$f_inf['size'] = $F["size"];
}
// echo $tmp_name.BR;
// echo $file_name.BR;
if (!is_uploaded_file($tmp_name)) return false;
$n = LE_FS::GEN_FNAME($file_name, $path);
$out = $path.DS.$n;
if (!move_uploaded_file($tmp_name, $out)) return false;
if (!file_exists($out)) return false;
if($debug!==false) $debug[$n] = $f_inf;
return $n;
};
if (is_array($F['tmp_name']))
{
$cnt = count($F['tmp_name']);
$res = [];
for ($i=0;$i<$cnt;$i++)
{
$_fn = $SAVE_FILE($inp['path'],$i);
if ($_fn!==false) $res[] = $_fn;
}
}
else
{
return $SAVE_FILE($inp['path']);
}
$cnt = count($res);
if (!$cnt>0) return false;
if ($cnt===1) return $res[0];
return $res;
}
public static function GEN_FNAME($inp_name = false, $path = false, $prefix=false)
{
$ext = ($inp_name) ? '.'.pathinfo ($inp_name,PATHINFO_EXTENSION) : ''; //extension .jpg
//file name alphabet
$fn_alphabet = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D',
'E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U','V','W','X','Y','Z','_','-'
];
$microtime = microtime(1);
$create_time = 1540388275;
$diff_time = Ceil($microtime*10000)-($create_time*10000);
$new = int2alphabet($fn_alphabet,$diff_time);
if ($prefix!==false) $new = $prefix.$new;
//проверка существования
if ($path && is_dir($path))
{
$part = rtrim($path,DS);
$i=1;
while(is_file($path . DS . $new.$ext))
{
if ($i>100) exit("problem gen file name!!!");
$new.=$fn_alphabet[rand(0,27)];
$i++;
}
}
return $new.$ext;
}
public static function Apply2Files($path,&$func,$recouse=0)
{
$path = rtrim($path,"/\\").DS;
if (!is_dir($path) || !($handle = opendir($path))) return;
while(false !== ($f = readdir($handle)))
{
if($f == "." || $f == "..") continue;
$obj=$path.$f;
if (is_file($obj))
$func($obj);
elseif (is_dir($obj) && $recouse)
LE_FS::Apply2Files($obj,$func,$recouse);
}
closedir($handle);
}
}

View File

@@ -0,0 +1,145 @@
<?php
abstract class LE_MOD_CONTROLLER
{
public $aliases, $params_url, $model,$cont_type;
function __construct($params_url=false,&$model=false)
{
$this->params_url = $params_url;
$this->model = &$model;
}
//точка входа
public function start()
{
//ajax methods
if (isset($_POST['ajax'])) return $this->ajax();
if (LE::$QUERY_DATA_TYPE=='json') return $this->json();
list($mod,$params) = $this->router();
if (!empty($mod) && isset($this->aliases[$mod])) $mod = $this->aliases[$mod];
$mod = "_inp_".$mod;
if ($mod=="_inp_" || !method_exists($this,$mod)) return $this->_inp_default($params);
return $this->$mod($params);
}
protected function router()
{
//echo_arr($this->params_url);
$url = $this->params_url[3];
$url = PRE::DOWN($url);
preg_match('!([^:]*)[:]?(.*)!ui',$url,$out);
//echo_arr($out);
return [$out[1],$out[2]];
}
protected function ajax()
{
//out without template
if (property_exists(LE::$TPL,'clear')) LE::$TPL->clear=1;
$mod = trim(arr_v($_POST,'mod',''));
if (empty($mod)) return false;
$mod = "_ajx_".$mod;
$data=false;
if (isset($_POST['data']))
{
$data = $_POST['data'];
if (!is_array($data) && !empty($data)) $data = json_decode($data,1);
}
if (!method_exists($this,$mod)) return false;
$res = $this->$mod($data);
//возвращать массив ответа как есть, не оборачивая в data
if (isset($res['as_is']) && $res['as_is'])
{
unset($res['as_id']);
$out = $res;
}
elseif ($res===false)
{
$out = ['success'=>0]; //error
}
else
{
$out = ['success'=>1];
$out['data'] = $res;
}
return json_encode($out);
}
protected function _inp_default($inp)
{
return false;
}
protected function json()
{
$postData = file_get_contents('php://input');
$data = json_decode($postData,1);
if (property_exists(LE::$TPL,'clear')) LE::$TPL->clear=1;
$method = trim(arr_v($data,'method',''));
if (empty($method)) return false;
$method = "_ajx_".$method;
if (!method_exists($this,$method)) return false;
unset($data['method']);
$res = $this->$method($data);
//возвращать массив ответа как есть, не оборачивая в data
if (isset($res['as_is']) && $res['as_is'])
{
unset($res['as_id']);
$out = $res;
}
elseif ($res===false)
{
$out = ['success'=>0]; //error
}
else
{
$out = ['success'=>1];
$out['data'] = $res;
}
return json_encode($out);
}
//301 redirect
public function move2new($url)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$url);
exit();
}
}

View File

@@ -0,0 +1,71 @@
<?php
class LE_MOD_LOAD {
public $m1=false,$m2=false,$space_list=[],$mod_aliases=[];
public $init_path=false,$mod_path=false,$url;
function __construct($autorun=1)
{
$this->m1=SYSDIR."MODULES".DS;
$this->m2=APPDIR."MODULES".DS;
$this->space_list = SYSCONF::$SPACE_LIST;
$this->mod_aliases = SYSCONF::$MOD_ALIASES;
if ($autorun) $this->parse_url();
}
public function parse_url()
{
$query = LE_REQUEST::url2arr()['query_clr'];
$spaces_str = implode('|',array_keys($this->space_list));
preg_match('!^/('.$spaces_str.')?/?([^/?]*)/?(.*?)$!simu', $query,$res);
$this->url = $res;
$space_in_q = $res[1];
$mod_in_q = $res[2];
$space=SYSCONF::$DEFAULT_MODSPACE; //default
if (!empty($space_in_q))
{
$space = $this->search_key($this->space_list,$space_in_q);
if ($space===false) return false;
}
if ($this->select_path($space)===false) return false;
$mod=arr_v(SYSCONF::$DEFAULT_MODULE,$space,false); //default
if (!empty($mod_in_q))
{
$mod_rr=false;
if (isset($this->mod_aliases[$space]))
$mod_rr = $this->search_key($this->mod_aliases[$space],$mod_in_q);
$mod = ($mod_rr) ? $mod_rr : $mod_in_q;
}
$this->init_path = $this->select_path($space,"__space_init.php");
$this->mod_path = $this->select_path($space,$mod.".php");
}
public function select_path($space,$path="")
{
$app_path = $this->m2.$space.DS.$path;
$sys_path = $this->m1.$space.DS.$path;
if (file_exists($app_path)) return $app_path;
if (file_exists($sys_path)) return $sys_path;
return false;
}
public function search_key($arr,$key)
{
foreach ($arr as $tpl => $val)
if(preg_match('!^('.$tpl.')$!simu', $key)) return $val;
return false;
}
}

278
CLASSES/core/LE_MYSQL.php Normal file
View File

@@ -0,0 +1,278 @@
<?php
class LE_MYSQL
{
public $l,$cnt = 0,$debug=0,$echo_sql=0;
private $cnf = [];
function __construct(&$cnf)
{
$this->cnf = &$cnf;
if (defined("DEBUG") && DEBUG==1) $this->debug=1;
$this->connect($cnf);
}
//exit and echo error
protected function err($txt)
{
http_response_code(503);
exit($txt);
}
/*****************************
| private helpers functions |
*****************************/
protected function create_connect()
{
if (isset($this->cnf['socket']) && !empty($this->cnf['socket']))
return new mysqli(NULL, $this->cnf['user'], $this->cnf['pass'], $this->cnf['db_name'], NULL,
$this->cnf['socket']);
return new mysqli($this->cnf['host'], $this->cnf['user'], $this->cnf['pass'], $this->cnf['db_name']);
}
public function connect()
{
$this->l = $this->create_connect();
if ($this->l->connect_errno) $this->err("ERROR CONNECT DB");
$this->sess_conf();
}
private function sess_conf()
{
$this->query("set names utf8");
$this->query("SET @@session.time_zone = '+00:00'");
}
public function check_conn ($debug=0)
{
if ($this->l->ping()!==false) return;
//проверим еще раз не переподключился ли он автоматом
usleep(500);
if ($this->l->ping()===false) $this->connect();
}
/*****************************
| query & anwer functions |
*****************************/
public function query($s, $buffer = true, $o = [])
{
$this->cnt++; //счетчик запросов
$buf = ($buffer) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT;
$type = (isset($o['type'])) ? $o['type'] : $this->detect($s);
if ($this->echo_sql) echo $s.BR;
$res = $this->l->query($s, $buf);
$e = ($this->l->error);
if (!empty($e)) $this->err(($this->c['debug'] ? $e . ' <br>(' . $s . ')' : 'ERR QUERY!!!'));
unset($e, $buf);
return $this->answer($res, $type, $o);
}
private function detect($s) {
if ((stripos($s, 'select', 0) !== false)) return 'S';
if ((stripos($s, 'SHOW', 0) !== false)) return 'S';
if ((stripos($s, 'insert', 0) !== false)) return 'I';
if ((stripos($s, 'update', 0) !== false)) return 'U';
if ((stripos($s, 'delete', 0) !== false)) return 'D';
if ((stripos($s, 'truncate', 0) !== false)) return 'T';
}
private function answer(&$r, $t_, $o) {
$t = &$this;
$l = &$this->l;
switch ($t_) {
case 'S':
if ((isset($o['row']) && $o['row']) || (isset($o['val']) && $o['val']))
{
$r_ = $this->get_row($r);
$r->free_result();
if (isset($o['val']) && $o['val']) return $r_[trim($o['val'])];
return $r_;
}
return $r;
break;
case 'I':
return $l->insert_id;
break;
case 'U';
case 'T';
case 'D';
return $l->affected_rows;
break;
}
return false;
}
public function get_row(&$r)
{
return ($r) ? mysqli_fetch_assoc($r) : FALSE;
}
/*****************************
| query prepare functions |
*****************************/
public function prepare($s)
{
return $this->l->real_escape_string($s);
}
public function arr2in($ids,$str=false)
{
if ($str) array_map(function($id){return "'".$id."'";},$ids);
$ids = (is_array($ids)) ? implode(',',$ids) : $ids;
return $this->prepare($ids);
}
public function gen_set($arr)
{
$arr_ = [];
if (count($arr)) {
foreach ($arr as $k => &$v) {
$arr_[] = "`" . $k . "`='" . (($v === '###') ? '' : $this->prepare($v)) . "'";
}
}
if (!count($arr_) > 0) {
return false;
}
unset($arr);
return implode(', ', $arr_);
}
/**********************
| result functions |
**********************/
public function count(&$res)
{
if (!$res || gettype($res)!=="object") return false;
return mysqli_num_rows ($res);
}
public function cnt(&$res) {return $this->count($res);}
public function res2arr($res = 0,$key=false,$shift_reg=false)
{
$res_arr = [];
if($key===false)
while($r = $this->get_row($res)) $res_arr[] = $r;
else
while($r = $this->get_row($res))
{
$_key = ($shift_reg) ? PRE::SHIFT($r[$key],$shift_reg) : $r[$key];
$res_arr[$_key] = $r;
}
return $res_arr;
}
public function found_rows()
{
return $this->query("SELECT FOUND_ROWS() as `cnt`", false, ['val' => 'cnt']);
}
/****************
QUERY GENERATORS
****************/
public function INS($table, $val_arr)
{
$table = $this->prepare($table);
$set_str = $this->gen_set($val_arr);
$sql = 'INSERT INTO `' . $table . '` SET ' . $set_str;
return $this->query($sql,0,['type'=>'I']);
}
public function UPD($table, $val_arr, $id, $idf = 'id',$str_key=false)
{
if (empty($id)) $this->err("ERR DB UPD");
$table = $this->prepare($table);
$set_str = $this->gen_set($val_arr);
$id_field = $this->prepare($idf);
$in_list = $this->arr2in($id,$str_key);
$sql = 'UPDATE `' . $table . '` SET ' . $set_str . ' WHERE `' . $id_field . '` IN (' . $in_list . ')';
return $this->query($sql,0,['type'=>'U']);
}
public function DEL($table, $id, $idf = "id",$str=false)
{
if (is_array($id) && !count($id)) return false; //нечего удалять, если ничего не передали
if (!is_array($id)) $id = [$id];
$table = $this->prepare($table);
$id_field = $this->prepare($idf);
$in_list = $this->arr2in($id);
$sql = 'DELETE FROM `' . $table . '` WHERE `' . $id_field . '` IN(' . $in_list.')';
return $this->query($sql,0,['type'=>'D']);
}
//ins or upd return index
public function SAVE($t,$v,$idf="id")
{
if (!isset($v[$idf]) || $v[$idf]==0) return $this->INS($t,$v);
$id = $v[$idf]; unset($v[$idf]);
//upd
if ($id>0 && count($v)>0) $this->UPD($t,$v,$id,$idf);
//delete
if ($id<0) $this->DEL($t,($id*-1),$idf);
return $id;
}
/*****************
* custom queries *
*****************/
public function query_arr($sql,$key=false,$shift_reg=0)
{
$res = $this->query($sql,0,['type'=>'S']);
$rez = $this->res2arr($res,$key,$shift_reg);
$res->free();
return $rez;
}
public function query_keyval($sql,$k=false,$v=false)
{
$k = trim($this->prepare($k));
$v = trim($this->prepare($v));
$res = $this->query($sql,0,['type'=>'S']);
$res_arr = [];
while($r = $this->get_row($res)) $res_arr[$r[$k]] = $r[$v];
return $res_arr;
}
public function query_single($s) {
return $this->query($s, false, ['row' => true]);
}
public function query_val($s,$v)
{
return $this->query($s, false, ['val' => $v]);
}
}

114
CLASSES/core/LE_REQUEST.php Normal file
View File

@@ -0,0 +1,114 @@
<?php
class LE_REQUEST {
public static function url2arr($s=false, $use_forwarded_host = false)
{
if ($s===false) $s = $_SERVER;
$res = [];
$ssl = (isset($s['HTTPS']) && $s['HTTPS'] == 'on' );
$port = (isset($s['SERVER_PORT'])) ? $s['SERVER_PORT'] : '80';
//хак для ssl nginx->apache
/*
if ((!$ssl) && function_exists('apache_request_headers'))
{
$h = apache_request_headers();
if (is_array($h) && isset($h['Nginx-Https']) && $h['Nginx-Https']=='on')
{
$ssl=true; $port=443;
}
}
*/
$protocol = strtolower($s['SERVER_PROTOCOL']);
$scheme = substr( $protocol, 0, strpos( $protocol, '/' ) ) . ( ( $ssl ) ? 's' : '' );
$standart_port = ((!$ssl && $port=='80') || ($ssl && $port=='443'));
$host="locahost";
if ($use_forwarded_host && isset( $s['HTTP_X_FORWARDED_HOST'] ))
$host = $s['HTTP_X_FORWARDED_HOST'];
elseif (isset( $s['HTTP_HOST']))
$host = $s['HTTP_HOST'];
elseif (isset( $s['SERVER_NAME']))
$host = $s['SERVER_NAME'];
$host_full = ($standart_port) ? $host : ($host.":".$port);
$query= isset($s['REQUEST_URI']) ? $s['REQUEST_URI'] : '';
$query_clr = preg_replace('!\?.*?$!','',$query);
return compact('ssl','port','scheme','standart_port','host','host_full','query','query_clr','protocol');
}
public static function TYPE_DETECT()
{
if (!isset($_SERVER["CONTENT_TYPE"])) return false;
$type = trim(explode(';',$_SERVER["CONTENT_TYPE"])[0]);
$type = PRE::DOWN($type);
if ($type=='application/json') return 'json';
return false;
}
public static function get2str($cust_get=null)
{
$get= (is_null($cust_get)) ? $_GET : $cust_get;
if (!is_array($get) || !count($get)) return '';
$arr = [];
foreach ($get as $k => $v)
$arr[] = $k.'='.$v;
return '?'.implode('&',$arr);
}
public static function str2get($q="")
{
if(empty($q)) return false;
$q = explode('&',$q);
$out=[];
$c = count($query);
for ($i=0;$i<$c;$i++)
{
$r=explode('=',$q[$i]);
if(!isset($r[1])) $r[1]='';
$out[$r[0]]=$r[1];
}
return $out;
}
public static function MOVE($u)
{
http_response_code(301);
header("Location: ".$u);
exit();
}
public static function FIX_URLCASE($u)
{
$q = arr_v($u,'query','');
if(empty($q)) return false;
if (PRE::SHIFT($q,'DOWN')!=$q)
LE_URL::MOVE(PRE::SHIFT($u['full'],'DOWN'));
}
}

View File

@@ -0,0 +1,7 @@
<?php
class LE_SQLITE
{
}

493
CLASSES/core/LE_TPL.php Normal file
View File

@@ -0,0 +1,493 @@
<?php
class LE_TPL {
public $load_tpls=[]; //список загруженных шаблонов
public $meta,$cont_top,$cont_bottom,$mod_cont,$head_cont;
public $vars=[],$prefix,$tpl_arr,$debug=0,$clear=0;
function __construct()
{
$this->meta = ['title'=>'','keywords'=>'','description'=>''];
$this->prefix="main";
$this->mod_cont="";
$this->vars = ['tpl_arr'=>&$this->tpl_arr,'tpl'=>&$this];
}
public function fetch($t,&$vars=array(),$prefix=false,$cache_en=false)
{
//выгружаем переменные в функцию
if (is_array($this->vars)) extract($this->vars);
if (is_array($vars)) extract($vars);
//определяем путь до шаблона
$this->load_tpls[] = $__p = $this->path($t,$prefix);
//инклудим шаблон, буферизуем его выхлоп
ob_start();
include($__p);
return ob_get_clean();
}
public function path($tpl_path,$prefix=false)
{
if ($prefix===false) $prefix = $this->prefix;
$path = $prefix.DS.$tpl_path.".tpl";
$path_app = realpath((APPDIR."TPL".DS.$path));
$path_sys = realpath((SYSDIR."TPL".DS.$path));
//echo APPDIR.$path.BR;
//echo SYSDIR.$path.BR;
if (is_file($path_app)) return $path_app;
if (is_file($path_sys)) return $path_sys;
exit($path." - NOT FOUND TPL");
}
public function display($prefix=false,$main_tpl="main")
{
//global $config,$db;
$tpl = &$this;
if ($this->debug) echo_arr($this->load_tpls);
if (arr_v($_POST,'clear')=='yes') $this->clear=1;
if($prefix===false) $prefix = $this->prefix;
include SYSDIR."TPL".DS.$prefix.DS."static_list.php";
$this->static_dep_apply();
$this->add_need_static();
$path= $this->path($main_tpl,$prefix);
if ($this->clear)
{
echo $this->mod_cont;
return ($this->clear=0);
}
$tpl_arr = &$this->tpl_arr;
include($path);
}
//static elements
public $need_st_list=[],$static_list=[],$static_dep=[],$top_st=[],$bottom_st=[];
public function need_static($inp)
{
if (!is_array($inp)) $inp = [$inp];
$cnt = count($inp);
for($i=0;$i<$cnt;$i++)
{
$v = $inp[$i];
if (empty($v)) continue;
$this->need_st_list[$v]=1;
}
}
public function static_dep_apply($dep_list=false)
{
if ($dep_list===false) $dep_list=$this->static_dep;
if (!is_array($dep_list) || empty($dep_list)) return;
$need = &$this->need_st_list;
foreach ($dep_list as $m_name => $dep_items)
{
//для выключенных модулей не применяем зависимости
if ( !(isset($need[$m_name]) && $need[$m_name]==1) ) continue;
foreach ($dep_items as $k => $dep)
{
$need[$dep]=1;
}
}
}
public function add_need_static()
{
$need = $this->need_st_list;
$list = $this->static_list;
foreach ($this->static_list as $key => $item)
{
$pos = arr_v($item,'pos',false);
$type = arr_v($item,'type',"");
$link = arr_v($item,'link',"");
//echo $link.BR;
if ($pos===false) $pos = ($type=="js") ? "bottom" : "top";
$mod=arr_v($item,'mod','default');
if ( !((isset($need[$mod]) && $need[$mod]==1) || $mod=='default') ) continue;
switch ($type)
{
case 'js':
$cont = $this->js($link);
break;
case 'css':
$cont = $this->css($link);
break;
default:
continue 2;
break;
}
if ($pos=="top")
$this->top_st[]=$cont;
else
$this->bottom_st[]=$cont;
}
$_gl = "\n\t";
$this->head_cont.=implode($_gl,$this->top_st);
$this->cont_bottom.=implode($_gl,$this->bottom_st);
//echo_arr($this->top_st);
}
public function css($p,$min=0)
{
return '<link rel="stylesheet" type="text/css" href="'.$this->p2min($p,$min,'css').'?v='.VER.'" />';
}
public function js($p,$min=0)
{
return '<script src="'.$this->p2min($p,$min,'js').'?v='.VER.'"></script>';
}
public function p2min($path,$min,$ext)
{
if ($min)
{
$path = str_replace('.'.$ext,'.min.'.$ext,$path);
$path = str_replace('min.min','min',$path);
}
return $path;
}
}
/*
<?php
MP::DEF('TPLDIR1',SYSDIR.'TPL'.DS);
MP::DEF('TPLDIR2',APPDIR.'TPL'.DS);
MP::DEF('LST_TPL',0);
MP::DEF('DBG_MGS',0);
MP::DEF('ST_DEV');
MP::DEF('ST_GLUE');
class TPL
{
public $template='default.tpl',$prefix='default',$clear=0;
public $js2bottom=1;
public $tpl_arr=[],$vars=[],$txt,$declare_parts=[], $load_tpls = []; //зарегистрированные части css и js
public $glue_arr = ['css'=>[],'js'=>[]];
function __construct() {
$this->tpl_arr = ['text'=>'','_html_'=>'','head_objects'=>'','meta_title'=>'','meta_keywords'=>'','meta_description'=>''];
$this->txt = &$this->tpl_arr['text'];
$this->vars = ['tpl_arr'=>&$this->tpl_arr,'tpl'=>&$this];
}
public function decl_p($inp)
{
$inp = MP_ARR::FROM_STR($inp);
while ($r = array_shift($inp)) $this->declare_parts[$r]=1;
}
public function js4part($p,$f,$EOL=false,$pre="",$glued=1)
{
if (ST_GLUE && $glued) return $this->glue_reg('js',$p,$f);
return $this->st4p($p,$this->js($f),$EOL,$pre);
}
public function css4part($p,$f,$EOL=false,$pre="",$glued=1)
{
if (ST_GLUE && $glued) return $this->glue_reg('css',$p,$f);
return $this->st4p($p,$this->css($f),$EOL,$pre);
}
public function glue_reg($type,$p,$url)
{
$path = str_replace('/mp_pub',SYSDIR."PUB", $url);
$path = str_replace('/pub_data',WEBDIR."pub_data", $path);
switch ($type) {
case 'css':
$path = str_replace('.css','.min.css',$path);
break;
case 'js':
$path = str_replace('.js','.min.js',$path);
break;
}
$this->glue_arr[$type][] =
['u'=>$url,'p'=>$path,'l'=> ((int)$this->if_decl_p($p))];
}
public function glue_stat()
{
$js_k = $css_k = "";
if (!ST_GLUE) return;
foreach ($this->glue_arr['js'] as $key => $it) $js_k.=$it['l'];
foreach ($this->glue_arr['css'] as $key => $it) $css_k.=$it['l'];
$alph = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_','-','='];
$js_k = int2alphabet($alph,bindec($js_k));
$css_k = int2alphabet($alph,bindec($css_k));
$glue_path = WEBDIR."pub_data/static_cache/";
$js_path = $glue_path.$js_k.".js";
$css_path = $glue_path.$css_k.".css";
$glue_path = $alph = NULL;
unset($glue_path,$alph);
if (!is_file($js_path) && count($this->glue_arr['js']))
{
foreach ($this->glue_arr['js'] as $key => $it)
{
if (!$it['l']) continue;*/
//$pre = '/* file: '.$it['u'].'*/'."\n";
/* file_put_contents($js_path,$pre.file_get_contents($it['p'])."\n",FILE_APPEND);
}
}
if (!is_file($css_path) && count($this->glue_arr['css']))
{
foreach ($this->glue_arr['css'] as $key => $it)
{
if (!$it['l']) continue;*/
//$pre = '/* file: '.$it['u'].'*/'."\n";
/*file_put_contents($css_path,$pre.file_get_contents($it['p'])."\n",FILE_APPEND);
}
}
$this->to_head($this->css('/pub_data/static_cache/'.$css_k.".css",1));
$js_block = ($this->js2bottom) ? 'bottom_js' : 'head_objects';
$this->add2block($js_block,$this->js('/pub_data/static_cache/'.$js_k.".js",1));
}
public function st4p ($p,$inc,$EOL=false,$pre="")
{
if($this->if_decl_p($p)) return $pre.$inc.(($EOL)?$EOL:'');
}
public function st_format($inp,$pre="",$EOL="")
{
preg_match_all('!(\<[^>]+\>)!simu',$inp,$res);
foreach ($res[1] as $key => $v) echo $pre.$v.$EOL;
}
public function undecl_p($inp)
{
if($this->if_decl_p($inp)) unset($this->declare_parts[$inp]);
}
public function if_decl_p($inp)
{
if ($inp===0) return true;
return (isset($this->declare_parts[$inp]));
}
//+++добавить несколько частей в массиве
public function part_css($part,$css)
{
if ($this->if_decl_p($part))
echo $this->css($css);
}
public function display($prefix=false,$tpl_name="default")
{
global $tpl,$config,$db;
if (LST_TPL) echo_arr($this->load_tpls);
if (arr_v($_POST,'clear')=='yes') $this->clear=1;
if($prefix===false) $prefix = $this->prefix;
if ($this->clear)
{
echo $this->tpl_arr['text'];
return ($this->clear=0);
}
$tpl_arr = &$this->tpl_arr;
include($this->path($tpl_name,$prefix));
if (DBG_MGS) include($this->path('debug_message','default'));
return 1;
}
public function path($tpl_name,$prefix=false)
{
$p = ((empty($prefix))?$this->prefix:$prefix).DS.$tpl_name.'.tpl';
if (is_file($p_=TPLDIR2.$p) || is_file($p_=TPLDIR1.$p))
return str_replace('//','/',$p_);
exit($tpl_name.' - NOT FOUND!!!');
}
public function add2block($k,$v){
$this->tpl_arr[$k] = (isset($this->tpl_arr[$k]))? $this->tpl_arr[$k]."\r\n".$v : $v;
return $this;
}
public function canonical($url)
{
$this->to_head('<link rel="canonical" href="'.$url.'" />');
}
public function show_bl($n)
{
if (isset($this->tpl_arr[$n])) echo $this->tpl_arr[$n];
}
public function css($p,$nm=0)
{
return '<link rel="stylesheet" type="text/css" href="'.$this->p2min($p,$nm,'css').'?v='.MP_VER.'" />';
}
public function js($p,$nm=0)
{
return '<script src="'.$this->p2min($p,$nm,'js').'?v='.MP_VER.'"></script>';
}
public function to_head($str)
{
return $this->add2block('head_objects',$str);
}
public function add_js ($inp,$no_mod=0){
return $this->to_head($this->js($inp,$no_mod));
}
public function add_css ($inp,$no_mod=0){
return $this->to_head($this->css($inp,$no_mod));
}
public function mp_css($inp)
{
$inp = MP_ARR::FROM_STR($inp);
for ($i=0,$c=count($inp); $i < $c; $i++)
$this->add_css(M_PUB.'/css/'.$inp[$i]);
return $this;
}
public function mp_js($inp)
{
$inp = MP_ARR::FROM_STR($inp);
for ($i=0,$c=count($inp); $i < $c; $i++)
$this->add_js(M_PUB.'/js/'.$inp[$i]);
return $this;
}
public function meta_tags ($i,$i2=false)
{
if ($i===false && is_array($i2))
{
$i=[];
list($i['meta_title'],$i['meta_keywords'],$i['meta_description']) = $i2;
}
$f = function($n) {return(htmlspecialchars($n));};
$m_arr = SELECT_FROM_ARR('meta_description;meta_keywords',$i);
$m_arr = array_map($f,$m_arr);
//титл не экранируем
$m_arr['meta_title'] = $i['meta_title'];
unset($i);
$this->tpl_arr = array_merge($this->tpl_arr,$m_arr);
//echo_arr($m_arr);
unset($f,$m_arr);
}
public function ograph($title,$description,$image,$url,$type="website")
{
$a = &$this->tpl_arr;
$a['_html_'] = ' prefix="og: http://ogp.me/ns#"';
$_arr = compact('title','type','url','description','image');
foreach ($_arr as $p => $v)
{
$v=htmlspecialchars($v);
$this->to_head('<meta property="og:'.$p.'" content="'.$v.'"/>');
}
}
public function fetch($t,&$vars=array(),$prefix=false,$cache_en=false)
{
if ($cache_en)
{
$cache_key = MPCACHE::gen_key_p(array($t,$vars,$prefix));
$cache = MPCACHE::from_cache("tpl_cache",$cache_key);
if($cache!==false) return $cache['content'];
}
if (empty($t)||(mb_substr($t,0,1)=="#")) return '';
if (is_array($this->vars))extract($this->vars);
if (is_array($vars))extract($vars);
$tpl = &$this;
$this->load_tpls[] = $__p = $this->path($t,$prefix);
ob_start();
include($__p);
if ($cache_en)
{
$html = ob_get_clean();
MPCACHE::to_cache("tpl_cache",$cache_key,['content'=>$html]);
return $html;
}
return ob_get_clean();
}
public function txt($txt){$this->add2block('text',$txt);}
}
*/

View File

@@ -0,0 +1,36 @@
# LE\_FS - класс для работы с файловой системой и файлами
## GEN\_FNAME($inp\_name, $path, $prefix);
example
```
LE_FS::GEN_FNAME("picture.png",WEBDIR."/pub_data/","prod_");
```
Генерирует уникальное имя файла для указанной папки, расширение нового файла соответствует расширению входного в `$inp_name`
Опционально к имени файла в начале пристыковывается в префикс, например `prod_` `cat_` ...
***
## Apply2Files($path,&$func,$recouse=0)
> Данная функция создана для обработки массива данных
```
LE_FS::Apply2Files("./inp_folder/",$callback,0);
```
* `$path` \- путь до папки
* `$func` \- callback функция в которую передается полный путь до файла
* `$recourse` \- признак рекурсивности\, по умолчанию применяется только к указанной папке\, но если указан флаг то пройдет по всем подпапкам
>Внутри callback функции нужно предусматривать фильтрацию по расширению файла, например только xml или только jpg...
>
## SAVE_POST($inp,&$debug=false) - сохранение файла из POST
Сохраняет файл переданный в POST с указанным именем поля формы в POST в указанную папку `<input type="file" name="img_file">`
```
LE_FS::SAVE_POST(['f_name'=>'img_file','path'=>'/www/path/'])
```
Уникальное имя файлов генерируется автоматически...