From b2284a827e44a1f0c78ab818ed913c2feb11fd2a Mon Sep 17 00:00:00 2001 From: renz78 Date: Wed, 24 May 2023 14:41:03 +0300 Subject: [PATCH] test --- k2shop/k2shop/app/sys/k2admin.php | 50 + k2shop/k2shop/app/sys/k2backup.php | 134 +++ k2shop/k2shop/app/sys/k2banners.php | 79 ++ k2shop/k2shop/app/sys/k2cache.php | 32 + k2shop/k2shop/app/sys/k2cfg.php | 1549 +++++++++++++++++++++++++++++ k2shop/k2shop/app/sys/k2const.php | 31 + k2shop/k2shop/app/sys/k2cont.php | 1104 ++++++++++++++++++++ k2shop/k2shop/app/sys/k2content.php | 207 ++++ k2shop/k2shop/app/sys/k2edit.php | 924 +++++++++++++++++ k2shop/k2shop/app/sys/k2editor.php | 407 ++++++++ k2shop/k2shop/app/sys/k2icons.php | 137 +++ k2shop/k2shop/app/sys/k2inc.php | 205 ++++ k2shop/k2shop/app/sys/k2ini.php | 26 + k2shop/k2shop/app/sys/k2koolphp.php | 106 ++ k2shop/k2shop/app/sys/k2log.php | 180 ++++ k2shop/k2shop/app/sys/k2mail.php | 161 +++ k2shop/k2shop/app/sys/k2messages.php | 112 +++ k2shop/k2shop/app/sys/k2obj.php | 992 ++++++++++++++++++ k2shop/k2shop/app/sys/k2page.php | 213 ++++ k2shop/k2shop/app/sys/k2parser.php | 94 ++ k2shop/k2shop/app/sys/k2pathway.php | 88 ++ k2shop/k2shop/app/sys/k2propis.php | 117 +++ k2shop/k2shop/app/sys/k2save.php | 204 ++++ k2shop/k2shop/app/sys/k2secur.php | 244 +++++ k2shop/k2shop/app/sys/k2sendMess.php | 80 ++ k2shop/k2shop/app/sys/k2site.php | 1468 +++++++++++++++++++++++++++ k2shop/k2shop/app/sys/k2stylecontrols.php | 175 ++++ k2shop/k2shop/app/sys/k2sys.php | 359 +++++++ k2shop/k2shop/app/sys/k2template.php | 172 ++++ k2shop/k2shop/app/sys/k2timer.php | 124 +++ k2shop/k2shop/app/sys/k2twig.php | 17 + k2shop/k2shop/app/sys/lng/k2edit/en.csv | 47 + k2shop/k2shop/app/sys/lng/k2edit/fr.csv | 22 + k2shop/k2shop/app/sys/lng/k2edit/ru.csv | 47 + k2shop/k2shop/app/sys/lng/k2edit/ua.csv | 44 + k2shop/k2shop/app/sys/lng/k2site/en.csv | 10 + k2shop/k2shop/app/sys/lng/k2site/ru.csv | 9 + k2shop/k2shop/app/sys/lng/k2site/ua.csv | 9 + k2shop/k2shop/app/sys/res/info.yml | 13 + k2shop/k2shop/app/sys/updatek2.php | 246 +++++ 40 files changed, 10238 insertions(+) create mode 100644 k2shop/k2shop/app/sys/k2admin.php create mode 100644 k2shop/k2shop/app/sys/k2backup.php create mode 100644 k2shop/k2shop/app/sys/k2banners.php create mode 100644 k2shop/k2shop/app/sys/k2cache.php create mode 100644 k2shop/k2shop/app/sys/k2cfg.php create mode 100644 k2shop/k2shop/app/sys/k2const.php create mode 100644 k2shop/k2shop/app/sys/k2cont.php create mode 100644 k2shop/k2shop/app/sys/k2content.php create mode 100644 k2shop/k2shop/app/sys/k2edit.php create mode 100644 k2shop/k2shop/app/sys/k2editor.php create mode 100644 k2shop/k2shop/app/sys/k2icons.php create mode 100644 k2shop/k2shop/app/sys/k2inc.php create mode 100644 k2shop/k2shop/app/sys/k2ini.php create mode 100644 k2shop/k2shop/app/sys/k2koolphp.php create mode 100644 k2shop/k2shop/app/sys/k2log.php create mode 100644 k2shop/k2shop/app/sys/k2mail.php create mode 100644 k2shop/k2shop/app/sys/k2messages.php create mode 100644 k2shop/k2shop/app/sys/k2obj.php create mode 100644 k2shop/k2shop/app/sys/k2page.php create mode 100644 k2shop/k2shop/app/sys/k2parser.php create mode 100644 k2shop/k2shop/app/sys/k2pathway.php create mode 100644 k2shop/k2shop/app/sys/k2propis.php create mode 100644 k2shop/k2shop/app/sys/k2save.php create mode 100644 k2shop/k2shop/app/sys/k2secur.php create mode 100644 k2shop/k2shop/app/sys/k2sendMess.php create mode 100644 k2shop/k2shop/app/sys/k2site.php create mode 100644 k2shop/k2shop/app/sys/k2stylecontrols.php create mode 100644 k2shop/k2shop/app/sys/k2sys.php create mode 100644 k2shop/k2shop/app/sys/k2template.php create mode 100644 k2shop/k2shop/app/sys/k2timer.php create mode 100644 k2shop/k2shop/app/sys/k2twig.php create mode 100644 k2shop/k2shop/app/sys/lng/k2edit/en.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2edit/fr.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2edit/ru.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2edit/ua.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2site/en.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2site/ru.csv create mode 100644 k2shop/k2shop/app/sys/lng/k2site/ua.csv create mode 100644 k2shop/k2shop/app/sys/res/info.yml create mode 100644 k2shop/k2shop/app/sys/updatek2.php diff --git a/k2shop/k2shop/app/sys/k2admin.php b/k2shop/k2shop/app/sys/k2admin.php new file mode 100644 index 0000000..c180db6 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2admin.php @@ -0,0 +1,50 @@ +adminpage)){ + $this->adminpage=$k2->ins_comp('k2adminpage'); + } + + $rez=$this->adminpage->getAdminInfo($html); + + return $rez; + } + + + // Вывод контента + function content(){ + global $k2; + + if (!isset($this->adminpanel)){ + $this->adminpanel=$k2->ins_comp('k2adminpanel'); + } + + return $this->adminpanel->content(); + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2backup.php b/k2shop/k2shop/app/sys/k2backup.php new file mode 100644 index 0000000..0c95bd8 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2backup.php @@ -0,0 +1,134 @@ +' . "\r\n"; + $mail_headers .= 'From: my_site ' . "\r\n"; + + + $start = microtime(true); // запускаем таймер + + $deleteOld = deleteOldArchives($backup_folder, $delay_delete); // удаляем старые архивы + $doBackupFiles = backupFiles($backup_folder, $backup_name, $dir); // делаем бэкап файлов + $doBackupDB = backupDB($backup_folder, $backup_name); // и базы данных + + // добавляем в письмо отчеты + if ($doBackupFiles) { + $mail_message .= 'site backuped successfully
'; + $mail_message .= 'Files: ' . $doBackupFiles . '
'; + } + + if ($doBackupDB) { + $mail_message .= 'DB: ' . $doBackupDB . '
'; + } + + if ($deleteOld) { + foreach ($deleteOld as $val) { + $mail_message .= 'File deleted: ' . $val . '
'; + } + } + + $time = microtime(true) - $start; // считаем время, потраченое на выполнение скрипта + $mail_message .= 'script time: ' . $time . '
'; + + mail($mail_to, $mail_subject, $mail_message, $mail_headers); // и отправляем письмо + } + + + /** + * backup файлов + * @param type $backup_folder + * @param type $backup_name + * @param type $dir + * @return string + */ + function backupFiles($backup_folder, $backup_name, $dir) + { + $fullFileName = $backup_folder . '/' . $backup_name . '.tar.gz'; + shell_exec("tar -cvf " . $fullFileName . " " . $dir . "/* "); + return $fullFileName; + } + + /** + * backup базы данных + * @param type $backup_folder + * @param type $backup_name + * @return string + */ + function backupDB($backup_folder, $backup_name) + { + $fullFileName = $backup_folder . '/' . $backup_name . '.sql'; + $command = 'mysqldump -h' . $db_host . ' -u' . $db_user . ' -p' . $db_password . ' ' . $db_name . ' > ' . $fullFileName; + shell_exec($command); + return $fullFileName; + } + + /** + * удаление старых архивов + * @param type $backup_folder + * @param type $delay_delete + * @return array + */ + function deleteOldArchives($backup_folder, $delay_delete) + { + $this_time = time(); + $files = glob($backup_folder . "/*.tar.gz*"); + $deleted = array(); + foreach ($files as $file) { + if ($this_time - filemtime($file) > $delay_delete) { + array_push($deleted, $file); + unlink($file); + } + } + return $deleted; + } + /** + * + * @return type + */ + function content() + { + $rez = $this->backup(); + return $rez; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2banners.php b/k2shop/k2shop/app/sys/k2banners.php new file mode 100644 index 0000000..d7e9765 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2banners.php @@ -0,0 +1,79 @@ +ico->edit_banner(); + + return "Редактировать"; + } + + + // Кнопки для администрирования + function admButtons(&$html){ + + global $k2; + + if (($k2->auth->isAdmin()) and ($k2->auth->isDesignMode())){ + $btn=$this->editLinks(); + }else{ + $btn=''; + } + + $html=str_replace('{edit}', $btn, $html); + + } + + + function content(){ + + if ($this->isshow){ + + + $cont=$this->getContent(false); + + $rez=str_replace('{content}', $cont, $this->template); + + $this->admButtons($rez); + + return $rez; + + +// $rez=$this->template; +// $this->admButtons($rez); + +// return $rez; + } + + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2cache.php b/k2shop/k2shop/app/sys/k2cache.php new file mode 100644 index 0000000..58ca491 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2cache.php @@ -0,0 +1,32 @@ +cache_on; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2cfg.php b/k2shop/k2shop/app/sys/k2cfg.php new file mode 100644 index 0000000..c726d27 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2cfg.php @@ -0,0 +1,1549 @@ + ['name'=>'Английский','align'=>'left'], + 'ua'=> ['name'=>'Украинский','align'=>'left'], + 'ru'=> ['name'=>'Русский','align'=>'left'] + ]; + + public $month = [ + 'ua' => ["1" => "січня", + "2" => "лютого", + "3" => "березня", + "4" => "квітня", + "5" => "травня", + "6" => "червня", + "7" => "липня", + "8" => "серпня", + "9" => "вересня", + "10" => "жовтня", + "11" => "листопада", + "12" => "грудня" + ] + ]; + + public $lngadmin='ru'; // The language of the admin (Язык админ-части) + public $lng='ru'; // The language of the public (Язык публичной части) + + + // Инициализация. Класс переопределяется всегда + protected function init_obj(){ + + if ($this->error_level==0){ + error_reporting(0); + }elseif($this->error_level==1){ + // Выводим все ошибки и замечания + error_reporting(E_ALL | E_STRICT); + }else{ + error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT); + } + + + if($this->timer){ + $this->timer=new k2timer(); + $this->timer->start_time(); + } + // Назначаем супер-глобальные переменные + $this->get=&$_GET; + $this->post=&$_POST; + $this->cookie=&$_COOKIE; + $this->env=&$_ENV; + $this->files=&$_FILES; + $this->request=&$_REQUEST; + $this->server=&$_SERVER; + $this->session=&$_SESSION; + //$this->globals=&$GLOBALS; + + $this->globals=$GLOBALS; + + } + + // + function LoadBeforeConfig(){ + //parent::LoadBeforeConfig(); + } + + + // Загрузка Yml из файла + // $ymlfilename - название yml-файла + // Ф-ция возвращает массив, сформированный из yml-файла + function loadFromYml($ymlfilename, $no_parse=false){ + $rez=[]; + $filename=nslashe($ymlfilename); + if (file_exists($filename)){ + + $ymltext=file_get_contents($filename); + if (!$no_parse){ + //$yaml_file=nslashe($this->rootdir.'\k2shop\k2shop\libs\yaml\Spyc.php'); + //require_once $yaml_file; + //$rez = Spyc::YAMLLoadString($ymltext); + $rez = Yaml::parse($ymltext); + }else{ + $rez = $ymltext; + + } + + }else{ + echo 'Error. File not found: '.$filename; + } + return $rez; + } + + + + + // Java-script уведомление + function mess_java($mess){ + echo ""; + } + + + // Восстановление языка + function restoreLang(){ + + + + if (trim($this->get('lng')<>'')){ + $_SESSION['lng']=$this->get('lng'); + } + + if (trim($this->get('lngadmin')<>'')){ + $_SESSION['lngadmin']=$this->get('lngadmin'); + } + + + + if (isset($_SESSION['lng'])){ + $this->lng=$_SESSION['lng']; + } + + if (isset($_SESSION['lngadmin'])){ + $this->lngadmin=$_SESSION['lngadmin']; + } + + } + + + // Сохранения языка + function saveLang(){ + $_SESSION['lng']=$this->lng; + $_SESSION['lngadmin']=$this->lngadmin; + + } + + + function __destruct() { + parent::__destruct(); + $this->db = null; + } + + + + + // Функция возвращает предыдущий каталог + function getParentDir($path){ + $dirarr = explode(DIRECTORY_SEPARATOR, $path); + unset($dirarr[count($dirarr)-1]); + $r=implode(DIRECTORY_SEPARATOR, $dirarr); + + return $r; + + } + + // Добавление пакета в перечень пакетов + function addPack($packname){ + global $k2; + array_push($this->packs, $packname); + } + + + // Выход из авторизации + function unLogin(){ + header ('Location: /?p=unlogin'); + } + + // Функция определяет является ли запуск К2 из веб или из приложения + function isWeb(){ + return trim($this->server['DOCUMENT_ROOT'])<>''; + } + + + // Возвращает название текщего домена + function domain(){ + $rez=''; + + if (isset($this->server['HTTP_HOST'])){ + $rez=$this->server['HTTP_HOST']; + } + + return $rez; + } + + // Возвращает адрес, откуда пришел пользователь + function reffer(){ + $rez=''; + + if (isset($this->server['HTTP_REFERER'])){ + $rez = $this->server['HTTP_REFERER']; + } + + return $rez; + } + + + // Возвращает название текущего шаблона + function cur_tpl(){ + $tpl=''; + + if (isset($this->template)) { + $tpl=$this->template->cur(); + } + + return $tpl; + } + + + // Возвращает является текущая папка корневой + function isRoot(){ + return !isset($_SERVER['REQUEST_URI']) or $_SERVER['REQUEST_URI']=='/'; + } + + // Возвращает текущий URL + function getCurURL(){ + $rez = $this->surl->getStandartURL($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); + return $rez; + } + + + + + // Возвращает параметры URL + function getParamURL(){ + return getenv('QUERY_STRING'); + } + + + // Нормализация URL + // Функция делает, чтоб не законченные URL начинались с корня + // например, из img/montparnasse.jpg делает /img/montparnasse.jpg + function normURL($url){ + $rez=$url; + + if (strlen($rez)>0){ + if (substr($rez, 0, 1)<>'/'){ + $rez='/'.$rez; + } + }else{ + $rez='/'; + } + + return $rez; + } + + + + + // Загружает языки + function loadLangs(){ + //$filename=nslashe($this->rootdir.'/k2shop/k2shop/resource/yaml/k2cfg-langs.yml'); + //$this->langs = Yaml::parse((file_get_contents($filename))); + //$this->langs = $this->loadFromYml($this->rootdir.'/k2shop/k2shop/resource/yaml/k2cfg-langs.yml'); + + //$this->langs = $this->loadFromYml($this->getResourceDirYml().'k2cfg-langs.yml'); + } + + + // Каталог ресурсов + function getResourceDir(){ + return $this->rootdir.'/k2shop/k2shop/resource/'; + } + + // Каталог ресурсов файлов yml + function getResourceDirYml(){ + return $this->getResourceDir().'yaml/'; + } + + // Каталог ресурсов файлов yml для заданного языка + function getResourceDirYmlLang($lang='ua'){ + return $this->getResourceDirYml().$lang.'/'; + } + + + // Функция расчитывает путь к корневому каталогу + function calc_root(){ + + global $root, $modeapp; + + + if ($this->isWeb() or $modeapp==1){ + $this->rootdir=trim($root); + $this->cfgdir=nslashe($this->rootdir.'/cfg'); + + $this->loadLangs(); + $this->LoadCfg(); + }else{ + + $this->rootdir=getcwd(); + $this->cfgdir=$this->rootdir.'/cfg'; + + $this->loadLangs(); + + $this->LoadCfg(); + + } + + + } + + + // Проверяет включено ли подключение, если не влкючено - включает его + function check_connect(){ + $rez=false; + if (!isset($this->db)){ + $this->connect_db=true; + $rez=$this->connectdb(true); + } + return $rez; + } + + + // Подключение к базе данных + // $db - PDO подключение + // $dbinfo - информация для подключения. Это массив + // 'driver' => $this->server_type, Тип базы данных + // 'user' => $this->user, Пользователь + // 'password' => $this->pass, Пароль + // 'host' => $this->pass, Хост + // 'dbname' => $this->dbname Название базы данных + function connect(&$db, $dbinfo){ + + //global $entityManager; + $rez = false; + + //var_dump($dbinfo); + + try { + + $typedb='mysql'; + if (isset($dbinfo['driver'])) + $this->phpDBType($dbinfo['driver']); + + $db = new PDO($typedb.":host=".$dbinfo['host'].";dbname=".$dbinfo['dbname'], + $dbinfo['user'], $dbinfo['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES UTF8')); + //$db = $entityManager->getConnection()->$_conn; + //var_dump($entityManager->getConnection()); + + //print_r($this->sql); + $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); + $rez=true; + //$this->connected=true; + + // Включение строгого режима + if ($this->strict_mode==1){ + $this->sql->runSQL("SET sql_mode='TRADITIONAL';"); + }else{ + // Включаем традиционный стиль SQL + $this->sql->runSQL("SET sql_mode='NO_ENGINE_SUBSTITUTION';"); + } + + // Установка временной зоны для mysql + $this->sql->runSQL("SET time_zone='".$this->time_zone_mysql."'"); + + + // Установка временной зоны для PHP + if (function_exists('date_default_timezone_set')){ + date_default_timezone_set($this->time_zone); + } + + } + catch(PDOException $e) { + $err = $e->getMessage(); + + $err = str_replace($dbinfo['user'], '', $err); + $err = str_replace(substr($dbinfo['password'], 0, 5), '.........', $err); + echo 'Error Connection: '.$err; + } + + return $rez; + } + + + // Подключение к базе данных + function connectdb($connectdb=false){ + + //global $entityManager; + + if ($this->connected) exit; + + if ($this->connect_db or $connectdb) { + $this->connected = $this->connect($this->db, + ['driver' => $this->server_type, + 'user' => $this->user, + 'password' => $this->pass, + 'host' => $this->host, + 'dbname' => $this->dbname + ]); + + $this->add_connections(); + + } + + return $this->connected; + } + + + // Производит подключение к дополнительным подключениям + function add_connections(){ + global $k2, $conn; + + if (isset($conn['add_connecton'])){ + + foreach ($conn['add_connecton'] as $k => $v){ + + $this->add_connections[$k]=$v; + $this->add_connections[$k]['connected']=false; + + if ($v['auto_connect']){ + $this->add_connections[$k]['connected'] = $this->connect($this->add_connections[$k]['db'], $this->add_connections[$k] ); + } + + } + } + + } + + // Возвращает название протокола + function getProtocol(){ + $protocol = ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") || $_SERVER["SERVER_PORT"] == "443") ? "https" : "http"; + //echo $this->server['HTTP_HOST']; + return $protocol; + } + + // Возвращает URL протокола + function getURLProtocol(){ + return $this->getProtocol()."://"; + } + + + // Возвращает URL вместе с доменом + function getDomainURL(){ + return $this->getURLProtocol().$this->domain(); + } + + function setProj(){ + global $root; + $projnamefile = getParentDir($root).'/k2proj.php'; + //$projnamefile = nslashe(getParentDir(__DIR__).'/k2proj.php'); + + if (file_exists($projnamefile)){ + $projname = file_get_contents($projnamefile); + } else { + $projname = 'default'; + } + return $projname; + } + + function setConn(){ + global $root; + $projname = $this->setProj(); + + $filename = nslashe(getParentDir($root).'/cfg/'.$projname.'/db.yml'); + if (file_exists($filename)){ + $conn = $this->loadFromYml($filename); + + $conn['charset'] = 'utf8'; + $conn['driverOptions'] = ['1002' => 'SET NAMES utf8']; + + + }else{ + echo 'Не найден конфигурационный файл подключения к базе данных'; + } + + return $conn; + } + + function init_small(){ + //global $conn; + require_once(k2sys('k2sys.php')); + //require_once 'k2sys.php'; + + $this->calc_root(); + + $this->sys = new k2sys(); + //echo 12233; + + //Компосер. Автозагрузчик + //$loader = require $this->rootdir.'\k2shop\vendor\vendor\autoload.php'; + + + $conn = $this->setConn(); + + if (trim($conn['dbname'])<>''){ + $this->host = $conn['host']; // Подключение к базе данных + $this->dbname = $conn['dbname']; + $this->user = $conn['user']; + $this->pass = $conn['password']; + + if (isset($conn['driver'])) + $this->server_type = $conn['driver']; + } + + + + // Компонента логирования + $this->log=$this->ins_comp('k2log'); + + // Выполнение sql + $this->sql=$this->ins_comp('k2sql'); + + } + + + + + + //ініціалізація з командної строки + function init_cmd(){ + global $k2, $conn, $root; + require_once(k2sys('k2sys.php')); + $this->calc_root(); + $this->sys = new k2sys(); + $projname = $this->setProj(); + $filename = nslashe(getParentDir($root).'/cfg/'.$projname.'/db.yml'); + if (file_exists($filename)){ + $conn = []; + if (file_exists($filename)){ + $ymltext = file_get_contents($filename); + $yaml_file = nslashe($this->rootdir.'\k2shop\k2shop\libs\yaml\Spyc.php'); + require_once $yaml_file; + $conn = Spyc::YAMLLoadString($ymltext); + //$conn = Yaml::parse($ymltext); + } else { + echo 'Error. File not found: '.$filename; + } + $conn['charset'] = 'utf8'; + $conn['driverOptions'] = ['1002' => 'SET NAMES utf8']; + }else{ + echo 'Не найден конфигурационный файл подключения к базе данных'; + } + //$conn = $this->setConn(); + + if (trim($conn['dbname'])<>''){ + $this->host = $conn['host']; // Подключение к базе данных + $this->dbname = $conn['dbname']; + $this->user = $conn['user']; + $this->pass = $conn['password']; + + if (isset($conn['driver'])) + $this->server_type = $conn['driver']; + } + $arr_sets = ['driver' => $this->server_type, + 'user' => $this->user, + 'password' => $this->pass, + 'host' => $this->host, + 'dbname' => $this->dbname + ]; + + $charset = 'utf8'; + $opt = []; + $dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$charset"; + try { + $this->db = new PDO($dsn, $this->user, $this->pass, $opt); + $this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); + $this->connected=true; + } catch(PDOException $e) { + echo 'Не удалось установить соединение';//'Error Connection: '.$e->getMessage(); + } + //$this->connected = $this->connect($this->db, $arr_sets); + // Компонента логирования + $this->log=$this->ins_comp('k2log'); + + // Выполнение sql + $this->sql=$this->ins_comp('k2sql'); + } + + /** + * изменение атрибута href в тегах a при ЧПУ + * @global type $k2 + * @param type $link + * @return type + */ + function updateSurlLinks($link) + { + global $k2; + require_once($k2->rootdir.'/k2shop/k2shop/libs/simpleHtmlDom/simple_html_dom.php'); + + + $html = str_get_html($link); + + if ($html){ + $e = $html->find("a"); + $html = str_replace('&', '&', $html); + foreach ($e as $e_element){ + $old_href = $e_element->href; + //$old_href = str_replace('&', '&', $old_href); + + $new_href = $this->getUrl($old_href); + $html = str_replace($old_href, $new_href, $html); + + // $html = str_replace('&', '&', $html); // Update the href + } + + } + return $html; + } + + + /** + * инициализация + */ + function init(){ + $this->init_small(); + + $this->secur=$this->ins_comp('k2secur'); + + + + + $this->template=new k2template(); + + // Определение протокола + if ($this->proto==''){ + $this->proto=$this->getProtocol(); + } + + + if ($this->server['HTTP_HOST'] == 'vdoc2.dpcenter.org.ua') { + $this->proto='http'; + } + + $this->connectdb(); + + //определение шаблона + if( !($this->template->getTemplate() == '') ) { + $this->template->cur=$this->template->getTemplate(); // Если указан шаблон для сайта в админке + } else { + $this->template->cur = $this->curtemplate; // Шаблон по умолчанию в папке usr/cfg + } + + + + // Инициализация конфигуратора + $this->cache=new k2cache(); + + + $this->parser=$this->ins_comp('k2parser'); + + + + + + $this->surl=$this->surl=$this->ins_comp('k2sefurl'); + + + + + if ($this->selfurl){ + $this->surl->URL_FromSefURL(); + } + $this->restoreLang(); + + $this->auth=$this->ins_comp('k2auth'); + + // Инициализация системы безопасности + $this->secur->init(); + + //$this->auth_alt=$this->ins_comp('k2auth_alt'); + $this->stylecontrols=$this->ins_comp('k2stylecontrols'); + + $this->mail=$this->ins_comp('k2mail'); + + // Защита Куки + //$this->secur->SecurCook(); + $this->secur->SecurAll(); // Попробую защищать все. Посмотрим будет ли нормально работать... + + + $this->site=$this->ins_comp('k2site'); + + // Инициализация Kool-компонент + $this->kool=$this->ins_comp('k2koolphp'); + + // Вставляем иконки + $this->ico=$this->ins_comp('k2icons'); + + + + if ($this->message_on){ + $this->message=$this->ins_comp('k2messages'); + } + + + // Определение версии браузера и запрет работы в нем + $this->browser=$this->ins_comp('k2browser'); + $this->browser->blockBrowser(); + + + $this->root_url = $this->getUrl($this->root_url); + + if (trim($this->root_url)<>'' && (isset($_SERVER['REQUEST_URI'])) && (($_SERVER['REQUEST_URI']=='/') or ($_SERVER['REQUEST_URI']=='/index.php'))){ + header('Location: '.$this->root_url); + } + // Переадресация корня на нужную компоненту +// if($this->auth->isAdmin()){ +// if (trim($this->root_url)<>'' && (isset($_SERVER['REQUEST_URI'])) && (($_SERVER['REQUEST_URI']=='/') or ($_SERVER['REQUEST_URI']=='/index.php'))){ +// header('Location: '.$this->root_url); +// } +// } else { +// if (trim($this->root_url)<>'' && (isset($_SERVER['REQUEST_URI'])) && (($_SERVER['REQUEST_URI']=='/index.php'))){ +// header('Location: '.$this->root_url); +// } +// } + + + + } + + + + // Функция возвращает информацию о подключении и классе работе с ним + function sqlInfo($dbname=''){ + + + if ($dbname=='') { + $rez = [ + 'ver' => 'k2', + 'conn' => $this->db, + 'connected' => $this->connected, + 'conf' => [ + "type" => $this->phpDBType($this->server_type), + "server" => $this->host, + "user" => $this->user, + "password" => $this->pass, + "database" => $this->dbname + + ], + 'k2sql' => $this->sql + ]; + }else{ + $db=$this->find_connection($dbname); + if (isset($db)){ + + $rez = [ + 'ver' => 'k2', + 'conn' => $db['db'], + 'connected' => $db['auto_connect'], + 'conf' => [ + "type" => $this->phpDBType($db['driver']), + "server" => $db['host'], + "user" => $db['user'], + "password" => $db['password'], + "database" => $db['dbname'] + + ], + 'k2sql' => $this->sql + ]; + + } + } + + + + return $rez; + } + + + + + // Формирует массив поиска компонент + function arrSearchComponents(){ + $rez = $this->search_comp; + + foreach ($this->packs as $p) { + foreach ($this->search_packarr as $t) { + $v = $t; + $v = str_replace('{pack}', $p, $v); + array_push($rez, $v); + } + } + + return $rez; +} + + + + + +// Поиск скрипта с заданным названием по указанному массиву путей +function search_script($name, $temp = '', $arr = [], $ext = '.php') +{ + global $root; + + $path=''; + + $name_temp=$name; + if ($temp<>''){ + $name_temp.='_'.trim($temp); + } + + // По умолчанию, берем массив путей к компонентам + if (count($arr)==0){ + $arr=$this->arrSearchComponents(); + } + + foreach ($arr as $e) { + $pathtmp=$this->replace_tpl_path($e, $name); + + // Проверка шаблона + $pathtmp1=$pathtmp.'/'.$name_temp.$ext; + $pathtmp1=nslashe($this->rootdir.$pathtmp1); + + if (file_exists($pathtmp1)){ + $path=$pathtmp1; + break; + } + + // Проверка компоненты + $pathtmp.='/'.$name.$ext; + $pathtmp=nslashe($this->rootdir.$pathtmp); + + //$pathtmp=str_replace('//', '/', $pathtmp); + + + //echo 'root='.$this->rootdir."\n"; + //echo $pathtmp."\n"; + + if (file_exists($pathtmp)){ + $path=$pathtmp; + break; + } + + } + + + return $path; + +} + + + +// Замена шаблонов в путях +// заменяется шаблон {domain} - на название домена +// {template} - на название шаблона. +function replace_tpl_path($path, $compname=''){ + global $k2proj; + + $path=str_replace('{domain}', $this->domain(), $path); + $path=str_replace('{template}', $this->cur_tpl(), $path); + $path=str_replace('{compname}', $compname, $path); + $path=str_replace('{proj}', $k2proj, $path); + + + return $path; +} + + +// Возвращает название к скрипту +// Возвращает массив с элементами: +// filename - название файла скрипта +// full_comp_name - название компоненты +function getScriptName($compname, $temp=''){ + + $filename=$this->search_script($compname, $temp); + + if (trim($temp)==''){ + $full_comp_name=trim($compname); + }else{ + $full_comp_name=trim($compname).'_'.trim($temp); + } + + // Если шаблонной компоненты не находим - ищем основную + if (trim($filename)==''){ + $filename=$this->search_script($compname); + } + + $rez['filename']=$filename; + $rez['full_comp_name']=$full_comp_name; + + return $rez; +} + + +// Возвращает название компонента и шаблона +// Возвращает массив с элементами +// 0 - название компоненты +// 1 - название шаблона компоненты +function getComp($comm){ + global $k2; + + $rez[0]=''; + + if (trim($comm)<>''){ + $s=explode('_', trim($comm), 2); + + $s2=''; + if (count($s)>1){ + $s2.=$s[1]; + } + + if (($s2<>'')&&($k2->get('c')<>'')){ + $s2.='_'; + } + + if (trim($k2->get('c'))<>''){ + $s2.=$k2->get('c'); + } + + + $rez[0]=$s[0]; + $rez[1]=$s2; + + } + + return $rez; + +} + + +// Вставка файла с учетом вхождения компонент +// Возвращает массив +// filename - название файла компоненты +// full_comp_name - полное название компоненты +public function inc($compname, $temp=''){ + + $p=$this->getScriptName($compname, $temp); + $filename=$p['filename']; + $full_comp_name=$p['full_comp_name']; + + //secho "comppath=$filename\n"; + + if (trim($filename)<>''){ + require_once($filename); + } + + return array('filename' => $filename, 'full_comp_name' => $full_comp_name); +} + + + +// Вставка компоненты +// $compname - название компоненты +// $owner - владелец класса +// $temp - шаблон +public function ins_comp2($compname, &$owner='', $temp=''){ + return $this::ins_comp($compname,$temp,false,$owner); +} + + +// Вставка компоненты +// $compname - название компоненты +// $isreq - обязательно требовать полного сопадения класса +public function ins_comp($compname, $temp='', $isreq=false, &$owner=''){ + + + $my=''; + + if (trim($temp)=='' and $isreq){ + return ''; + } + + $arr=$this->inc($compname, $temp); + $filename=$arr['filename']; + $full_comp_name=$arr['full_comp_name']; + + + if ($filename==''){ + echo 'Component not Found: '.$full_comp_name."
\n"; + }else{ + + try{ + + if (class_exists($full_comp_name)){ + //echo "comp=$filename\n"; + //echo "comp=$full_comp_name\n"; + $my = new $full_comp_name($temp,$filename,$owner); + + //var_dump($my); + }else{ + $arr=$this->inc($compname); + $full_comp_name=$arr['full_comp_name']; + + + if (class_exists($full_comp_name) && !$isreq){ + //echo 'isreq='.$isreq."\n"; + $my = new $compname($temp,$filename,$owner); + }else{ + //echo "exit comp=$compname\n"; + return ''; + } + } + + $my->path_comp=$filename; + + } + catch(PDOException $e) { + echo $e->getMessage(); + } + + + } + return $my; + + } + + + + // Команды инициализации для интернет-страницы + function iniPage(){ + } + + + // Получение массива get (в будущем будем блокировать возможность взлома) + // $varname - название переменной $_GET + // $safe - применять ли защищенное чтение + function get($varname, $safe=true){ + if (isset($this->secur)){ + return $this->secur->get($varname, $safe); + } + } + + + // Получения массива post (в будущем будем блокировать возможности взлома) + // $varname - название переменной $_POST + // $safe - применять ли защищенное чтение + function post($varname, $safe=true){ + return $this->secur->post($varname, $safe); + } + + + + // Проаерка инициализации + function issetPost($varname){ + return isset($this->post[$varname]); + + } + + +// Проаерка инициализации + function issetGet($varname){ + return isset($this->get[$varname]); + + } + + // Функция получения get для вставки в базу данных + function getDB($varname, $safe=true){ + $rez=$this->get($varname, $safe); + $rez=$this->strSQL($rez); + return $rez; + } + + + // Функция получения post для вставки в базу данных + function postDB($varname, $safe=true){ + $rez=$this->post($varname, $safe); + $rez=$this->strSQL($rez); + return $rez; + } + + + // Функция обработки строки перед вставкой в базу данных + // Заменяет запрещенные символы для sql на стабильную комбинацию + function strSQL($strinp){ + $rez=str_replace("'", "''", $strinp); + return $rez; + } + + + + // Получение массива session (в будущем будем блокировать возможность взлома) + // $varname - название переменной $_SESS + // $safe - применять ли защищенное чтение + function sess($varname, $safe=true){ + $rez=null; + + if (isset($_SESSION[$varname])){ + $rez=$_SESSION[$varname]; + }else{ + $rez=''; + }; + + + return $rez; + } + + // Берет переменные как с $_SESSION, $_POST и $_GET + // $varname - название переменной $_GET + // $safe - применять ли защищенное чтение + function myvar($varname, $safe=true){ + + $rez=null; + + if (isset($_SESSION[$varname])){ + $rez=$_SESSION[$varname]; + }elseif (isset($_POST[$varname])){ + $rez=$_POST[$varname]; + }elseif (isset($_GET[$varname])){ + $rez=$_GET[$varname]; + }; + + if ($rez=null){ + $rez=''; + } + + return $rez; + } + + + function GoBack($url=''){ + if (trim($url)==''){ + header ('Location: '.$this->reffer()); + }else{ + header ('Location: '.$url); + } + } + + + // Выводит значение элемента массива, если массив не пустой и элемент массива не нул + function myecho($arr, $fieldname){ + $rez=''; + + if (isset($arr)){ + + if (isset($arr[$fieldname])){ + $rez=$arr[$fieldname]; + } + } + + return $rez; + } + + + + // Месяц прописью + function getMonthPropis($month_num, $lang='ua'){ + + if (!isset($this->month[$lang])){ + $this->month[$lang]=$this->getResourceDirYmlLang($lang).'k2cfg-month.yml'; + } + + /*$month_r = [ + "1" => "січня", + "2" => "лютого", + "3" => "березня", + "4" => "квітня", + "5" => "травня", + "6" => "червня", + "7" => "липня", + "8" => "серпня", + "9" => "вересня", + "10" => "жовтня", + "11" => "листопада", + "12" => "грудня"]; */ + + return $this->month[$lang][$month_num]; + } + + + // Проверяет есть ли сейчас вставка значений + function isPost(){ + $rez=!empty($this->post); + + //!empty($_POST) + + return $rez; + } + + + // Запись в лог + // $mess - сообщение + // $filename - название файла + // $isshow - выводить ли сообщение на экран + function addLog($mess, $filename='k2main.log', $isshow=false, $event="Non"){ + $this->log->addLog($mess, $filename, $isshow); + } + + function dump($arr){ + ob_start(); + var_dump($arr); + $rez=ob_get_contents(); + ob_end_clean(); + return $rez; + } + + + + // Форммирует название бланка печати + function getBlankName($filename=''){ + global $k2proj; + + $rez='/data/'.$k2proj.'/reports/'.$filename.'.mrt'; + $full_file=nslashe($this->rootdir.$rez); + if (!file_exists($full_file)){ + $rez='/var/reports/'.$filename.'.mrt'; + $full_file=nslashe($this->rootdir.$rez); + if (!file_exists($full_file)){ + $rez=''; + } + } + + return $rez; + } + + + /** + * Формирует название шаблона письма + * @global type $k2proj + * @param type $filename + * @return string + */ + function getEmailTpl($filename=''){ + global $k2proj; + + $rez='/data/'.$k2proj.'/emails/'.$filename.'.html'; + $full_file=nslashe($this->rootdir.$rez); + if (!file_exists($full_file)){ + $rez='/var/emails/'.$filename.'.html'; + $full_file=nslashe($this->rootdir.$rez); + if (!file_exists($full_file)){ + $rez=''; + } + } + + return $rez; + } + + + // Печать документа + // $filename - Основное название отчета + // $filename2 - Альтернативное название отчета + function printDoc($filename='', $filename2=''){ + $rep=$this->ins_comp2('k2stimul_report', $this); + + $full_file=''; + if ($filename2<>''){ + $full_file=$this->getBlankName($filename2); + } + + if (($filename2=='')or($full_file=='')){ + $full_file=$this->getBlankName($filename); + } + + echo 'full_file='.$full_file; + + $rez=$rep->view(/*$this->getBlankName($filename)*/$full_file); + + return $rez; + } + + + // Вызов дизайнера документа + function designDoc($filename='', $filename2=''){ + if (!$this->auth->isSuperAdmin()){ + die('Доступ заборонено!'); + } + + $rep=$this->ins_comp2('k2stimul_report', $this); + + $full_file=''; + if ($filename2<>''){ + $full_file=$this->getBlankName($filename2); + } + + if (($filename2=='')or($full_file=='')){ + $full_file=$this->getBlankName($filename); + } + + + $rez=$rep->design(/*$this->getBlankName($filename)*/$full_file); + + return $rez; + } + + + // Вызов дизайнера документа + function saveDoc($filename='', $filename2=''){ + + + $rep=$this->ins_comp2('k2stimul_report', $this); + + $full_file=''; + if ($filename2<>''){ + $full_file=$this->getBlankName($filename2); + } + + if (($filename2=='')or($full_file=='')){ + $full_file=$this->getBlankName($filename); + } + + + $rez=$rep->savereport(/*$this->getBlankName($filename)*/$full_file); + + return $rez; + } + + // Формирует из адреса ЧПУ-адрес + function getUrl($url){ + $rez=''; + + if ($this->selfurl){ + $rez=$this->surl->SefURL_FromURL($url); + }else{ + $rez=$url; + } + + + return $rez; + } + + + // Возвращает название подключения в php + function phpDBType($dbtype){ + $rez=$dbtype; + + $rez=str_replace('pdo_','', $rez); + if (trim($rez)=='mysql'){ + $rez='mysqli'; + } + + return $rez; + } + + // Ищет подключение по названию + function find_connection($conn_name){ + $rez=null; + + if (isset($this->add_connections) && (isset($this->add_connections[$conn_name])) ) + { + $rez=$this->add_connections[$conn_name]; + } + + + return $rez; + } + + + // Возвращает каталог с метаданными + function getMetadataDir(){ + $rez=nslashe($this->rootdir.'/k2shop/k2shop/metadata/'); + return $rez; + } + + // Возвращает каталог с метаданными + function getMetadataDirPack($pack){ + $rez=nslashe($this->rootdir.'/k2shop/k2shop/metadata/'.$pack); + return $rez; + } + + function getMetadataViewDir(){ + $rez=nslashe($this->rootdir.'/k2shop/k2shop/metadata_view/'); + return $rez; + } + + +} // Конец класса!!! + + + + +// ВНИМАНИЕ! ЭТО ФУНКЦИЯ ЗА ПРЕДЕЛАМИ КЛАССА! +function inik2cfg(){ + + global $k2; + + if (!isset($k2)){ + $k2=new k2cfg(); + + // Для совместимости с предыдущими версиями + $GLOBALS['k2cfg']=$k2; + //$GLOBALS['k2']=$k2; + + $k2->init(); + $k2->show(); + + // Для совместимости с предыдущими версиями + $GLOBALS['k2sys']=$k2->sys; + } + + +} + + +function inik2cfg_cmd(){ + + global $k2; + + if (!isset($k2)){ + $k2=new k2cfg(); + + // Для совместимости с предыдущими версиями + $GLOBALS['k2cfg']=$k2; + + $k2->init_cmd(); + + } + +} + diff --git a/k2shop/k2shop/app/sys/k2const.php b/k2shop/k2shop/app/sys/k2const.php new file mode 100644 index 0000000..b86c105 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2const.php @@ -0,0 +1,31 @@ +db->query($sqlQuery) as $row) { + $constValue = $row['const_value']; + } + + return $constValue; + } + +} + diff --git a/k2shop/k2shop/app/sys/k2cont.php b/k2shop/k2shop/app/sys/k2cont.php new file mode 100644 index 0000000..91c8b1e --- /dev/null +++ b/k2shop/k2shop/app/sys/k2cont.php @@ -0,0 +1,1104 @@ + + $(document).ready(function () { + + $("body").on("click", "#content-update_{contentid}", function(e) { + //console.log(4534654654); + // Получаем ID редактируемого элемента + myId = $(this).attr("id"); + ClassArr = myId.split("_"); + e.preventDefault(); + + $.ajax({ + url: "/?comp=k2edit&temp=ajax", + type: "GET", + data: {action : "edit", item_id : ClassArr[1]}, + success: function (data) { + $("body").append(data); + location.href="#popup_contentupdate"; + + }, + error: function () { + alert("Ошибка!"); + } + }); + }); + // Разобраться чтобы событие не отвязывалось. Пока так + $("body").on("click", ".close1", function(e) { + location.reload(true); + }); + }); + '; + public $short_tpl = ''; + public $full_tpl = ''; + public $above_tpl = '
{short_tpl}
'; + + + public $image_path = ''; + + public $articles_arr = ['stati','novosti','articles']; + + public $editScript = ' + '; + + protected function init_obj(){ + global $k2; + + $this->getProjectData(); // Присваиваем значения свойствам, отвечающим за многодоменность + + //$this->getIncArea(); + } + + + public function getEditButton($contentId) { + global $k2; + + $ico = $k2->ico->edit_content(); + + $buttonLink = "Редактировать"; + $ajaxSrtipt = $this->ajaxScript; + $ajaxSrtipt = str_replace('{contentid}', $contentId, $ajaxSrtipt); + + return $buttonLink.$ajaxSrtipt; + } + + /** + * Возвращает текущий язык, установленный в системе + * @global type $k2 + * @return string + */ + public function getCurrentLang() { + global $k2; + + return $currentLang = $k2->lng; + } + + /** + * Получает и возвращает язык из строки запроса, если таковой указан + * @global type $k2 + * @return boolean + */ + public function getLang() { + global $k2; + + if( $k2->get('lang') ){ + return trim( $k2->get('lang') ); + } else { + return false; + } + } + + /** + * Возвращает нужный идентификатор языка для контента + * @return type string + */ + public function getContentLang() { + + $currentLang = $this->getCurrentLang(); + $isLangInGet = $this->getLang(); + + if($isLangInGet) { + return $isLangInGet; + } else { + return $currentLang; + } + } + + + + /** + * Парсит название компоненты, отвечающей за вывод полного контента + * @param type $contentShowComponent - string + * @return type array - массив из двух элементов - названия компоненты и команды + */ + private function getContentShowCompontentParts($contentShowComponent) { + + $componentPartsArray = explode('_', $contentShowComponent); + + return $componentPartsArray; + } + + /** + * Проверяет существует ли текущий домен в БД + * @return mixed. Если запись найдена - отдает sideid (integer) если нет - false (boolean) + */ + public function isDomainExist($domainName) { + global $k2; + + $sqlQuery = 'SELECT siteid AS siteID FROM k2sites WHERE domainname ="'.$domainName.'"'; + + foreach ($k2->db->query($sqlQuery) as $siteItem) { + $siteId = $siteItem['siteID']; + } + + if ( !empty($siteId) ) { + return $siteId; + } else { + return false; + } + + } + + /** + * Проверяет существует ли текущий домен в БД как алиас + * @return mixed. Если запись найдена - отдает sideid (integer) если нет - false (boolean) + */ + public function isAliasExist($domainName) { + global $k2; + + $sqlQuery = 'SELECT domainname AS domainName FROM k2sites WHERE site_alias LIKE "%'.$domainName.'%"'; + + foreach ($k2->db->query($sqlQuery) as $siteItem) { + $domainName = $siteItem['domainName']; + } + + if ( !empty($domainName) ) { + return $domainName; + } else { + return false; + } + + } + + /** + * Формирует массив алиасов для сайта с указанным ID + * @param type $siteId integer - ID сайта + * @return type array - массив алиасов + */ + private function getSiteAliasesArray($siteId) { + + global $k2; + + $sqlQuery = 'SELECT site_alias AS siteAliasList + FROM k2sites + WHERE siteid ='.$siteId; + + foreach ($k2->db->query($sqlQuery) as $aliasesField) { + $siteAliases = $aliasesField['siteAliasList']; + } + + $siteAliasesArray = explode ("\n", $siteAliases); + + return $siteAliasesArray; + + } + + /** + * Отдает имя домена, анализируя его алиасы + * @return type string + */ + public function getSiteName() { + global $k2; + + $domainName = $k2->domain(); + + if ( $this->isDomainExist($domainName) ) { + + return $domainName; + } else { + $DomainNameByAlias = $this->isAliasExist($domainName); + + if (!empty($DomainNameByAlias) ) { + + return $DomainNameByAlias; + } else { + return ''; + } + } + } + + /** + * Парсит название текущего домена и присваивает значения публичным свойствам + */ + public function getProjectData() { + global $k2; + + // Получаем имя текущего домена c учетом возможности существования алиасов + $siteName = $this->getSiteName(); + + $domainArray = explode('.', $siteName); + + $sqlQuery = 'SELECT p.projid AS projectID, s.siteid AS siteID, s.langid AS langID + FROM k2proj AS p + + LEFT JOIN k2sites AS s + ON p.projid = s.projid + + WHERE s.domainname ="'.$siteName.'" AND p.proj_active = 1 AND s.site_active = 1'; + + + + foreach ($k2->db->query($sqlQuery) as $projectData) { + //$k2->site->siteid = $projectData['siteID']; + //$k2->site->projid = $projectData['projectID']; + $this->currentProjectID = $projectData['projectID']; + $this->currentSiteID = $projectData['siteID']; + $this->currentLangID = $projectData['langID']; + } + + } + /** + * Получение записей из БД с учетом всех заданных параметров + * @param type $recordsNumber integer Необходимое количество записей + * @param type $parentContent string Тип контента (page, news) + * @param type $command string Знаение поля command для получения нужной записи + * @param type $contentId integer Значение поля commentid для получения нужной записи + * @param type $start integer Значение поля commentid для получения нужной записи + * @return array Массив записей. + */ + public function getRecords($recordsNumber = '', $parentContent = '', $command = '', $contentId = '', $notid = '', $start=0, $currentLang = '') { + global $k2; + + $recordsArray = []; + + if ($currentLang == ''){ + $currentLang = $k2->lng; + } + + + // Для текущего проекта нет контента в таблице k2content +// if($this->currentProjectID == NULL) { +// return []; +// } + + $contentLanguage = $this->getContentLang(); //Определяем необходимый язык для контента + //$whereCondition = '((c.lgparentid is null) OR (c.lgparentid=0) or 1=1) '; + $whereCondition = '1=1 '; + $limitCondition = $recordsNumber; + $sortOrder = 'c.create_datetime DESC, c.ordnum DESC'; + + // Если запрошена определенная страница с определенной command + if ( $command <> '' ) { + $whereCondition .= 'AND c.command ="'.$command.'"'; + } + + + if ( $contentId <> '' ) { + $whereCondition .= 'AND c.contentid ="'.$contentId.'"'; + } + + if ( $notid <> '' ) { + $whereCondition .= ' AND c.contentid <>"'.$notid.'" AND c.lang = "'.$contentLanguage.'" '; + } + if ( $start <> 0 ) { + $limitCondition = "$start, $recordsNumber"; + } + + $sqlQuery = 'SELECT c.contentid, c.content, c.title, c.descript, c.keywords, c.h1, c.usercreate, c.slug, + c.short_description, c.image_min, c.image, c.create_datetime, c.command, c.parentcontent, c.ordnum, + IFNULL(tr.contentid,c.contentid) as contentid_tr, + IFNULL(tr.h1,c.h1) as h1_tr, + IFNULL(tr.title,c.title) as title_tr, + IFNULL(tr.descript,c.descript) as descript_tr, + IFNULL(tr.keywords,c.keywords) as keywords_tr, + IFNULL(tr.short_description,c.short_description) as short_description_tr, + IFNULL(tr.content,c.content) as content_tr + FROM k2content AS c + LEFT JOIN k2content AS tr + ON (c.contentid = tr.lgparentid) AND (tr.lang="'.$currentLang.'") + WHERE '.$whereCondition.' AND c.active = 1 AND (c.lang="'.$currentLang.'") + ORDER BY '.$sortOrder.' + LIMIT '.$limitCondition; + //print_r ($sqlQuery); + /*AND (c.lang="'.$currentLang.'") */ + /*if ( $notid <> '' ) { + print_r($sqlQuery); + }*/ + + try { + foreach ($k2->db->query($sqlQuery) as $record) { + array_push($recordsArray,$record); + } + }catch (Exception $e) { + echo "Ошибка : ".$e->getMessage()."\n"; + } + + return $recordsArray; + } + /** + * Получение количество записей из БД с учетом всех заданных параметров + * @param type $parentContent string Тип контента (page, news) + * @param type $command string Знаение поля command для получения нужной записи + * @param type $contentId integer Значение поля commentid для получения нужной записи + * @return array Массив записей. + */ + public function getRecordsCol( $parentContent = '', $command = '', $contentId = '', $notid = '') { + global $k2; + + $recordsArray = []; + + $currentLang = $k2->lng; + + $contentLanguage = $this->getContentLang(); //Определяем необходимый язык для контента + //$whereCondition = '((c.lgparentid is null) OR (c.lgparentid=0)) '; + $whereCondition = '1=1 '; + $sortOrder = 'contentid DESC'; + + // Если запрошена определенная страница с определенной command + if ( $command <> '' ) { + $whereCondition .= 'AND c.command ="'.$command.'"'; + } + + + if ( $contentId <> '' ) { + $whereCondition .= 'AND c.contentid ="'.$contentId.'"'; + } + + if ( $notid <> '' ) { + $whereCondition .= ' AND c.contentid <>"'.$notid.'" AND c.langid = "'.$contentLanguage.'" '; + } + + $sqlQuery = 'SELECT COUNT(c.contentid) as p_num + FROM k2content AS c + LEFT JOIN k2content AS tr + ON (c.contentid = tr.lgparentid) AND (tr.langid="'.$currentLang.'") + WHERE '.$whereCondition.' AND (c.lang="'.$currentLang.'") AND c.active = 1 AND (c.lang="'.$currentLang.'")'; + + try { + foreach ($k2->db->query($sqlQuery) as $record) { + array_push($recordsArray,$record); + } + }catch (Exception $e) { + echo "Ошибка : ".$e->getMessage()."\n"; + } + + return $recordsArray; + } + + /** + * Получение записей из БД с учетом всех заданных параметров + * @param type $recordsNumber integer Необходимое количество записей + * @param type $parentContent string Тип контента (page, news) + * @param type $command string Знаение поля command для получения нужной записи + * @param type $contentId integer Значение поля commentid для получения нужной записи + * @return array Массив записей. + */ + public function getRecord($recordsNumber, $parentContent, $command, $contentId) { + global $k2; + + $recordsArray = []; + + $currentLang = $k2->lng; + + // Для текущего проекта нет контента в таблице k2content + // if($this->currentProjectID == NULL) { + // return []; + // } + + $contentLanguage = $this-> getContentLang(); //Определяем необходимый язык для контента + $whereCondition = '((c.lgparentid is null) OR (c.lgparentid=0)) '; + $limitCondition = $recordsNumber; + $sortOrder = 'contentid DESC'; + + // Если запрошена определенная страница с определенной command + if ( $command <> '' ) { + $whereCondition .= 'AND c.command ="'.$command.'"'; + } + + if ( $contentId <> '' ) { + $whereCondition .= 'AND c.contentid ="'.$contentId.'"'; + } + + $sqlQuery = 'SELECT c.contentid, c.content, c.image, c.create_datetime, c.usercreate, c.title, c.descript, c.keywords, c.h1, c.short_description, c.command, + IFNULL(tr.contentid,c.contentid) as contentid_tr, + IFNULL(tr.h1,c.h1) as h1_tr, + IFNULL(tr.title,c.title) as title_tr, + IFNULL(tr.descript,c.descript) as descript_tr, + IFNULL(tr.keywords,c.keywords) as keywords_tr, + IFNULL(tr.short_description,c.short_description) as short_description_tr, + IFNULL(tr.content,c.content) as content_tr + FROM k2content AS c + LEFT JOIN k2content AS tr + ON (c.contentid = tr.lgparentid) AND (tr.langid="'.$currentLang.'") + WHERE '.$whereCondition.' + ORDER BY '.$sortOrder.' + LIMIT '.$limitCondition; + + try { + foreach ($k2->db->query($sqlQuery) as $record) { + array_push($recordsArray,$record); + } + }catch (Exception $e) { + echo "Ошибка : ".$e->getMessage()."\n"; + } + + return $recordsArray; + } + + function getIncArea() + { + global $k2; + + $rez = ''; + + $parentContent = $this->contentType; // Какой контент получать из базы + $template = $this->contentTemplate; // Шаблон + $command = $this->contentCommand; // Конкретная страница + $contentId = $this->contentId; // Конкретный ID записи + $contentComponent = $this->contentShowCompontent; // Компонента для показа полной записи + $recordsArray = $this->getRecord(12, $parentContent, $command, $contentId); + + //if( ($k2->auth->isAdmin()) && ($k2->auth->isDesignMode()) ) { + foreach ($recordsArray as $key => $record) { + array_push($this->pageInc, $record); + } + + //} + } + + /** + * Формирование html для вывода с учетом всех параметров + * @param type $recordsNumber Integer Необходимое количество записей. По умолчанию =1 + * @return string Готовый html + */ + public function showContent ($recordsNumber = 1) { + global $k2; + + $rez = ''; + + $parentContent = $this->contentType; // Какой контент получать из базы + $template = $this->contentTemplate; // Шаблон + $command = $this->contentCommand; // Конкретная страница + $contentId = $this->contentId; // Конкретный ID записи + $contentComponent = $this->contentShowCompontent; // Компонента для показа полной записи + if ($this->recordsNum !== ''){ + $recordsNumber = $this->recordsNum; + } + + $componentArray = $this->getContentShowCompontentParts($contentComponent); + + //Формируем массив записей согласно заданным условиям + $recordsArray = $this->getRecords($recordsNumber, $parentContent, $command, $contentId); + + if (count($recordsArray) == 0) { + $recordsArray = $this->getRecords($recordsNumber, $parentContent, $command, $contentId, '', 0, 'ru'); + } + + + //Проверяем на правильность подключения компоненты + if( count($recordsArray) < 1 ) { + //return 'Нет контента!'; + return ''; + } else { + foreach ($recordsArray as $key => $record) { + + if( ($this->edit) && ($k2->auth->isAdmin()) && ($k2->auth->isDesignMode()) ) { + $rez.= $this->getEditButton($record['contentid_tr']); + + } + + $rez.= $this->contentTemplate; + + // Заменяем содержимое тегов {} + if ( $this->pageHeaderLink ) { + + $rez = str_replace('{header}', ''.$record['h1_tr'].'', $rez); + } else { + $rez = str_replace('{header}', $record['h1_tr'], $rez); + } + + if($this->pageShortDescriptionLink) { + $rez = str_replace('{short_description}', ''.$record['short_description_tr'].'', $rez); + } else { + $rez = str_replace('{short_description}', $record['short_description'], $rez); + } + //setlocale(LC_TIME, "fi_FI"); + //$create_datetime = date("d F Y ", strtotime($record['create_datetime'])); + + $create_datetime = date("d.m.Y ", strtotime($record['create_datetime'])); + $image_min = $record['image_min']; + $image = $record['image']; + + $pos = strpos($image_min, '.'); + + if (!$pos) { + $image_min = $record['image_min'].'default.jpg'; + } + + $pos = strpos($image, '.'); + + if (!$pos) { + $image = $record['image'].'default.jpg'; + } + + if ($record['slug'] !== '' && $record['slug'] !== null ) { + $rez = str_replace('{slug}', $record['slug'], $rez); + } else { + $rez = str_replace('{slug}', '{contentid}', $rez); + } + + $rez = str_replace('{content}', $record['content_tr'], $rez); + $rez = str_replace('{keywords}', $record['keywords_tr'], $rez); + $rez = str_replace('{usercreate}', $record['usercreate'], $rez); + $rez = str_replace('{create_datetime}', $create_datetime, $rez); + $rez = str_replace('{image_min}', $image_min, $rez); + $rez = str_replace('{title}', $record['title'], $rez); + $rez = str_replace('{image}', $image, $rez); + $rez = str_replace('{contentid}', $record['contentid'], $rez); + $rez = str_replace('{command}', $record['command'], $rez); + + //content comments + //$comment = $k2->ins_comp('k2comment','make'); + //$rez = str_replace('{commentbtn}', $comment->commentTpl($contentId), $rez); + //$rez = str_replace('{comments}', '

Комментарии:

'.$comment->getComments($contentId), $rez); + + //content rating + +// $incrate = $k2->ins_comp('k2rate','void'); +// $rez = str_replace('{rating}', $incrate->showRatings($contentId), $rez); + + + + $rez = str_replace('{parentcontent}', $record['parentcontent'], $rez); + + if ($this->is_item) { + if ($record['title'] !== '' && $record['title'] !== null ) { + $k2->site->title = $record['title']; + } + if ($record['keywords'] !== '' && $record['keywords'] !== null) { + $k2->site->keywords = $record['keywords']; + } + + if ($record['descript'] !== '' && $record['descript'] !== null ) { + $k2->site->description = $record['descript']; + } + + $k2->site->pageimage = $k2->proto.'://'.$k2->domain().'/'.$image; + } + + + //$this->updateSlug($record['contentid'], $record['title']); + + } + } + + //var_dump($_POST); + + return $rez; + } + + + + + function sumTpl() + { + global $k2; + $rez = $this->showContent(); + $rez = $this->parsing($rez); + $arr_rep = $k2->site->getDecodedTags('other'); + + + foreach ($arr_rep as $key=>$value) { + $arr_cont = explode('_',$value); + $count = $arr_cont[1]; + if(!$count){ + $count = 12; + } + $records = $this->getRecords($count, $arr_cont[0], $arr_cont[0], '', $k2->get('item')); + foreach ($records as $record) { + $this->contentTemplate = $this->short_tpl; + $this->contentId = $record['contentid']; + $short .= $this->showContent(); + } + + $rez = str_replace($key, $short, $rez); + + } + + + return $rez; + } + + + function parsing($html){ + global $k2; + $strtp = $html; + + $pos = 0; + $tag = $k2->site->getTagValue('{', '}', $strtp); + array_push($k2->site->tag_comp,$tag); + + while (trim($strtp) <> '') { + + $tag = $k2->site->getTagValue('{', '}', $strtp); + + if (trim($tag)<>''){ + array_push($k2->site->tag_comp,$tag); + } + + } + return $html; + + } + + // Получить h1 страницы напрямую по command c учетом языка перевода + function getContsTitleByCommand($command){ + global $k2; + + $currentLang = $k2->lng; + $sqlQuery = "SELECT c.title, + c_tr.k2menuitemid AS k2menuitemid_tr, c_tr.caption AS menuitemname_tr, + IFNULL(c_tr.caption,c.caption) as caption + + FROM k2menuitems c + + LEFT JOIN k2menuitems c_tr + ON (c.k2menuitemid = c_tr.lgparentid) + AND (c_tr.langid='".$k2->lng."') + + WHERE((c.lgparentid is null) OR (c.lgparentid='0')) AND (c.active = '1') AND (c.parentid='0') AND (c.command = '".$command."') "; + + + foreach ($k2->db->query($sqlQuery) as $row) { + $rez = $row['title']; + } + + return $rez; + } + + // Получить h1 страницы напрямую по command c учетом языка перевода + function getPageTitleByCommand($command){ + global $k2; + + $currentLang = $k2->lng; + + $sqlQuery = "SELECT c.h1, tr.h1, + IFNULL(tr.h1,c.h1) as h1_tr + FROM k2content AS c + LEFT JOIN k2content AS tr + ON (c.contentid = tr.lgparentid) AND (tr.langid='".$currentLang."') + WHERE ((c.lgparentid is null) OR (c.lgparentid=0)) AND c.command = '".$command."'"; + + foreach ($k2->db->query($sqlQuery) as $row) { + $rez = $row['h1_tr']; + } + + return $rez; + } + + // Получить h1 страницы напрямую по ID + function getPageTitleById($itemid){ + global $k2; + + $sqlQuery = 'SELECT h1 AS main_header FROM k2content WHERE contentid="'.$itemid.'" AND lang="'.$k2->lng.'"'; + + + foreach ($k2->db->query($sqlQuery) as $row) { + $rez = $row['main_header']; + } + + return $rez; + } + + // Получить title страницы напрямую по ID + function getTitleById($itemid){ + global $k2; + + $sqlQuery = 'SELECT title AS main_header FROM k2content WHERE contentid="'.$itemid.'" AND lang="'.$k2->lng.'"'; + + + foreach ($k2->db->query($sqlQuery) as $row) { + $rez = $row['main_header']; + } + + return $rez; + } + + + /** + * определение contentid по slug + * @global type $k2 + * @param type $slug + * @return type + */ + function getIdBySlug($slug){ + global $k2; + + $sqlQuery = 'SELECT contentid FROM k2content WHERE slug="'.$slug.'" AND lang = "'.$k2->lng.'"'; + + try { + foreach ($k2->db->query($sqlQuery) as $row) { + $rez = $row['contentid']; + } + }catch (Exception $e) { + echo "Ошибка : ".$e->getMessage()."\n"; + } + + return $rez; + } + /** + * Получает запись из таблицы k2conten по ID + * @param type $itemId + * @return array + */ + public function getItemContentById($itemId) { + global $k2; + + $contenItemsArray = []; + + $sqlQuery = 'SELECT * FROM k2content WHERE contentid="'.$itemId.'" LIMIT 1'; + try { + foreach ($k2->db->query($sqlQuery) as $row){ + array_push($contenItemsArray, $row); + } + } catch (PDOException $e) { + echo "Ошибка: $sqlQuery\n"; + echo $e->getMessage(); + } + + + return $contenItemsArray; + } + + /** + * Получаем из БД запись по $command и текущему проекту, домену и языку + * @param type $command - string + * @return array массив данных о найденной записи + */ + public function getItemContentByCommand($command) { + global $k2; + + $contenItemsArray = []; + + $currentLang = $k2->lng; + + $sqlQuery = 'SELECT * FROM k2content WHERE command="'.$command.'" AND projid = "'.$this->currentProjectID.'" AND siteid ="'.$this->currentSiteID.'" AND lang="'.$currentLang.'" LIMIT 1'; + + try { + foreach ($k2->db->query($sqlQuery) as $row){ + array_push($contenItemsArray, $row); + } + + } catch (PDOException $e) { + echo "Ошибка: $sqlQuery\n"; + echo $e->getMessage(); + } + + if ($contenItemsArray == []) { + if (substr($command, -1) !== '-') { + //$this->createItemDueCommand($command); + } + } + + return $contenItemsArray; + } + + public function escapequpted($content){ + + return str_replace('"','\"', $content); + } + + public function updateOnlyContent($itemId) { + + global $k2; + + $currentLang = $k2->lng; + + if($itemId <> '') { + $sqlQuery = 'UPDATE k2content SET content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('full_content'))).'" WHERE contentid ='.$itemId; + } + + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + } + + public function deleteContent($itemId) { + + global $k2; + + $currentLang = $k2->lng; + + if($itemId <> '') { + $sqlQuery = 'UPDATE k2content SET active="0" WHERE contentid = "'.$itemId.'" '; + } + + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + } + + /** + * Обновение записи с указанным ID в БД + * @param type $itemId integer - ID записи + */ + public function updateItem($itemId = '', $itemCommand = '') { + global $k2; + + $currentLang = $k2->lng; + + if($itemId <> '') { + $sqlQuery = 'UPDATE k2content SET title ="'.$k2->post('meta_title').'", descript="'.$k2->post('meta_description').'", keywords="'.$k2->post('meta_keywords').'", content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('full_content'))).'", h1="'.$k2->post('h1_header').'", short_description="'.$k2->post('short_description').'" WHERE contentid ="'.$itemId.'" '; + } + + if ($itemCommand <> '') { + $sqlQuery = 'UPDATE k2content SET title ="'.$k2->post('meta_title').'", descript="'.$k2->post('meta_description').'", keywords="'.$k2->post('meta_keywords').'", content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('full_content'))).'", h1="'.$k2->post('h1_header').'", short_description="'.$k2->post('short_description').'" + WHERE command ="'.$itemCommand.'" AND projid = "'.$this->currentProjectID.'" AND siteid ="'.$this->currentSiteID.'" AND langid="'.$currentLang.'"'; + } + + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + } + + /** + * Проверяет есть ли в БД запись с заданной command и относящейся к активным проекту и домену + * с языком по умолчанию + * @param type $command - string + * @return boolean + */ + public function isItemExist($command) { + global $k2; + + $result = false; + + $sqlQuery = 'SELECT command AS command FROM k2content WHERE command ="' . $command . '" AND projid = "'.$this->currentProjectID.'" AND siteid ="'.$this->currentSiteID.'" AND langid="'.self::DEFAULT_LANGUAGE_ID.'"'; + + foreach ($k2->db->query($sqlQuery) as $record) { + if ($record) { + $result = true; + } + } + + return $result; + } + + /** + * получение комментарий к объекту + * @global type $k2 + * @param type $objectid + * @return array + */ + function getComments($objectid = '') + { + global $k2; + + $sql = 'SELECT contentid FROM k2content WHERE objectid = "'.$objectid.'" '; + $arr_comment = []; + try { + foreach ($k2->db->query($sql) as $row) { + $comment = $this->getRecords('','','',$contentid); + array_push($arr_comment,$comment); + } + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + + return $arr_comment; + } + + /** + * получение max ordnum + * @global type $k2 + * @return type + */ + function getMaxOrdnum($command) + { + global $k2; + + $result = false; + + $sqlQuery = 'SELECT MAX(ordnum) AS ordnum FROM k2content WHERE command ="' . $command . '" '; + + try { + foreach ($k2->db->query($sqlQuery) as $row) { + $rez=$row['ordnum']; + } + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + + return $rez; + } + + /** + * Создает запись с заданной command и данными о текущем проекте и сайте в БД и языке по умолчанию + * @param type $command string + */ + public function addItemCommand($command, $image_path = '') { + global $k2; + $path = '/public/img/'; + $CurrentLang = $this->getCurrentLang(); + $title = $k2->post('caption'); + $slug = $k2->sys->str2url($title); + $descript = $k2->post('descript'); + $keywords = $k2->post('keywords'); + $content = $k2->post('content'); + $h1 = $k2->post('h1'); + $ordnum = $k2->post('ordnum'); + //$command = 'news'; + $create_datetime = date('Y-m-d H:i:s'); + $contentid = rand(1,9).$this->getID(); + $image = $path.$k2->post('image'); + $image_min = $path.$k2->post('image'); + $short_descr = $k2->post('short_description'); + $usercreate = $k2->auth->login; + $script= $k2->post('script'); + $sqlQuery = 'INSERT INTO k2content ( + contentid, title, slug, create_datetime, command, descript, keywords, content, short_description, image, image_min, script, h1, lang, projid, siteid, langid, lgparentid, active, usercreate, ordnum) + VALUES( + "'.$contentid.'", + "'.$this->escapequpted(htmlspecialchars_decode($title)).'", + "'.$slug.'", + "'.$create_datetime.'", + "'.$this->escapequpted(htmlspecialchars_decode($command)).'", + "'.$this->escapequpted(htmlspecialchars_decode($descript)).'", + "'.$keywords.'", + "'.$this->escapequpted(htmlspecialchars_decode($content)).'", + "'.$this->escapequpted(htmlspecialchars_decode($short_descr)).'", + "'.$this->escapequpted(htmlspecialchars_decode($image)).'", + "'.$this->escapequpted(htmlspecialchars_decode($image_min)).'", + "'.$this->escapequpted(htmlspecialchars_decode($script)).'", + "'.$this->escapequpted(htmlspecialchars_decode($h1)).'", + "'.$CurrentLang.'", + "'.$this->currentProjectID.'", + "'.$this->currentSiteID.'", + "'.self::DEFAULT_LANGUAGE_ID.'", + "'.self::DEFAULT_PARENT_LANGUAGE_ID.'", + "1", + "'.$usercreate.'", + "'.$ordnum.'" + )'; + + try { + $k2->db->exec($sqlQuery); + $rez = 1; + } catch (PDOException $e) { +// echo "Ошибка вставки информации о контакте: $sqlQuery\n"; +// echo $e->getMessage(); + $rez = 0; + } + return $rez; + } + + /** + * генерация slug для отображения в URL + * @global type $k2 + * @param type $itemId + * @param type $title + */ + public function updateSlug($itemId, $title) { + + global $k2; + + + $slug = $k2->sys->str2url($title); + + if($itemId <> '') { + $sqlQuery = 'UPDATE k2content SET slug="'.$slug.'" WHERE contentid ="'.$itemId.'" '; + } + + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки: $sqlQuery\n"; + echo $e->getMessage(); + } + } + + /** + * Создает запись с заданной command и данными о текущем проекте и сайте в БД и языке по умолчанию + * @param type $command string + */ + public function createItemDueCommand($command, $objectid = '') { + global $k2; + + $CurrentLang = $this->getCurrentLang(); + $contentid = $this->getID(); + + $sqlQuery = 'INSERT INTO k2content (contentid, title, command, lang, projid, siteid, langid, lgparentid, content, active) + VALUES("'.$contentid.'","Включаемая область '.$command.'","'.$command.'","'.$CurrentLang.'","'.$this->currentProjectID.'","'.$this->currentSiteID.'","'.$CurrentLang.'","'.self::DEFAULT_PARENT_LANGUAGE_ID.'","empty","1")'; + + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + } +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2content.php b/k2shop/k2shop/app/sys/k2content.php new file mode 100644 index 0000000..ecdcc06 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2content.php @@ -0,0 +1,207 @@ +ico->edit_content(); + + if ($k2->get('p')<>''){ + $p='&p='.trim($k2->get('p')); + }else{ + $p=''; + } + + return "Редактировать"; + } + + // Кнопки для администрирования + function admButtons(&$html){ + global $k2; + + if (($k2->auth->isAdmin()) and ($k2->auth->isDesignMode())){ + //$btn=$this->editLinks(); + }else{ + $btn=''; + } + + $html=str_replace('{edit}', $btn, $html); + } + + + // Выполняет команды + function command(){ + global $k2; + $rez = ''; + $command = ''; + + + $userid = $k2->auth->userid; + $isactive = $k2->auth->isActiveUserid($userid); + if ($k2->auth->isAuth() && $isactive !== '1') { + header ('Location: /?p=unlogin'); + } + + + if ($k2->get('p')=='auth'){ + $authform = $k2->ins_comp('k2auth','form'); + //$rez.=$authform->content(); + + $rez .= str_replace('{content}', $authform->content(), $this->template); + + } elseif ($k2->get('p')=='unlogin'){ // Выход из авторизации + $k2->auth->unLogin(); + header ('Location: /'); + + + }elseif ($k2->get('p')=='install'){ //install + $install = $k2->ins_comp('k2install'); + $rez = $install->content(); + + }elseif ($k2->get('p')=='api'){ //install + $api = $k2->ins_comp('k2api'); + $rez = $api->content(); + + } elseif (($k2->get('p')=='reg')or($k2->get('p')=='registered')or($k2->get('p')=='remember')){ + $authform = $k2->ins_comp('k2auth','regform'); + //$rez.=$authform->content(); + + $rez .= str_replace('{content}', $authform->content(), $this->template); + + // Показываем пункты меню + } elseif ( $k2->get('menu-item_id') <> '') { + $menu = $k2->ins_comp('k2menu'); + $cont = $menu->getMenuContent( $k2->get('menu-item_id') ); + $rez .= str_replace('{content}', $cont, $this->template); + } elseif ( $k2->get('p')) { + $menu = $k2->ins_comp('k2menu'); + $cont = $menu->getMenuContent( '', $k2->get('p') ); + $rez .= str_replace('{content}', $cont, $this->template); + } + + else{ // Вывод контента + $cont = $this->getContent(false); + $isscript = (!$k2->isRoot() and trim($k2->get('p'))==''); + + $rez .= str_replace('{content}', $cont, $this->template); + + + // Выполнение скрипта + if (!$isscript and trim($this->page->script)<>''){ + + $scr = explode(",", $this->page->script); + $compname = $scr[0]; + + // Команда + if (count($scr)>2){ + $command=$scr[2]; // ф-ция, которую вызываем + } + + // Шаблон + if (count($scr)>1){ + $temp=$scr[1]; // Шаблон + }else{ + $temp=''; // Компонента + } + + $comp = $k2->ins_comp($compname, $temp); + + // Вызов фцнкции + if (trim($command)==''){ + $rez.=$comp->content(); + }else{ + eval("\$rez.=\$comp->".$command.";"); + } + + } + + } + + $this->admButtons($rez); + return $rez; + } + + // Редактирование + function edit(){ + global $k2; + $k2->edit=$k2->ins_comp('k2editor'); + $k2->edit->show(); + } + + // Добавление + function add(){ + global $k2; + $k2->edit=$k2->ins_comp('k2editor'); + $k2->edit->show(); + } + + // Удаление + function del(){ + global $k2; + $k2->edit=$k2->ins_comp('k2editor'); + $k2->edit->show(); + } + + // Выполнение операции с контентом + function oper(){ + global $k2; + + $rez = ''; + $c = $k2->get('c'); + + if ($c == 'edit'){ // Редактировать элемент + $rez = $this->edit(); + }elseif ($c == 'add'){ // Добавить элемент + $rez = $this->add(); + }elseif ($c == 'del'){ // Удалить элемент + $rez = $this->del(); + } + + return $rez; + } + + + // Выводит контент + function content(){ + global $k2; + + $cont = ''; + $rez = ''; + $c = $k2->get('c'); + + if (trim($c) == ''){ + $rez = $this->command(); + }else{ + $rez = $this->oper(); + } + + if ($k2->get('comp')<>''){ // Реализация вызова компонент + $cmp = $k2->ins_comp($k2->get('comp')); + $rez = $cmp->content(); + } + + return $rez; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2edit.php b/k2shop/k2shop/app/sys/k2edit.php new file mode 100644 index 0000000..41f7382 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2edit.php @@ -0,0 +1,924 @@ + + + + + '; + + public $catli_tpl = ' +
  • +
    {menuitemname}
    +
      + {sub} +
    +
  • + '; + public $content_window_tpl = '
    + + +
    + +
    + {cont_block} +
    + + '; + + public $seo_form_tpl = "
    + + + + + + + + + + + + +
    +
    + + +
    +
    +
    "; + + + public $content_form_tpl = "
    + + + + + {add_input} + + + + +
    +
    + + +
    +
    + +
    + + + "; + + public $item_content_el_upd_tpl = "
    +
    + + +
    +
    + + +
    +
    +
    + + + +
    +
    + + +
    "; + + + public $item_content_el_add_tpl = " + + + + + + "; + + + + public $articles_arr = ['stati','novosti','articles']; + /** + * Формируем выпадающий список для выбора языка документа + * @return type string - готовый код для выпадающего списка. + */ + function getLanguagesSelect() { + global $k2; + + $rez = ''; + + $langSelect = $k2->ins_comp('k2select2'); + + $LanguagesArray = []; + + foreach ($k2->langs as $langKey => $language) { + $LanguagesArray[$langKey] = $language['name']; + } + + $rez.=$langSelect->sel( + ['name' => 'selectedLang', + 'sql' => "", + 'value' => $k2->lng, + 'search_input' => 1, + 'additems' => $LanguagesArray, + ] + ); + + return $rez; + } + + + /** + * Отображает форму для редактирования записи + * @return type string + */ + function showEditForm() { + + global $k2; + + $cont = $k2->ins_comp('k2cont'); + + $itemId = $k2->get('item_id'); // Получаем ID записи из $_GET + + $itemCommand = $k2->get('command'); // Получаем command записи из $_GET + + if ($itemId) { // Задан ID + $itemDataArray = $cont->getItemContentById($itemId); // Получаем контент по ID + + } else if ($itemCommand) { // Указана command + + // Проверить есть ли такая запись в БД. + $dBRecord = $cont->isItemExist($itemCommand); + + // Если записи нет, то создать ее... + if(!$dBRecord) { + $cont->createItemDueCommand($itemCommand); // Создать новую записб в БД + } + + $itemDataArray = $cont->getItemContentByCommand($itemCommand); // Получаем контент по command + } + + // Если была нажата кнопка Submit - обновляем запись в БД. + if ( $k2->post('save_content') == 'submited' ) { + + $cont->updateOnlyContent($k2->post('item_id')); + header("Location: ".'/'); + } + + // иначе просто показываем форму. + else if($itemDataArray) { + $popup = $k2->ins_comp('k2popup'); + $popup->popUpID = 'contentupdate'; + $popup->popupContent = $this->contentupdate; // Указываем какую форму сунуть в окно. + + $rez = $popup->content(); + + //$rez = str_replace('{languageSelect}', $this->getLanguagesSelect(), $rez); + $rez = str_replace('{header}', $itemDataArray[0]['h1'], $rez); + $rez = str_replace('{ShortDescription}', $itemDataArray[0]['short_description'], $rez); + $rez = str_replace('{FullContent}', $itemDataArray[0]['content'], $rez); + $rez = str_replace('{MetaTitle}', $itemDataArray[0]['title'], $rez); + $rez = str_replace('{MetaDescription}', $itemDataArray[0]['descript'], $rez); + $rez = str_replace('{MetaKeywords}', $itemDataArray[0]['keywords'], $rez); + $rez = str_replace('{itemID}', $itemId, $rez); + + + // или не показываем, если нет ID записи в GET + } else { + die('Не указан контент для редактирования!'); + } + + return $rez; + } + public function escapequpted($content){ + + return str_replace('"','\"', $content); + + return str_replace("'","\'", $content); + } + + /** + * + * @global type $k2 + * @return string + */ + function editConent() + { + global $k2; + $rez = ''; + $path = '/public/img/'; + + //$arr_datetime = explode('', $this->escapequpted(htmlspecialchars_decode($k2->post('create_datetime')))); + + $create_datetime = $k2->sys->dateSecure($this->escapequpted(htmlspecialchars_decode($k2->post('create_datetime')))); + $title = $k2->post('caption'); + //print_r($k2->post('caption')); + + if ($title == '') { + $title = $k2->post('title'); + } + if ($k2->post('image')) { + $sqlQuery = 'UPDATE k2content SET + title ="'.$this->escapequpted(htmlspecialchars_decode($title)).'", + descript="'.$this->escapequpted(htmlspecialchars_decode($k2->post('descript'))).'", + image = "'.$this->escapequpted(htmlspecialchars_decode($path.$k2->post('image'))).'", + image_min = "'.$this->escapequpted(htmlspecialchars_decode($path.$k2->post('image'))).'", + keywords="'.$this->escapequpted(htmlspecialchars_decode($k2->post('keywords'))).'", + short_description="'.$this->escapequpted(htmlspecialchars_decode($k2->post('short_description'))).'", + content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('content'))).'", + create_datetime="'.$create_datetime.'", + ordnum = "'.$k2->post('ordnum').'", + h1="'.$this->escapequpted(htmlspecialchars_decode($k2->post('h1'))).'" + + WHERE contentid="'.$k2->post('contentid').'" '; + } else { + + $sqlQuery = 'UPDATE k2content SET + title ="'.$this->escapequpted(htmlspecialchars_decode($title)).'", + descript="'.$this->escapequpted(htmlspecialchars_decode($k2->post('descript'))).'", + keywords="'.$this->escapequpted(htmlspecialchars_decode($k2->post('keywords'))).'", + short_description="'.$this->escapequpted(htmlspecialchars_decode($k2->post('short_description'))).'", + content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('content'))).'", + create_datetime="'.$create_datetime.'", + ordnum = "'.$k2->post('ordnum').'", + h1="'.$this->escapequpted(htmlspecialchars_decode($k2->post('h1'))).'" + + WHERE contentid="'.$k2->post('contentid').'" '; + } + //print_r($sqlQuery); + + + // $r = $k2->sql->upd( + // 'UPDATE k2content + // SET + // title ="'.$this->escapequpted(htmlspecialchars_decode($title)).'", + // descript="'.$this->escapequpted(htmlspecialchars_decode($k2->post('descript'))).'", + // image = "'.$this->escapequpted(htmlspecialchars_decode($path.$k2->post('image'))).'", + // image_min = "'.$this->escapequpted(htmlspecialchars_decode($path.$k2->post('image'))).'", + // keywords="'.$this->escapequpted(htmlspecialchars_decode($k2->post('keywords'))).'", + // short_description="'.$this->escapequpted(htmlspecialchars_decode($k2->post('short_description'))).'", + // content="'.$this->escapequpted(htmlspecialchars_decode($k2->post('content'))).'", + // create_datetime="'.$create_datetime.'", + // ordnum = "'.$k2->post('ordnum').'", + // h1="'.$this->escapequpted(htmlspecialchars_decode($k2->post('h1'))).'" + + // WHERE contentid="'.$k2->post('contentid').'" + // ', + + // [ + // // 'name' => htmlspecialchars(strip_tags($input['name'])), + // // 'login' => htmlspecialchars(strip_tags($input['login'])), + // // 'email' => htmlspecialchars(strip_tags($input['email'])), + // // 'id' => $id + // ] + // ); + + + // if($r['err']!==''){ + // $k2->log->err('Ошибка API: '.$r['err']); + // return; + // } + try { + $k2->db->exec($sqlQuery); + + } catch (PDOException $e) { + echo "Ошибка вставки информации о контакте: $sqlQuery\n"; + echo $e->getMessage(); + } + return $rez; + } + + function getSubMenus($menuid) + { + global $k2; + + + $menuDataArray = []; + $cont = $k2->ins_comp('k2cont'); + + $sql = "SELECT c.k2menuid, c.k2menuitemid, c.parentid, c.active, c.h1, c.hint, c.class, c.content as menuitemcont, + c.command, c.url, c.ord, c.caption AS menuitemname, c.descript, c.title, c.keywords, + c_tr.k2menuitemid AS k2menuitemid_tr, c_tr.caption AS menuitemname_tr, c_tr.content AS menuitemcont_tr, + IFNULL(c_tr.caption,c.caption) as caption, + IFNULL(c_tr.content,c.content) as content + + FROM k2menuitems c + + LEFT JOIN k2menuitems c_tr + ON (c.k2menuitemid = c_tr.lgparentid) + AND (c_tr.langid='".$k2->lng."') + + WHERE (c.k2menuitemid='".$menuid."') AND (c.active='1') AND (c.projid ='".$cont->currentProjectID."') AND (c.siteid = '".$cont->currentSiteID."') AND (c.langid = '".$k2->lng."') "; + + //echo $sql; + foreach ($k2->db->query($sql) as $menuData) { + array_push($menuDataArray, $menuData); + } + + $dec_arr = json_encode($menuDataArray); + + return $dec_arr; + + } + function getSubMenus1($menuid) + { + global $k2; + + + $menuDataArray = []; + $cont = $k2->ins_comp('k2cont'); + + $sql = "SELECT c.k2menuid, c.k2menuitemid, c.parentid, c.active, c.h1, c.hint, c.class, c.content as menuitemcont, + c.command, c.url, c.ord, c.caption AS menuitemname, c.descript, c.title, c.keywords, + c_tr.k2menuitemid AS k2menuitemid_tr, c_tr.caption AS menuitemname_tr, c_tr.content AS menuitemcont_tr, + IFNULL(c_tr.caption,c.caption) as caption, + IFNULL(c_tr.content,c.content) as content + + FROM k2menuitems c + + LEFT JOIN k2menuitems c_tr + ON (c.k2menuitemid = c_tr.lgparentid) + AND (c_tr.langid='".$k2->lng."') + + WHERE (c.k2menuitemid='".$menuid."') AND (c.projid ='".$cont->currentProjectID."') AND (c.siteid = '".$cont->currentSiteID."') AND (c.langid = '".$k2->lng."') "; + + //echo $sql; + foreach ($k2->db->query($sql) as $menuData) { + array_push($menuDataArray, $menuData); + } + + + + return $menuDataArray; + + } + public function getItem($menuDataArray) + { + global $k2; + $cont = $k2->ins_comp('k2cont'); + $cont_arr = $cont->getRecords(1, '', '', $menuDataArray); + $dec_arr = json_encode($cont_arr); + echo $dec_arr; + } + public function getItem1($menuDataArray) + { + global $k2; + $cont = $k2->ins_comp('k2cont'); + $cont_arr = $cont->getRecords(1, '', '', $menuDataArray); + return $cont_arr; + } + + /** + * загрузка фото + * @global type $k2 + * @global type $trans + */ + function uploadPhoto () + { + global $k2; + $rez = ''; + $upload = $k2->ins_comp('k2upload'); + $path = 'public/img/'; + $rez = $upload->simpleUpload($path); + echo $path; + } + + + public function updateMenuItem($menuItemId) { + global $k2; + + $cont = $k2->ins_comp('k2cont'); + + $caption = $k2->post('caption'); + $active = 1; + $projid = $cont->currentProjectID; + $siteid = $cont->currentSiteID; + $langid = $k2->lng; + $title = $k2->post('title'); + $descript = $k2->post('descript'); + $keywords = $k2->post('keywords'); + $content = $k2->post('content'); + $h1 = $k2->post('h1'); + $script= $k2->post('script'); + + + $sqlQuery = 'UPDATE k2menuitems SET caption ="'.$caption.'", projid="'.$projid.'", siteid="'.$siteid.'", langid="'.$langid.'", title="'.$title.'", descript="'.$descript.'", keywords="'.$keywords.'", content="'.$this->escapequpted(htmlspecialchars_decode($content)).'", h1="'.$h1.'", script="'.$script.'" WHERE k2menuitemid="'.$menuItemId.'"'; + + try { + $res=$k2->db->exec($sqlQuery); + + } catch(PDOException $e) { + echo "Can't update menu item: $sqlQuery\n"; + echo $e->getMessage(); + } + } + + /** + * удаление пункта меню + * @global type $k2 + * @param type $menuid + * @return type + */ + function deleteMenu($menuid) + { + global $k2; + $menu = $k2->ins_comp('k2menu'); + $menu->deleteMenuItem($menuid); + return $rez; + } + + /** + * добавление пункта меню + * @global type $k2 + * @param type $menuid + * @return type + */ + function addMenu($menuid) + { + global $k2; + $menu = $k2->ins_comp('k2menu'); + $rez = $menu->createMenuItem($menuid); + return $rez; + } + + function addItem($command) + { + global $k2; + $cont = $k2->ins_comp('k2cont'); + $rez = $cont->addItemCommand($command); + return $rez; + } + + /** + * удаление контента + * @global type $k2 + * @param type $itemid + * @return type + */ + function deleteItem($itemid) + { + global $k2; + $cont = $k2->ins_comp('k2cont'); + $rez = $cont->deleteContent($itemid); + return $rez; + } + + function getArrLinks($mainmenuid) + { + global $k2; + + $rez = ['rez'=>'', 'err'=>'']; + + $r = $k2->sql->sel("SELECT m.k2menuid, m.k2menuitemid, m.parentid, m.caption AS menuitemname + + FROM k2menuitems m + WHERE m.k2menuid = '".$mainmenuid."' AND m.active = 1 AND m.langid='".$k2->lng."' + ORDER BY m.ord + ",[]); + $arr_cat = []; + + if($r['err'] !== ''){ + $k2->log->err('Ошибка: '.$r['err']); + $rez['err'] = $err['err']; + return $rez; + } + //преобразовываем полученнный массив + foreach ($r['data'] as $row){ + if(empty($arr_cat[$row['parentid']])) { + $arr_cat[$row['parentid']] = []; + } + $arr_cat[$row['parentid']][] = $row; + } + + $rez['rez'] = $r['data']; + + + $struct = $this->view_cats($arr_cat); + + + return $struct; + } + + function view_cats($arr, $parent_id = 0) { + global $k2; + $rez = ''; + //Условия выхода из рекурсии + if(empty($arr[$parent_id])) { + return; + } + + for($i = 0; $i < count($arr[$parent_id]);$i++) { + + $rez .= $this->catli_tpl; + + $newid = $arr[$parent_id][$i]['k2menuitemid']; + $sub = ''; + + $count = count($arr[$newid]); + if ($count > 0) { + $sub .= $this->view_cats($arr,$newid,$url); + } else { + + } + $namecat = $arr[$parent_id][$i]['menuitemname']; + //$namecat = mb_strimwidth($arr[$parent_id][$i]['name'], 0, 24); + $rez = str_replace('{menuitemid}', $newid, $rez); + $rez = str_replace('{menuitemname}', $namecat, $rez); + $rez = str_replace('{sub}', $sub, $rez); + } + + return $rez; + } + + function getMenuStruckt() + { + global $k2; + $mainmenuid = $k2->post('meinmenuid'); + $rez = "Структура меню"; + + $rez .= ' + '; + $rez .= + '
    + +
    +
      + '.$this->getArrLinks($mainmenuid).' +
    +
    +
    + + '; + + + return $rez; + } + + + function updateStruckt($menuitemid, $parentid, $ord) + { + global $k2; + echo $menuitemid.'--'.$parentid.'--'.$ord."\n"; + $sqlQuery = 'UPDATE k2menuitems SET parentid="'.$parentid.'", ord="'.$ord.'" WHERE k2menuitemid="'.$menuitemid.'"'; + + try { + $res=$k2->db->exec($sqlQuery); + + } catch(PDOException $e) { + echo "Can't update menu item: $sqlQuery\n"; + echo $e->getMessage(); + } + return $rez; + } + + + function saveMenuStruckt() + { + global $k2; + $struct = $k2->post('struckt_json'); + $arr_struckt = json_decode($struct, true); + //print_r($arr_struckt); + $ord = 1; + foreach ($arr_struckt as $arr1) { + $parentid = 0; + $this->updateStruckt($arr1['id'], $parentid, $ord); + $ord++; + $parentid = $arr1['id']; + foreach ($arr1['children'] as $arr2) { + $parentid = $arr1['id']; + $this->updateStruckt($arr2['id'], $parentid, $ord); + $ord++; + $parentid = $arr2['id']; + foreach ($arr2['children'] as $arr3) { + $parentid = $arr2['id']; + $this->updateStruckt($arr3['id'], $parentid, $ord); + $ord++; + $parentid = $arr3['id']; + foreach ($arr3['children'] as $arr4) { + $parentid = $arr3['id']; + $this->updateStruckt($arr4['id'], $parentid, $ord); + $ord++; + $parentid = $arr4['id']; + foreach ($arr4['children'] as $arr5) { + $parentid = $arr4['id']; + $this->updateStruckt($arr5['id'], $parentid, $ord); + $ord++; + $parentid = $arr5['id']; + } + } + } + } + } + return $rez; + } + + function getForm(){ + global $k2; + $rez=$this->content_window_tpl; + + + $rez = str_replace('{seo_block}', $this->seo_form_tpl, $rez); + $rez = str_replace('{cont_block}', $this->content_form_tpl, $rez); + $command = $k2->get('p'); + $event = $k2->post('action'); + $id = $k2->post('menuid'); + switch ($event) + { + case "update_content": + $data = $this->getSubMenus1($id); + $data = $data[0]; + $rez = str_replace('{add_input}', '', $rez); + $rez = str_replace('{action_form}', 'saveMenuCont("{menuid}")', $rez); + $rez = str_replace('{title}', $data['title'], $rez); + $rez = str_replace('{descript}', $data['descript'], $rez); + $rez = str_replace('{keywords}', $data['keywords'], $rez); + $rez = str_replace('{caption}', $data['caption'], $rez); + $rez = str_replace('{h1}', $data['h1'], $rez); + $rez = str_replace('{short_description}', $data['short_description'], $rez); + $rez = str_replace('{content}', $data['content'], $rez); + //id контента + $rez = str_replace('{menuid}', $id ,$rez); + break; + case "add_content": + + $rez = str_replace('{add_input}', '', $rez); + $rez = str_replace('{action_form}', 'addMenuCont({menuid})', $rez); + //id меню + $rez = str_replace('{menuid}', $id, $rez); + break; + case "update_item": + + $data = $this->getItem1($id); + $command = $data[0]['command']; + + + $data = $data[0]; + $newimg = 1; + if ($data['image'] == '') { + $newimg = 0; + } + + $rez = str_replace('{add_input}', $this->item_content_el_upd_tpl, $rez); + if (in_array($command, $this->articles_arr)) { + + $rez = str_replace('{hidden}', '', $rez); + } else { + + //$rez = str_replace('{hidden}', 'style="display:none"', $rez); + } + + $rez = str_replace('{action_form}', 'saveItemCont("{contentid}", "'.$newimg.'")', $rez); + $rez = str_replace('{title}', $data['title'], $rez); + $rez = str_replace('{descript}', $data['descript'], $rez); + $rez = str_replace('{keywords}', $data['keywords'], $rez); + $rez = str_replace('{caption}', $data['title'], $rez); + $rez = str_replace('{create_datetime}', date('d.m.Y', strtotime($data['create_datetime'])), $rez); + $rez = str_replace('{h1}', $data['h1'], $rez); + $rez = str_replace('{short_description}', $data['short_description'], $rez); + $rez = str_replace('{content}', $data['content'], $rez); + $rez = str_replace('{img}', $data['image'], $rez); + $rez = str_replace('{ordnum}', $data['ordnum'], $rez); + + //id оновленя новин + $rez = str_replace('{contentid}', $id, $rez); + + break; + case "add_item": + $cont = $k2->ins_comp('k2cont'); + $rez = str_replace('{add_input}', $this->item_content_el_add_tpl, $rez); + $rez = str_replace('{action_form}', 'addItem("{comand}")', $rez); + $ordnum = $cont->getMaxOrdnum($id) + 1; + $rez = str_replace('{ordnum}', $ordnum, $rez); + //комада для вставки (news, article...) + $rez = str_replace('{comand}', $id, $rez); + break; + default: + $rez = ''; + } + $rez = str_replace('{add_input}', '', $rez); + $rez = str_replace('{id_form}', '', $rez); + $rez = str_replace('{title}', '', $rez); + $rez = str_replace('{descript}', '', $rez); + $rez = str_replace('{keywords}', '', $rez); + $rez = str_replace('{caption}', '', $rez); + $rez = str_replace('{h1}', '', $rez); + $rez = str_replace('{descript}', '', $rez); + $rez = str_replace('{content}', '', $rez); + $rez = str_replace('{menuid}', '' ,$rez); + + + $rez = $this->Translate($rez); + + return $rez; + } + + function changeMenuView() + { + global $k2; + + $k2menuitemid = $k2->post('menuid'); + $is_admin = $k2->post('is_admin'); + + $val = 1; + if ($is_admin == '1') { + $val = 0; + } + + $sqlQuery = 'UPDATE k2menuitems SET + is_admin = "'.$val.'" + WHERE k2menuitemid="'.$k2menuitemid.'" '; + + try { + $k2->db->exec($sqlQuery); + } catch (PDOException $e) { + echo "Ошибка: $sqlQuery\n"; + echo $e->getMessage(); + } + return $rez; + } + + + function content() { + + global $k2; + + if ($k2->auth->roleid == '43fa9c5e6de98b6993316e95f8d3fbee') { + + } else { + if (!$rez = $k2->auth->isAdmin()) { + die('У Вас нет прав редактировать данный текст!!!'); + } + } + + $event = $k2->get('event'); + switch ($event) + { + case "savecont": + $rez = $this->editConent(); + break; + case "addmenu": + $rez = $this->addMenu($k2->post('menuid')); + break; + case "getmenu": + $rez = $this->getSubMenus($k2->post('menuid')); + break; + case "getitem": + $rez = $this->getItem($k2->post('itemid')); + break; + case "savemenu": + $rez = $this->updateMenuItem($k2->post('menuid')); + break; + case "delmenu": + $rez = $this->deleteMenu($k2->post('menuid')); + break; + case "addcont": + $rez = $this->addItem($k2->post('command')); + break; + case "delcont": + $rez = $this->deleteItem($k2->post('itemid')); + break; + case "uploadphoto": + $rez = $this->uploadPhoto(); + break; + case "menustruck": + $rez = $this->getMenuStruckt(); + break; + case "savemenustruck": + $rez = $this->saveMenuStruckt(); + break; + case "getform": + $rez=$this->getForm(); + break; + case "viewadmin": + $rez=$this->changeMenuView(); + break; + default: + $rez=''; + } + + //$rez = $this->showEditForm(); + + return $rez; + } + + + +} diff --git a/k2shop/k2shop/app/sys/k2editor.php b/k2shop/k2shop/app/sys/k2editor.php new file mode 100644 index 0000000..69fcb84 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2editor.php @@ -0,0 +1,407 @@ + + + + Редактирование + + {script} + + + {content_editor} + + '; + + public $safe_editor=false; // Включать защищенный режим + + + + // Возвращаемся на страницу, откуда пришли + function GoBack($url){ + header ('Location: '.$url); + } + + + // Выводит форму редактора + function formEditor(){ + + global $k2; + + + $script=" + "; + + $html=$this->html_editor; + $html=str_replace('{script}', $script, $html); + + $cont=''; + $title=''; + $description=''; + $short_description=''; + $keywords=''; + $h1=''; + $type=''; + + + $ispost=($k2->post('SaveAndExit')<>'')+($k2->post('Save')<>'')+($k2->post('Cancel')<>''); + + + // Обработка параметров, которые передаются через Post + if ($ispost){ + $backurl=$k2->post('backurl', $this->safe_editor); + $parcont=$k2->post('parcont', $this->safe_editor); + $cont=$k2->post('editor', $this->safe_editor); + $p=$k2->post('p', $this->safe_editor); + + // Сохраняем ключевые слова + $title=$k2->post('title', $this->safe_editor); + $description=$k2->post('description', $this->safe_editor); + $keywords=$k2->post('keywords', $this->safe_editor); + $h1=$k2->post('h1', $this->safe_editor); + + $short_description=$k2->post('short_editor', $this->safe_editor); + + $type=$k2->post('', $this->safe_editor); + + + }else{ + // Обратный адрес возврата + $backurl=$k2->reffer(); + + // Получение контента из компоненты + $parcont=$k2->get('content'); + + + + if ($k2->isRoot()){ + $p='/'; + }else{ + $p=$k2->get('p'); + } + + + + + } + + + + $parcont=str_replace('_', ' ', $parcont); + $tag=$k2->site->decodeTag($parcont); + + // Создаем компоненту, которая отвечает за работу с контентом + $comp=$k2->ins_comp($tag[0], $tag[1]); + + + if (!$ispost){ + $cont=$comp->getContent(true); + $title=$comp->page->title; + + $short_description=$comp->page->short_description; + $description=$comp->page->description; + + $keywords=$comp->page->keywords; + $h1=$comp->page->h1; + + $type=$comp->page->type; + } + + + $arr=array( + 'content' => $cont, + 'title' => $title, + 'short_description' => $short_description, + 'description' => $description, + 'keywords' => $keywords, + 'h1' => $h1, + 'p' => $p, + 'component' => $parcont, + 'type' => $type + ); + + +//!!! $k2->site->show(false); + $k2->site->setPath($cont); + + + + // Обрабатываем параметры + if ($k2->post('SaveAndExit')<>''){ + echo "Сохраняем и выходим...
    Возвращаемся на: $backurl"; + $comp->Save($arr); + + $this->GoBack($backurl); + exit; + + }elseif ($k2->post('Save')<>''){ + + $comp->Save($arr); + + + echo "Сохранено..."; + + }elseif ($k2->post('Cancel')<>''){ + echo "Выходим без изменений...
    Возвращаемся на: $backurl"; + + $this->GoBack($backurl); + exit; + }else{ + + + } + + + + + $form=" + + + + + +
    + + + +
    + + + + + + + + + + +
    + + + + + + + +

    + Заголовок окна: +

    +

    + Заголовок окна: +

    +

    + Описание: +

    +

    + Ключевые слова: +

    + + + + +
    +
    + +

    + + +

    + + + +
    +
    + +

    + + +

    + + +
    + + + + +
    + + + + + + + + + "; + $html=str_replace('{content_editor}', $form, $html); + + + + + + + return $html; + + } + + + function content(){ + + global $k2; + + if (!$rez=$k2->auth->isAdmin()){ + die('У Вас нет прав редактировать данный текст!!!'); + + if (!$k2->isRoot() and trim($k2->get('p'))==''){ + die('Параметры редактирования не заданы...'); + } + } + + + $rez=$this->formEditor(); + + return $rez; + } + + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2icons.php b/k2shop/k2shop/app/sys/k2icons.php new file mode 100644 index 0000000..fc3d803 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2icons.php @@ -0,0 +1,137 @@ + 'highlight.png', // Редактиврование включаемой области + 'edit_content' => 'edit.png', // Редактирование контента + 'edit_banners' => 'looknfeel.png', // Редактирование баннеров + 'edit_menu' => 'kmenuedit.png', // Редактирование меню + 'add_content' => 'edit_add.png', // Добавление контента + 'del_content' => 'edit_remove.png', // Удаление контента + 'search' => 'find.png', // Поиск + + 'add_news' => 'edit_add.png', // Добавление новости + 'edit_news' => 'tablet.png', // Редактирование новости + 'del_news' => 'edit_remove.png' // Удаление новости + + ); + public $cur_ico_size = '24x24'; // Текущий размер иконки + public $icon_sizes = array( // Размеры иконок + '16x16', '22x22', '24x24', '32x32', '48x48', '64x64', '128x128' + ); + + public $admin_icons=array( // Иконки админ-части + 'addusers' => 'add_user.png', // Добавить пользователя + 'addgroup' => 'add_group.png', // Добавить группу + 'users' => 'personal.png', // Пользователи + 'content' => 'kfm.png', // Контент + 'settings' => 'Service Manager.png', // Настройки + 'shop' => 'folder_home.png', // Магазин + 'contacts' => 'agt_member.png', // Контакты + 'sysinfo' => 'hwinfo.png', // Информация о системе + 'orders' => 'kformula_kfo.png', // Заказы + 'paysystems' => 'ksame.png', // Платежные системы + 'statistic' => 'log.png', // Статистика + 'forum' => 'agt_forum.png', // Форум + 'calc' => 'calc.png', // Калькулятор + 'calendar' => 'date.png', // Календарь + 'about' => 'documentinfo.png', // О разработчике + 'update' => 'agt_add-to-autorun.png', // Обновление + 'check' => 'advancedsettings.png', // Проверка + 'backup' => 'db_comit.png', // Резервное копирование + 'restore' => 'db_update.png', // Восстановление резервной копии + 'design' => 'colorize.png', // Оформление + 'fileman' => 'file-manager.png', // Файловый менеджер + 'logs' => 'jabber_protocol.png', // Логи + 'images' => 'thumbnail.png', // Изображения + 'sqlmanager' => 'cache.png', // SQL-менеджер + 'antivirua' => 'agt_virussafe.png', // Антивирус + 'chat' => 'ksmiletris.png', // Чат + 'mail' => 'ksmiletris.png', // Почта + 'note' => 'knotes.png' // Заметки + ); + public $cur_sumall_admin_ico_size = '24x24'; // Текущий размер иконок админки для меню + public $cur_admin_ico_size = '64x64'; // Текущий размер больших иконок + + public $dialog_icons=array( // Иконки диалоговых окон + 'ok' => 'button_ok.png', + 'cancel' => 'button_cancel.png', + 'warning' => 'messagebox_warning.png' + ); + + public $format_doc_ico=array( // массив форматов документов + 'pdf' => 'acroread.png', // PDF + 'openoffice_write' => 'openofficeorg-20-writer.png', // OpenOfice Writer + 'openoffice_calc' => 'openofficeorg-20-math.png' // OpenOfice Calc + ); + + + // Возвращает путь к иконке + function getPathIco($iconame){ + return $this->icons_dir.'/'.$this->cur_ico_size.'/'.$iconame; + } + + + // Возвращает путь к иконке редактирования включаемой области + function edit_inc(){ + return $this->getPathIco($this->icons['edit_inc']); + } + + // Возвращает путь к иконке редактирования контента + function edit_content(){ + return $this->getPathIco($this->icons['edit_content']); + } + + // Возвращает путь к иконке редактирования баннера + function edit_banner(){ + return $this->getPathIco($this->icons['edit_banners']); + } + + // Возвращает путь к иконке редактирования меню + function edit_menu(){ + return $this->getPathIco($this->icons['edit_menu']); + } + + // Добавить пункт меню + function add_menuItem(){ + return $this->getPathIco($this->icons['add_news']); + } + + + // Добавить новость + function add_news(){ + return $this->getPathIco($this->icons['add_news']); + } + + // Редактировать новость + function edit_news(){ + return $this->getPathIco($this->icons['edit_news']); + } + + // Удалить новость + function del_news(){ + return $this->getPathIco($this->icons['del_news']); + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2inc.php b/k2shop/k2shop/app/sys/k2inc.php new file mode 100644 index 0000000..72465be --- /dev/null +++ b/k2shop/k2shop/app/sys/k2inc.php @@ -0,0 +1,205 @@ + + .aligndiv{ + position: absolute; + right: 5%; + } + .fixeddiv{ + padding-bottom: 40px; + } + .incarea2{ + outline: 2px solid #09ab3f; + //border: 5px solid #09ab3f; + 1z-index:9999; + position: relative; + } + '; + + public $content = ''; // Контент + + public $save; // Компонента сохранения данных + + + // Инициализация. Класс переопределяется всегда + protected function init_obj(){ + global $k2; + + if( ($k2->auth->isAdmin()) && ($k2->auth->isDesignMode()) ) { + $this->template = '{edit}
    {content}
    '; + } + + } + + + // Выдет внешний вид кнопки + function editLinks($contentId){ + global $k2; + $ico=$k2->ico->edit_inc(); + + + $content = $k2->ins_comp('k2cont'); + $jqx = $k2->ins_comp2('k2window', $this); + $arr_win = [ + 'caption'=>'Редактирование области '.$this->incID, + 'main_div'=>'decoration', + 'wnd_id'=>'window{contentid}', + 'is_modal'=>true, + 'height'=>650, + 'width'=>850, + 'left'=>450, + 'top'=>225, + 'is_modal'=>false, + 'button'=>false, + 'wnd_body'=>" +
    + +
    + " + ]; + + //$ajaxSrtipt = $content->ajaxSrtipt; + $ajaxSrtipt = $jqx->showWindow($arr_win).$content->editScript.''; + + $ajaxSrtipt = str_replace('{contentid}', $contentId, $ajaxSrtipt); + + //return "Редактировать".$ajaxSrtipt; + //return "Редактировать ".$this->incID."".$ajaxSrtipt; + //return "Редактировать ".$this->incID."".$ajaxSrtipt; + return $ajaxSrtipt; + } + + + + // Кнопки для администрирования + function admButtons(&$html){ + global $k2; + + if (($k2->auth->isAdmin()) and ($k2->auth->isDesignMode())){ + $content = $k2->ins_comp('k2cont'); + + if ($this->contentID == '') { + $contentItem = $content->getItemContentByCommand($this->incID); + } else { + $contentItem = $content->getItemContentById($this->contentID); + } + if( !empty($contentItem) ) { + $contentId = $contentItem[0]['contentid']; + $title = $contentItem[0]['title']; + $h1 = $contentItem[0]['h1']; + $contents = $contentItem[0]['content']; + $short_description = $contentItem[0]['short_description']; + $descript = $contentItem[0]['descript']; + $keywords = $contentItem[0]['keywords']; + } else { + $contentId = 0; + } + //$btn='
    '.$this->editLinks().'
    '; + $btn='
    '.$this->editLinks($contentId); + //$btn = $this->editLinks(); + $btn = str_replace('{title}', $title, $btn); + $btn = str_replace('{h1}', $h1, $btn); + //$btn = str_replace('{content}', $contents, $btn); + $btn = str_replace('{short_description}', $short_description, $btn); + $btn = str_replace('{descript}', $descript, $btn); + $btn = str_replace('{keywords}', $keywords, $btn); + + }else{ + $btn = ''; + + } + $html = str_replace('{contentid}', $contentId, $html); + $html = str_replace('{edit}', $btn, $html); + } + + + + public function getTemplateContent($templateCommand, $contentId = '', $contentType = '') { + global $k2; + + $rez = ''; + + $content = $k2->ins_comp('k2cont'); + $content->contentCommand = $templateCommand; + $content->contentTemplate = '{content}'; + $content->contentType = $contentType; + $content->contentId = $contentId; + $content->is_item = $this->is_item; + //$content->pageShortDescriptionLink = true; + if ($this->temp_name !== '') { + if ($k2->get('item') ) { + if (($this->temp_name)) { + $tpl = $this->temp_name.'_tpl'; + $content->contentTemplate = $content->$tpl; + } else { + $contentid = $k2->get('item'); + if ($k2->site->is_slug) { + $contentid = $content->getIdBySlug($contentid); + } + $k2->site->pathway->add('', ''.$content->getTitleById( $contentid )); + $content->contentTemplate = $content->full_tpl; + } + + } else { + $tpl = $this->temp_name.'_tpl'; + $content->contentTemplate = $content->short_tpl; + } + $rez = $content->sumTpl(); + + return $rez; + } + $rez = $content->showContent(); + + return $rez; + } + + function content(){ + global $k2; + + $rez = ''; + + $templateCommand = $this->templ; //Получили название темплейта / command в таблице k2content + + if ($this->isshow){ + $cont = $this->getTemplateContent($this->incID, $this->contentID, $this->incID); + $rez = str_replace('{content}', $cont, $this->template); + $this->admButtons($rez); + //$rez=str_replace('{contentid}', $this->contentID, $this->template); + } +// $not = $k2->ins_comp('k2notification'); +// $rez .= $not->content(); + return $rez; + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2ini.php b/k2shop/k2shop/app/sys/k2ini.php new file mode 100644 index 0000000..ee04a22 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2ini.php @@ -0,0 +1,26 @@ +init(); + } + + + // Стиль форм + function style_form(){ + global $k2; + return $k2->stylecontrols->cur_style('form'); + } + + // Стиль таблиц + function style_grid(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('grid'); + } + + + // Стиль меню + function style_slidemenu(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('slidemenu'); + } + + // Стиль Pivot-таблиц + function style_pivot(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('pivot'); + } + + // Стиль закладок + function style_tabs(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('tabs'); + } + + // Стиль древовидных таблиц + function style_treegrid(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('treegrid'); + } + + // Стиль деревьев + function style_tree(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('tree'); + } + + // Стиль загрузки + function style_upload(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('upload'); + } + + // Стиль списочного поля + function style_listbox(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('listbox'); + } + + // Стиль выпадающего списка + function style_combobox(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('combobox'); + } + + // Стиль календаря + function style_calendar(){ + global $k2; + return $style = $k2->stylecontrols->cur_style('calendar'); + } + + // Инициализации компонент KoolControls + function init(){ + global $k2; + $this->KoolControlsFolderAbs=nslashe($k2->rootdir.'/k2shop/k2shop/libs/KoolPHPSuite/KoolControls'); + $this->KoolControlsFolder='/k2shop/k2shop/libs/KoolPHPSuite/KoolControls'; + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2log.php b/k2shop/k2shop/app/sys/k2log.php new file mode 100644 index 0000000..083113a --- /dev/null +++ b/k2shop/k2shop/app/sys/k2log.php @@ -0,0 +1,180 @@ +addLog($mess, 'mess.log', $isshow, "mess"); + } + + + + // Лог консольного приложения + function logcmd($mess, $isshow=false){ + $this->addLog($mess, 'logcmd.log', $isshow, "logcmd"); + } + + + // Лог крона + function cron($mess, $isshow=false){ + $this->addLog($mess, 'cron.log', $isshow, "cron"); + } + + + // Ошибка базы данных + function errDB($mess, $isshow=false){ + $this->addLog($mess, 'ErrorDB.log', $isshow, "errDB"); + } + + + // Вывод ошибки + function err($mess, $isshow=false){ + $this->addLog($mess, 'Error.log', $isshow, "error"); + } + + + // Замечание + function warn($mess, $isshow=false){ + $this->addLog($mess, 'Warn.log', $isshow, "warning"); + } + + + // Отладочный лог + function debug($mess, $isshow=false){ + $this->addLog($mess, 'Debug.log', $isshow, "debug"); + } + + + // Начало события в логе + function begLog($mess){ + + } + + + // Конец события в логе + function endLog($mess){ + + } + + + // Фиксация времени работы + function runningLog($mess){ + + } + + + // Отключение перевода каретки + function delReturn($str){ + $rez = str_replace(["\r\n", "\r", "\n"], '', $str); + return $rez; + } + + + // Запись в лог + // $mess - сообщение + // $filename - название файла + // $isshow - выводить ли сообщение на экран + function addLog($mess, $filename='main.log', $isshow=false, $event="Non"){ + global $k2; + + $login = ''; + if (isset($k2->auth)){ + $login = $k2->auth->login; + } + + $ip = ''; + $agent = ''; + if (isset($k2->sys)){ + $ip = $k2->sys->ip(); + $agent = $k2->sys->agent(); + } else { + echo 'k2->sys not sets!!!'; + var_dump($k2); + } + + + $mk = microtime(true); + $mk = ($mk-floor($mk))*1000000; + + $fullmess = date("m.d.y H:i:s (").$mk.' мкс)|'.$this->delReturn($mess)."|".$event."|".$login."|".$ip."|".$agent."\r\n"; + + if ($isshow){ + echo $mess."\n"; + } + + $logdir = $k2->rootdir.'/var/'.'log'; + + if ($k2->sys->forceDir($logdir)){ + file_put_contents($logdir.'/'.$filename, $fullmess, FILE_APPEND ); + + if ($event<>'debug'){ + file_put_contents($logdir.'/alllog.log', $fullmess, FILE_APPEND ); // Общее сборище логов + } + } + } + + /** + * запись в базу + * @global type $k2 + */ + function addDBLog($comp = '', $event = '', $descript = ''){ + global $k2; + $rez = ''; + $userid = ''; + if (isset($k2->auth)){ + $userid = $k2->auth->userid; + } + $ip = $k2->sys->ip(); + $agent = $k2->sys->agent(); + $logid = $this->getID(); + if ($userid && $event) { + $sql = "INSERT INTO k2logs + ( + logid, + userid, + ip, + agent, + comp, + event, + descript, + datetime + ) + VALUES + ( + '".$logid."', + '".$userid."', + '".$ip."', + '".$agent."', + '".$comp."', + '".$event."', + '".$descript."', + '".date("Y-m-d H:i:s")."' + )"; + + try { + $k2->db->exec($sql); + } catch (Exception $e) { + echo "Ошибка: ".$e->getMessage().$sql."\n"; + } + } + + return $rez; + } +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2mail.php b/k2shop/k2shop/app/sys/k2mail.php new file mode 100644 index 0000000..51c4dbb --- /dev/null +++ b/k2shop/k2shop/app/sys/k2mail.php @@ -0,0 +1,161 @@ +encoding." \r\n"; + $header .= "From: ".$this->mail_from." \r\n" + ."X-Mailer: PHP"; + $header .= "MIME-Version: 1.0 \r\n"; + $header .= "Content-Transfer-Encoding: 8bit \r\n"; + $header .= "Date: ".date("r (T)")." \r\n"; + } + + mail($mailto, $subj, $mess, $header); + + } + + + //устанавливаем параметры + public function setParam() + { + global $k2; + + $getsets = $k2->sql->sel('select * from k2mail_sets', []); + foreach ($getsets['data'][0] as $key => $value){ + if (isset($value)){ + $this->$key = $value; + } + } + + } + + function sendMail($mailto, $subj, $mess, $header = '') + { + $this->setParam(); + if ($this->is_smtp) { + $this->sendMailSmtp($mailto, $subj, $mess, $header = ''); + } else { + $this->sendOldMail($mailto, $subj, $mess, $header = ''); + } + + } + + + /** + * прием ответа сервера + * @param type $smtp_conn + * @return type + */ + function get_data($smtp_conn) + { + $data=""; + while($str = fgets($smtp_conn,515)) + { + $data .= $str; + if(substr($str,3,1) == " ") { break; } + } + return $data; + } + + /** + * SMTP + * @param type $mailto + * @param type $subj + * @param type $mess + * @param type $header + */ + function sendMailSmtp($mailto, $subj, $mess, $header = '') + { + + + $mail = new PHPMailer(true); + try { + //Server settings + $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output + $mail->isSMTP(); //Send using SMTP + $mail->Host = $this->host; //Set the SMTP server to send through + $mail->SMTPAuth = true; //Enable SMTP authentication + $mail->Username = $this->username; //SMTP username + $mail->Password = $this->password; //SMTP password + $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption + $mail->Port = $this->port; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` + $mail->SMTPOptions = [ + 'ssl' => [ + 'verify_peer' => false, + 'verify_peer_name' => false, + 'allow_self_signed' => true, + ] + ]; + + + $mail->CharSet = 'utf-8'; + //Recipients + $mail->setFrom($this->username, $this->sender); + $mail->addAddress($mailto, ''); //Add a recipient + //$mail->addAddress('ellen@example.com'); //Name is optional + //$mail->addReplyTo('info@example.com', 'Information'); + //$mail->addCC('cc@example.com'); + //$mail->addBCC('bcc@example.com'); + + //Attachments + //$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments + //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name + + //Content + $mail->isHTML(true); //Set email format to HTML + $mail->Subject = $subj; + $mail->Body = $mess; + $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; + + $mail->send(); + echo 'Message has been sent'; + } catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; + } + } + + + + + +} diff --git a/k2shop/k2shop/app/sys/k2messages.php b/k2shop/k2shop/app/sys/k2messages.php new file mode 100644 index 0000000..c4cee24 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2messages.php @@ -0,0 +1,112 @@ + +
    + + +
    +
    + X + +

    {Reed_message}

    +
    +
    + +

    {message}

    + +
    +
    + + + + +
    + +
    + +
    + + "; + + + // Инициализация. Класс переопределяется всегда + protected function init_obj(){ + global $k2; + $k2->site->addCSS('messages.css', '/k2shop/k2shop/app/app/k2/k2adminmessage/messages.css'); + $k2->site->addJSEnd('messages.js', '/k2shop/k2shop/app/app/k2/k2adminmessage/messages.js'); + } + + + //Показ сообщений + function showMessages(){ + global $k2; + + $rez=""; + + $userid = $k2->auth->login; + if($userid){ + $sql="SELECT k.messid, k.adres, k.message, k.color + FROM k2mass_message k + WHERE k.messid + NOT IN (SELECT m.messid FROM k2mass_mess_user m WHERE m.usermessid = '".$userid."') + AND (k.userid <> '".$userid."') + AND (k.adres = '*' OR k.adres = '".$userid."') LIMIT 1"; + + foreach($k2->db->query($sql) as $row){ + $message=htmlspecialchars_decode($row['message']); + $messid=$row['messid']; + $color = $row['color']; + $sql2="INSERT INTO `k2mass_mess_user` (messid, usermessid, messuserdate) VALUES (".$messid.", '".$userid."', now()) "; + + $rez.= $this->message; + + $curUrl=$k2->getParamURL(); + + if($k2->post('messid')==$messid){ + $k2->db->exec($sql2); + header ('Location: /?'.$curUrl); + } + $rez = str_replace('{Reed_message}',$this->Translate("{lnReedMessage}"), $rez); + $rez = str_replace('{message}',$message, $rez); + $rez = str_replace('{mesid}',$messid, $rez); + $rez = str_replace('{color}',$color, $rez); + + + } + + + } + + + return $rez; + } + + + + + function content(){ + global $k2; + $rez=$this->showMessages(); + return $rez; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2obj.php b/k2shop/k2shop/app/sys/k2obj.php new file mode 100644 index 0000000..5977e7a --- /dev/null +++ b/k2shop/k2shop/app/sys/k2obj.php @@ -0,0 +1,992 @@ +'0', + 'w'=>'0', + 'i'=>'0', + 'd'=>'0', + 'c'=>'0', + 'exp'=>'0', + 'imp'=>'0', + 'settable'=>'0', + 'cutpast'=>'0', + 'enable'=>'0' + ]; // Права доступа + + + public $path_objs=[ + '/cfg', + '/cfg/{proj}', + '/usr/def/cfg', + '/usr/{template}/cfg', + '/k2shop/usr/{template}/cfg', + '/usr/{domain}/cfg', + '/k2shop/k2shop/cfg' + ]; + + protected $objs = []; // Перечень зависимы объектов + protected $owner = ''; // Владелец + + + private $vars = []; // Переменные. Формат: Ключ => значение + + + + + + // Подключение к базе данных через которое работает компонента по умолчанию + // Структура массива + // connect_name - Название подключения, под которым оно присутствует в ядре + // db - PDO-подключение + // connected - информация о том, что подключено к базе данных или нет + // name - название подключения (для человека) + // comment - примечание к подключению (для человека) + // driver - драйвер для подключения (формат, принятый в Symfony) + // user - имя пользователя для подключения + // password - пароль + // host - ip-арес сервера + // dbname - название базы данных + // auto_connect - производить ли автоматическое подключение + public $db = []; + + + // Получает текущее подключение + function getConn(){ + global $k2; + $rez=''; + + if (isset($this->db['connect_name'])){ + $conf=$k2->sqlInfo($this->db['connect_name'])['conf']; + }else{ + $conf=$k2->sqlInfo()['conf']; + } + + return $rez; + } + + + + + // Установка информации о подключении в компоненте + // Если $connect_name пусто, то берет основное подключение ядра + function setDB($connect_name=''){ + global $k2; + + if (!isset($k2)) return; + + if ($connect_name=='' && isset($this->db['connect_name'])) + $connect_name=$this->db['connect_name']; + + if (!isset($this->db['connect_name']) || $this->db['connect_name']==''){ + $this->db=[ + 'connect_name' => '', + 'db' => (isset($k2->db) ? $k2->db : null), + 'driver' => $k2->server_type, + 'user' => $k2->user, + 'password' => $k2->pass, + 'host' => $k2->host, + 'dbname' => $k2->dbname, +// 'options'=> [ +// 1002=> "SET NAMES utf8", +// 1000=> true +// ] + ]; + }else{ + $conninfo=$k2->find_connection($connect_name); + if (isset($conninfo)){ + + $this->db=$conninfo; + $this->db['connect_name']=$connect_name; + //$k2->db = $this->db['db']; + } + } + + + } + + + // $templ - template title (название шаблона ) + // $script - script name (название скрипта) + // $obj - класс к которому прикрепляется данный объект (становится зависимым от объекта) + public function __construct($templ='', $script='', &$owner='') { + global $k2; + + $this->name=$this::genName(); + + $this->path_comp = nslashe($script); + $this->templ = $templ; + + $this->LoadBeforeConfig(); + $this->LoadCfg(); + $this->setDB(); + $this->LoadAfterConfig(); + + $this::getCompVersion(); + if (isset($k2)){ + $this->voc = $this::loadTranslate($k2->lng); + } + + if (!empty($owner)){ + $this->owner = $owner; + if ($owner instanceof k2obj){ + $owner->addObj($this); + } + } + + $this->init_obj(); + + $this->loadPermission(); + $this::addToHead(); + $this::userPermission(); + } + + + // Запускается перед загрузком конфигурационного файла + function LoadBeforeConfig(){ + // + } + + // Запускается после загрузки конфигурационного файла + function LoadAfterConfig(){ + // + } + + + + // Инициализация. Класс переопределяется всегда + protected function init_obj(){ + + } + + + // Загрузка текста из ресурсов + // $filename - название файла (с расширением) + function loadTextFromRes($filename){ + $rez=''; + $full_filename=nslashe($this->getDirComponent().'/res/'.$filename); + + if (file_exists($full_filename)){ + $rez=file_get_contents($full_filename); + }else{ + echo 'Не найден файл ресурсов: '.$full_filename; + } + + return $rez; + } + + + // Загружает YML файл из ресурсов + // $filename - название файла, без расширения .yml + // Класс должен вызываться из класса-наследника. Т.к. по нему определяется + // место расположения ресурса + // $no_parse - парсить или не парсить ресурс + public function loadResYML($filename, $no_parse=false, $path = ''){ + global $k2; + if ($path == '') { + $ymlfile = nslashe($this->getDirComponent().'/res/'.$filename.'.yml'); + } else { + $ymlfile = nslashe($k2->rootdir.$path.$filename.'.yml'); + } + + + $rez = $this->loadResYMLFull($ymlfile, $no_parse); + + return $rez; + } + + + // Загружает YML файл из ресурсов + // $filename - название файла, без расширения .yml + // Класс должен вызываться из класса-наследника. Т.к. по нему определяется + // место расположения ресурса + // $no_parse - парсить или не парсить ресурс + public function loadInfoYML($path, $no_parse=false){ + global $k2; + $rez = ''; + $ymlfile = nslashe($path); + if (file_exists($ymlfile)){ + $rez = $this->loadResYMLFull($ymlfile, $no_parse); + } + return $rez; + } + + + // Загрузка ресурса по указанному полному пути + public function loadResYMLFull($filename, $no_parse = false){ + global $k2; + $str=$k2->loadFromYml($filename, true); + if (!$no_parse){ + preg_match_all("#<%(.*)%>#isUu",$str,$tegs); + + foreach ($tegs[1] as $teg){ + $trans=$this->Translate("{".$teg."}"); + if (trim($trans)<>"{".$teg."}"){ + $str= str_replace('<%'.$teg.'%>', $trans, $str); + }else{ + $var=$this->find_var($teg); + + $str= str_replace('<%'.$teg.'%>', /*$teg*/$var, $str); + } + } + + + try{ +// $yaml_file=nslashe($k2->rootdir.'\k2shop\k2shop\libs\yaml\Spyc.php'); +// require_once $yaml_file; +// $rez = Spyc::YAMLLoadString($str); +// $rez = $this->updateYaml($rez); + //echo $filename; + $rez = Yaml::parse($str); + } catch (Exception $e) { + echo 'Выброшено исключение: ', $e->getMessage(), "\n"; + } + + + }else{ + $rez = $str; + } + + return $rez; + } + + + + function updateYaml($arr) + { + if (is_array($arr['select'])) { + $arr['select'] = implode(" ", $arr['select']); + } + foreach ($arr['fields'] as $key => $value) { + if (is_array($value['sql'])) { + $arr['fields'][$key]['sql'] = implode(" ", $value['sql']); + } + if (is_array($value['sql_form'])) { + $arr['fields'][$key]['sql_form'] = implode(" ", $value['sql_form']); + } + } + return $arr; + } + + + + // Ищет переменную + // Зарегистрированные переменные в yml: + // <%User%> - текущий пользователь + // <%Date%> - текущая дата + // <%Now%> - текущая дата и время + // <%Role%> - роль + // <%Firm%> - текущая фирма + function find_var($teg){ + global $k2; + $rez=$teg; + + switch (mb_strtoupper($teg)) { + case 'USER': + $rez = $k2->auth->login; + break; + case 'USERID': + $rez = $k2->auth->userid; + break; + case 'DATE': + $rez = date("d.m.Y"); + break; + case 'NOW': + $rez = date('d.m.Y H:i:s'); + break; + case 'ROLE': + $rez = $k2->auth->roleid; + break; + case 'FIRM': + $rez = $k2->auth->firmid; + break; + default: + // Перебираем все переменные + foreach ($this->vars as $k => $val){ + if (mb_strtoupper($teg)==mb_strtoupper($k)){ + $rez = $val; + } + } + } + + + return $rez; + } + + // Очистка ключей + function clearVars(){ + $this->vars=[]; + } + + // Добавление переменных + // $arr - массив переменных с элементами ключ => значение + function addVars($arr){ + $this->vars = array_merge($this->vars, $arr); + } + + + // Устанавливает переменные. Перед вставкой - удаляет имеющиеся переменные + function Vars($arr){ + $this->clearVars(); + $this->addVars($arr); + } + + + + // Деструктор + function __destruct() { + + // Освобождение зависимых объектов + foreach ($this->objs as $obj){ + if (isset($obj)){ + unset($obj); + } + } + + } + + // Добавление зависимого объекта + function addObj(&$obj){ + $objs[]=$obj; + } + + + + + // Загрузка прав доступа + function loadPermission(){ + global $k2; + + if (!empty($k2->auth)){ + + // Супер-админ может все + if ($k2->auth->isSuperAdmin()){ + $this->setFullRights(); + }else{ + $this->findRights(); + } + + if (!empty($k2->site)){ + if ($k2->debug==1){ + $perm=$this::arrToStrKey($this->permission); // сохраняю в виде строки массив + $varname='Permission.'.$this::getClassName(); + + $k2->site->addHead($varname, ''); + } + } + + } + + } + + + // Установка пользовательских прав + function userPermission(){ + + } + + + // Поиск прав для текущего объекта + function findRights(){ + global $k2; + + // Проверяем есть ли данный класс в списке объектов на которые определяются права + if (isset($k2->secur->admin_menus[$this::getClassName()])){ + $el = &$k2->secur->k2admin_menus_prava[$this::getClassName()]; + + if (isset($el)){ + $this->permission=[]; + if (isset($el['r'])) $this->permission['r']=$el['r']; + if (isset($el['w'])) $this->permission['w']=$el['w']; + if (isset($el['i'])) $this->permission['i']=$el['i']; + if (isset($el['d'])) $this->permission['d']=$el['d']; + if (isset($el['c'])) $this->permission['c']=$el['c']; + if (isset($el['exp'])) $this->permission['exp']=$el['exp']; + if (isset($el['imp'])) $this->permission['imp']=$el['imp']; + if (isset($el['settable'])) $this->permission['settable']=$el['settable']; + if (isset($el['cutpast'])) $this->permission['cutpast']=$el['cutpast']; + if (isset($el['enable'])) $this->permission['enable']=$el['enable']; + } + + }else{ + $this->setNormalRights(); + } + + } + + // Преобразует массив в строку с соблюдением ключей + function arrToStrKey($arr){ + $rez=json_encode($this->permission); // сохраняю в виде строки массив + $rez=str_replace('"', '', $rez); + $rez=str_replace('{', '', $rez); + $rez=str_replace('}', '', $rez); + return $rez; + } + + + // Установка полных прав + function setNormalRights(){ + $this->permission=['r'=>'1', 'w'=>'1', 'i'=>'1', 'd'=>'1', 'c'=>'0', 'exp'=>'0', + 'imp'=>'0', 'settable'=>'1', 'cutpast'=>'0', 'enable'=>'0']; + } + + + // Установка полных прав + function setFullRights(){ + $this::setAllPermission('1'); + } + + + // Установка всех прав заданным значением + function setAllPermission($val){ + $this->permission=['r'=>$val, 'w'=>$val, 'i'=>$val, 'd'=>$val, 'c'=>$val, 'exp'=>$val, + 'imp'=>$val, 'settable'=>$val, 'cutpast'=>$val, 'enable'=>$val]; // Права доступа + + } + + + // Права чтения + function isRead(){ + return $this->permission['r']==1; + } + + // Права записи + function isWrite(){ + return $this->permission['w']==1; + } + + // Права вставки + function isIns(){ + return $this->permission['i']==1; + } + + // Права удаления + function isDel(){ + return $this->permission['d']==1; + } + + // Права копирования + function isCopy(){ + $rez=$this->permission['c']==1; + if (!$this->isWrite()){ + $rez=false; + } + + return $rez; + } + + // Права экспорта + function isExp(){ + return $this->permission['exp']==1; + } + + // Права импорта + function isImp(){ + $rez=$this->permission['imp']==1; + if (!$this->isWrite()){ + $rez=false; + } + + return $rez; + } + + // Разрешено ли настраивать таблицы + function isSetTable(){ + return $this->permission['settable']==1; + } + + // Разрешено копировать в буфер + function isCutPaste(){ + return $this->permission['cutpast']==1; + } + + // Разрешено ли устанавливать фокус + function isEnable(){ + return $this->permission['enable']==1; + } + + + // Возвращает название объекта класса + function getName(){ + return $this->name; + } + + // Устанавливает название объекта + function setName($name){ + $this->name=$name; + } + + + // Получить название div для таблицы + function getDivName(){ + global $k2; + $rez=$this::getName(); + + return $rez; + } + + + // Генерация названия объекта класса + function genName(){ + $rez=get_class($this)."_".$this::getID(); + return $rez; + } + + + // Определение версии кимпоненты + function getCompVersion(){ + $dirname=nslashe($this->getDirComponent()); + $arr_info = $this->loadInfoYML(nslashe($dirname).'/ver.yml'); + if($arr_info){ + $this->version = $arr_info['version']; + } + } + + + // Генерация уникального ID + function getID(){ + mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up. + $charid = strtoupper(md5(uniqid(rand(), true))); + $hyphen = chr(45);// "-" + $uuid = chr(123)// "{" + .substr($charid, 0, 8).$hyphen + .substr($charid, 8, 4).$hyphen + .substr($charid,12, 4).$hyphen + .substr($charid,16, 4).$hyphen + .substr($charid,20,12) + .chr(125); + return md5($uuid); + } + + // Вставка библиотек в Head + function addToHead(){ + global $k2; + + // $k2->site->addCSS('jqx.base.css',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/styles/jqx.base.css"); + // $k2->site->addJS('jqxpanel.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxpanel.js"); + } + + + // File upload function from csv, and save the data into an array (Функция загрузки файла из csv и сохранения данных в массив) + // The array elements are numbered in accordance with the 1st string (Элементы массива нумеруются в соответствии с 1-й строкой) + // The index serves as 1st field the csv-file (В качестве индекса выступает 1-е поле csv-файла) + // As field names appears 1st line of the file (В качестве названий полей выступает 1-я строка файла) + function loadCSV($filename, $razd='|', $rows=0){ + global $k2; + $arr = []; + + + if (file_exists($filename)){ + $data = file_get_contents($filename); + $arr_rows=explode("\n", $data); + + $i=1; + foreach ($arr_rows as $key) { + + if (trim($key)<>''){ + if ($i<>1){ + list($name, $value)=explode($razd, $key); + $arr[$name]=$value; + } + + } + + $i++; + if ($i>$rows) break; + } + + + + } + + return $arr; + } + + + // Загрузка данных из CSV-таблицы + // 0 массив - массив с описанием + function loadCSVTable($filename, $razd='|', $rows=0){ + global $k2; + $arr = []; + + if (file_exists($filename)){ + $data = file_get_contents($filename); + $arr_rows=explode("\n", $data); + + $i=0; + foreach ($arr_rows as $val) { + + $elems_arr=explode("|", $val); + $arr[$i]=$elems_arr; + + + $i++; + if ($rows<>0 and $i>$rows) break; + } + + } + + return $arr; + } + + + // Сохранение текстового файла + // $textdata - данные, которые сохраняются в файл + // $filename - название файла + // $is_replace - замена файла, если он есть + function saveTextData($textdata, $filename, $is_replace=true){ + global $k2; + + if ((!$is_replace)&&(file_exists($filename))){ + return ''; + } + + file_put_contents($filename, $textdata); + } + + + // Загружает текстовый файл с именем $filename + function loadTextData($filename){ + global $k2; + $rez=''; + + if (file_exists($filename)){ + $rez=file_get_contents($filename); + } + + return $rez; + } + + + + // Возвращает каталог, где находится компонента + function getDirComponent(){ + global $k2; + + $dirname=''; + if ($this->path_comp<>'' ){ + $p=pathinfo($this->path_comp); + if (isset($p) && isset($p['dirname'])){ + $dirname=$p['dirname']; + } + } + + return $dirname; + } + + + + // The name of the file translation (Название файла перевода) + function getTranslateName($lng=''){ + global $k2; + + $lang=$k2->lng; + if (trim($lng)<>'') + { + $lang=trim($lng); + } + + + $dirname=$this->getDirComponent(); + + return $dirname.'/lng/'.$this::getClassName().'/'.$lang.'.csv'; + } + + + // Loading translation (Загрузка перевода) + function loadTranslate($lng=''){ + global $k2; + $arr=array(); + + $transfile=$this::getTranslateName($lng); + + if (file_exists($transfile)){ + $data = file_get_contents($transfile); + $arr_rows=explode("\n", $data); + + $i=1; + foreach ($arr_rows as $key) { + + if (trim($key)<>''){ + if ($i<>1){ + $arr_expl=explode("|", $key); + if (count($arr_expl)>=2){ + $arr[$arr_expl[0]]=$arr_expl[1]; + } + } + + } + + $i++; + } + + } + + return $arr; + + } + + // Translate the above text (Перевести указанный текст) + function Translate($strinp=''){ + global $k2; + + $rez=$strinp; + + foreach ($this->voc as $key=>$value) { + $key=trim($key); + $value=trim($value); + $rez=str_replace("{".$key."}", $value, $rez); + } + + return $rez; + } + + + // Replace mask in text (Замена масок в тексте) + function replArrMask($str = '', $arr = []){ + global $k2; + + $rez = $str; + + foreach ($arr as $key=>$value) { + $key = trim($key); + $value = trim($value); + $rez = str_replace("{".$key."}", $value, $rez); + } + + return $rez; + } + + // Replace mask in text (Замена масок команд в тексте) + function replContMask($str = ''){ + global $k2; + $findcont = $k2->sql->sel("select command, content from k2content where langid=:langid", ['langid'=>$k2->lng]); + $rez = $str; + $arr2 = []; + foreach ($findcont['data'] as $value) { + $arr2[$value['command']] = $value['content']; + } + foreach ($arr2 as $key=>$value) { + $key=trim($key); + $value=trim($value); + $rez=str_replace("{".$key."}", $value, $rez); + } + + return $rez; + } + + // Returns the name of the class (Возвращает название класса) + function getClassName(){ + return get_class($this); + } + + // Returns the class name and the template that will be used to store information (Возвращет название класса и шаблона, которое будет использоваться для хранения информации) + function getTemplateName(){ + $rez=$this::getClassName(); + + if (trim($this->templ)<>''){ + $rez.='_'.trim($this->templ); + } + + return $rez; + } + + + + // Returns the path to the configuration file (Возвращает путь к конфигурационному файлу) + function getCfg(){ + + global $k2; + + $arr=$this->path_objs; + + if (isset($k2)){ + $filename=$k2->search_script($this->getClassName(), $this->templ, $arr,'.php'); + }else{ + $filename=''; + } + + return $filename; + } + + + + // Loads the class settings (Загружает настройки класса) + // $obj - Transmitted object of the current class (передаваемый объект текущего класса) + function LoadCfg($cfgname=''){ + + global $k2; + + if ($cfgname==''){ + $cfgname=$this->getCfg(); + + if (isset($k2) and (trim($cfgname)=='')){ + $s=nslashe($k2->cfgdir.'/'.$this->getClassName().'.php'); + }else{ + $s=$cfgname; + } + }else{ + $s=$k2->rootdir.$cfgname; + } + + + + if (file_exists($s)){ + require($s); + } + + } + + + // Returns the content without toolbar (Возвращает контент без панели интсрументов) + function getContent($isshow=false){ + return $this->page->content; + } + + + function renderJS(){ + + } + + // Conclusion content (Вывод контента) + function content(){ + return ''; + } + + + function show(){ + echo $this::content(); + } + + // Return items in the admin menu (Возвращает элементы в админ-меню) + function getAdminMenu(){ + return array(); + } + + function admCommands($comm){ + return false; + } + + +} + + +/////////////////////////////////////////////////////////////// +// Content objects (Контентные объекты) // +/////////////////////////////////////////////////////////////// +class k2contentobj extends k2obj implements ik2contentobj{ + + public $filter=''; // When the content is displayed. for example: $this->isshow=$k2->isRoot() (Когда выводится контент. Например: $this->isshow=$k2->isRoot()) + public $isshow = true; + + public $page; + + + protected function init_obj(){ + $this->Load(); + } + + + // File name to save the data file / data / (Название файла в файле сохранения данных /data/) + // This name is intended to cases of work with the system without the use of database (данное название предназначено на случаи работы с системой без использования базы данных) + function getFileNameData(){ + global $k2; + + $rez='/data/'.$k2->domain().'/'.$this->getTemplateName().'.php'; + + return $rez; + } + + + // It passes the content without toolbars and template parts (Передает контент без панелей инструментов и шаблонной части) + function getContent($isshow=false){ + + // If there is a condition of output - print it (Если есть условие вывода - выводим его) + if ((!$this->isshow) and (!$isshow)){ + return ''; + } + + $cont=$this->content; + + return $cont; + + } + + + // Saving data (Сохранение данных) + function Save($data){ + global $k2; + + $this->save=$k2->ins_comp('k2save'); + $this->save->Save($data, $this); + } + + // Loading data (Загрузка данных) + function Load(){ + global $k2; + + $this->page=$k2->ins_comp('k2page'); + $this->page->LoadFromData($this->getFileNameData()); + + $this->save=$k2->ins_comp('k2save'); + $this->save->Load($this); + } + + + + +} + diff --git a/k2shop/k2shop/app/sys/k2page.php b/k2shop/k2shop/app/sys/k2page.php new file mode 100644 index 0000000..7eec312 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2page.php @@ -0,0 +1,213 @@ +title=$arr['title']; + $this->short_description=$arr['short_description']; + $this->description=$arr['description']; + $this->keywords=$arr['keywords']; + $this->h1=$arr['h1']; + $this->content=$arr['content']; + } + + + // Preservation properties of the array (Сохранение свойств в массив) + function saveToArr(){ + + $arr=array( + 'title' => $this->title, + 'short_description' => $this->short_description, + 'description' => $this->description, + 'keywords' => $this->keywords, + 'h1' => $this->h1, + 'content' => $this->content + ); + + return $arr; + } + + + // Loading class of the Data folder (Загрузка класса из папки Data) + function LoadFromData($filenamedata){ + + global $k2; + + $s=$k2->rootdir.$filenamedata; + + if (file_exists($s)){ + $this->isloadedcontent=true; + + require_once($s); + } + + } + + + // Escaping special characters (Экранирование спец-символов) + function SafeSym($cont){ + $rez=$cont; + + // The variables in the file will be saved with a double-quote, so Escapes double quotation mark (Переменные в файле буду сохранять с двойной кавычкой, поэтому, экранирую двойную кавычку) + $rez=str_replace('"', '\"', $rez); + + return $rez; + } + + + // Restoring escaped characters (Восстановление экранированных символов) + function unSafeSym($cont){ + $rez=$cont; + + // The variables in the file will be saved with a double-quote, so Escapes double quotation mark (Переменные в файле буду сохранять с двойной кавычкой, поэтому, экранирую двойную кавычку) + $rez=str_replace('\"', '"', $rez); + + return $rez; + } + + + + // Setting the title properties (Установка свойства заголовка) + function setTitle(&$title){ + $this->title=$title; + } + + // Installing a brief description of the properties (Установка свойства короткого описания) + function setShortDescription(&$short_description){ + $this->short_description=$short_description; + } + + + // Setting description properties (Установка свойства описания) + function setDescription(&$description){ + $this->description=$description; + } + + + // Setting properties keywords (Установка свойства ключевых слов) + function setKeywords(&$keywords){ + $this->keywords=$keywords; + } + + // Setting header (Установка заголовка) + function setH1(&$h1){ + $this->h1=$h1; + } + + // Setting Content Properties (Установка свойств контента) + function setContent(&$content){ + $this->content=$content; + } + + + // Loading properties header (Загрузка свойства заголовка) + function getTitle(){ + return $this->title; + } + + // Loading a brief description of the properties (Загрузка свойства короткого описания) + function getShortDescription(){ + return $this->short_description; + } + + + // Loading properties description (Загрузка свойства описания) + function getDescription(){ + return $this->description; + } + + // Loading properties keywords (Загрузка свойства ключевых слов) + function getKeywords(){ + return $this->keywords; + } + + // Loading properties page header (Загрузка свойства заголовка страницы) + function getH1(){ + return $this->h1; + } + + + // Loading content properties (Загрузка свойств контента) + function getContent($isshow=false){ + return $this->content; + } + + // Loading from the database (Загрузка из базы данных) + function loadFromDB(){ + } + + + // It saves a file (Сохраняет в файл) + function saveToFile($FileName){ + + global $k2; + + $rez=$k2->rootdir.$FileName; + $cont='content().' ?>'; + file_put_contents($rez, $cont); + } + + + // Loading the file (Загрузка из файла) + function loadFromFile($FileName){ + + global $k2; + + $rez=$k2->rootdir.$FileName; + + if (file_exists($rez)){ + require_once($rez); + } + + } + + + + // Returns content (Возвращает контент) + function content(){ + + $rez=''; + $arr=$this->saveToArr(); + + + foreach ($arr as $k => $value ) { + $rez.='$this->'.$k.'="'.$this->SafeSym($value)."\";\n"; + } + + return $rez; + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2parser.php b/k2shop/k2shop/app/sys/k2parser.php new file mode 100644 index 0000000..6b2aca9 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2parser.php @@ -0,0 +1,94 @@ +parser->clearComment('',$html); + function clearComment($tag1, $tag2, &$html){ + + $str=$this->getTagValueSafe($tag1,$tag2,$html); + + while ($str<>false){ + + $html=str_replace($str, '', $html); + $str=$this->getTagValueSafe($tag1,$tag2,$html); + + } + + return $html; + } + + + + // Gets the text located between the two tag values (Получает текст, находящийся между 2 значениями тега) + // Returned item with tags (Возвращается элемент вместе с тегами) + // After running, the script will not be reduced by the size of the analyzed (После выполнения, скрипт НЕ уменьшается на проанализированный размер) + // $tag1 - beginning tag (начало тега) + // $tag2 - tag end (конец тега) + // $pos - item number with which to search for tags (номер позиции, с которой искать теги) + function getTagValueSafe($tag1, $tag2, &$html){ + $rez=''; + + $pos = strpos($html, $tag1); + $pos2 = strpos($html, $tag2, $pos); + + + if (($pos==false)or($pos2==false)){ + $rez=false; + }else{ + $rez=substr($html,$pos,$pos2-$pos+strlen($tag2)+1); + } + + $pos=$pos2; // Return back position (Возвращаем обратно позицию) + + return $rez; + } + + + // Gets the text located between the two tag values (Получает текст, находящийся между 2 значениями тега) + // After the script is reduced by the size of the analyzed (После выполнения, скрипт уменьшается на проанализированный размер) + // $tag1 - beginning tag (начало тега) + // $tag2 - tag end (конец тега) + // $pos - item number with which to search for tags (номер позиции, с которой искать теги) + // $deltags - Do remove tags (удалять ли теги) + function getTagValue($tag1, $tag2, &$html, $deltags=false){ + $rez=''; + + $pos = strpos($html, $tag1); + $pos2 = strpos($html, $tag2, $pos); + + + if (($pos==false)or($pos2==false)){ + $rez=false; + $html=''; + }else{ + + if ($deltags){ + $rez=substr($html,$pos+strlen($tag1),$pos2-$pos-strlen($tag1)); + }else{ + $rez=substr($html,$pos,$pos2-$pos+strlen($tag1)+1); + } + + $html=substr($html,$pos2+strlen($tag2)+1); + } + + $pos=$pos2; // Return back position (Возвращаем обратно позицию) + + return $rez; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2pathway.php b/k2shop/k2shop/app/sys/k2pathway.php new file mode 100644 index 0000000..3218102 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2pathway.php @@ -0,0 +1,88 @@ +{elements}'; // Template group (Шаблон для группы) + public $temp_el='
  • {caption}
  • '; // Template for items (Шаблон для элементов) + public $temp_last_el='
  • {caption}
  • '; // Template for the last elements (Шаблон для последнего элементов) + public $temp_act='class="active"'; // The pattern of the active element (Шаблон активного элемента) + + public $patharr = []; // Массив пути + + + // Installation path (Установка пути) + function setPathWay($arr){ + $this->patharr = $arr; + } + + // Cleaning bread crumbs (Очистка хлебной крошки) + function clear(){ + $this->patharr = []; + } + + // Add a breadcrumb element (Добавить один элемент хлебной крошки) + function add($url, $caption){ + $this->patharr[$url] = $caption; + //$arr = array($url => $caption); + //array_push($this->patharr, $arr); + } + + // Добавить весь путь + function addarr($arr){ + $this->patharr=array_merge($this->patharr, $arr); + } + + // Output of bread crumbs (Вывод хлебной крошки) + function getPathWay(){ + global $k2; + $rez = $this->temp_group; + + $items = ''; + $cnt = count($this->patharr); + $i = 1; + foreach ($this->patharr as $key => $value) { + + if ($i<>$cnt){ + $eltmp=$this->temp_el; + }else{ + $eltmp=$this->temp_last_el; + } + + $eltmp = str_replace('{url}', $k2->surl->SefURL_FromURL($key), $eltmp); + $eltmp = str_replace('{caption}', $value, $eltmp); + $eltmp = str_replace('{active}', $this->temp_act, $eltmp); + + $items .= $eltmp; + $i++; + } + + $rez = str_replace('{elements}', $items, $rez); + + if ($k2->root_url == $k2->surl->SefURL_FromURL($k2->getCurURL())) { + $rez = ''; + } + + return $rez; + } + + + // Returns content (Возвращает контент) + function content(){ + $rez=$this->getPathWay(); + return $rez; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2propis.php b/k2shop/k2shop/app/sys/k2propis.php new file mode 100644 index 0000000..3dd4930 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2propis.php @@ -0,0 +1,117 @@ + 'ноль', + 'ten' => array( + array('','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'), + array('','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять'), + ), + 'a20' => array('десять','одиннадцать','двенадцать','тринадцать','четырнадцать' ,'пятнадцать','шестнадцать','семнадцать','восемнадцать','девятнадцать'), + 'tens' => array(2=>'двадцать','тридцать','сорок','пятьдесят','шестьдесят','семьдесят' ,'восемьдесят','девяносто'), + 'handred' => array('','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот','восемьсот','девятьсот'), + 'unit' => array( + array('копейка' ,'копейки' ,'копеек', 1), + array('рубль' ,'рубля' ,'рублей' ,0), + array('тысяча' ,'тысячи' ,'тысяч' ,1), + array('миллион' ,'миллиона','миллионов' ,0), + array('миллиард','милиарда','миллиардов',0), + ) + ); + public $ukr=array('null' => 'ноль', + 'ten' => array( + array('','один','два','три','чотири',"п'ять",'шість','сім', 'вісім',"дев'ять"), + array('','одна','дві','три','чотири',"п'ять",'шість','сім', 'вісім',"дев'ять"), + ), + 'a20' => array('десять','одинадцять','дванадцять','тринадцять','чотирнадцять' ,"п'ятнадцять",'шістнадцять','сімнадцять','вісімнадцять',"дев'ятнадцять"), + 'tens' => array(2=>'двадцять','тридцять','сорок',"п'ятдесят",'шістдесят','сімдесят' ,'вісімдесят',"дев'яносто"), + 'handred' => array('','сто','двісті','триста','чотириста',"п'ятсот",'шістсот', 'сімсот','вісімсот',"дев'ятсот"), + 'unit' => array( + array('копійка' ,'копійки' ,'копійок', 1), + array('гривня' ,'гривні' ,'гривень' ,0), + array('тисяча' ,'тисячі' ,'тисяч' ,1), + array('мільйон' ,'мільйона','мільйонів' ,0), + array('мільярд','мільярда','мільярдів',0), + ) + ); + + + function num2str($num, $lngarr) { + $nul=$lngarr['null']; + $ten=$lngarr['ten']; + $a20=$lngarr['a20']; + $tens=$lngarr['tens']; + $hundred=$lngarr['handred']; + $unit=$lngarr['unit']; + + list($rub,$kop) = explode('.',sprintf("%015.2f", floatval($num))); + $out = array(); + + if (intval($rub)>0) { + foreach(str_split($rub,3) as $uk=>$v) { // by 3 symbols + if (!intval($v)) continue; + $uk = sizeof($unit)-$uk-1; // unit key + $gender = $unit[$uk][3]; + list($i1,$i2,$i3) = array_map('intval',str_split($v,1)); + + + $out[] = $hundred[$i1]; # 1xx-9xx + if ($i2>1) $out[]= $tens[$i2].' '.$ten[$gender][$i3]; # 20-99 + else $out[]= $i2>0 ? $a20[$i3] : $ten[$gender][$i3]; # 10-19 | 1-9 + + // units without rub & kop + if ($uk>1) $out[]= $this->morph($v,$unit[$uk][0],$unit[$uk][1],$unit[$uk][2]); + } //foreach + } + else $out[] = $nul; + + $out[] = $this->morph(intval($rub), $unit[1][0],$unit[1][1],$unit[1][2]); // rub + $out[] = $kop.' '.$this->morph($kop,$unit[0][0],$unit[0][1],$unit[0][2]); // kop + return trim(preg_replace('/ {2,}/', ' ', join(' ',$out))); + } + + /** + * Bow wordform (Склоняем словоформу) + * @ author runcore + */ + function morph($n, $f1, $f2, $f5) { + $n = abs(intval($n)) % 100; + if ($n>10 && $n<20) return $f5; + $n = $n % 10; + if ($n>1 && $n<5) return $f2; + if ($n==1) return $f1; + return $f5; + } + + // Returns the amount of words (Возвращает сумму прописью) + function getSumPropisRus($sumpropis){ + $rez=$this->num2str($sumpropis, $this->rus); + return $rez; + } + + // Returns the amount of words (Возвращает сумму прописью) + function getSumPropisUkr($sumpropis){ + $rez=$this->num2str($sumpropis, $this->ukr); + return $rez; + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2save.php b/k2shop/k2shop/app/sys/k2save.php new file mode 100644 index 0000000..5b1ed17 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2save.php @@ -0,0 +1,204 @@ +domain().'/'.$compname.'.php'; + + return $compname; + } + + + + // Search in the database content (Поиск контента в базе данных) + function searchContent($command){ + global $k2; + + $sql = "SELECT contentid FROM k2content WHERE (command='$command')"; + + $s=''; + + // Output line (Выводим строки) + foreach ($k2->db->query($sql) as $row) { + $s=$row['contentid']; + break; + } + + return $s; + + } + + + // Insert of the content in database (Вставка контента в базу данных) + function insContent(&$data, $obj, $command){ + global $k2; + + $title=$data['title']; + + $descript=$data['description']; + $short_description=$data['short_description']; + $p=$data['p']; + + $keywords=$data['keywords']; + $content=$data['content']; + $h1=$data['h1']; + + + $sql = "INSERT k2content (title, descript, keywords, content, command, parentcontent, h1, short_description) VALUES ('$title', '$descript', '$keywords', '$content', '$command', '$p','$h1','$short_description')"; + + echo "sqlinsert=$sql"; + + $s=''; + $s=$k2->db->exec($sql); + + return $s; + + } + + + // Update of the content in the database (Обновление контента в базе данных) + function updateContent(&$data, $obj, $command){ + global $k2; + + $title=$data['title']; + + $descript=$data['description']; + $short_description=$data['short_description']; + $p=$data['p']; + + $keywords=$data['keywords']; + $content=$data['content']; + $h1=$data['h1']; + + $sql = "UPDATE k2content set title='$title', descript='$descript', keywords='$keywords', content='$content', h1='$h1', short_description='$short_description', parentcontent='$p' WHERE (command='$command')"; + + echo "sqlupdate=$sql"; + + $s=''; + $s=$k2->db->exec($sql); + + return $s; + } + + + // Returns the name of the team (Возвращает название команды) + function getCommand($component_name, $p){ + global $k2; + + $command='component='.trim($component_name); + + if ($k2->isRoot()){ + $command.=';p='; + }else{ + $command.=';p='.trim($p); + } + + return $command; + } + + + // Saving the database (Сохранение в базе данных) + function saveToDB(&$data, $obj){ + $command=$this->getCommandObj($obj); + + // Check whether the content in the database (Проверяем есть ли контент в базе данных) + $contentid=$this->searchContent($command); + + if (trim($contentid)<>''){ + $this->updateContent($data, $obj, $command); + }else{ + $this->insContent($data, $obj, $command); + } + } + + + // Saving data (Сохранение данных) + function Save(&$data, $obj){ + global $k2; + + if ($k2->connect_db){ // Сохранить в базу данных + $this->saveToDB($data, $obj); + }else{ // Сохранять в файл + $this->page=$k2->ins_comp('k2page'); + $this->page->loadFromArr($data); + $this->page->saveToFile($this->SaveFileName($data['component'])); + } + } + + // Production Team (Получение команд) + function getCommandObj($obj){ + global $k2; + $command='component='.$obj->getTemplateName(); + + if ($k2->isRoot()){ + $command.=';p='; + }else{ + $command.=';p='.$k2->get('p'); + } + + return $command; + } + + + // Load from the database (Загрузка из базы данных) + function LoadFromDB(&$obj){ + global $k2; + $command=$this->getCommandObj($obj); + + $command=$k2->get('p'); + $sql = "SELECT k2menuitemid, title, descript, keywords, content, command, parentid, h1, script FROM k2menuitems WHERE command=:command"; + $r = $k2->sql->sel($sql,['command'=>$command]); + + $s=''; + + + // Выводим строки + foreach ($r['data'] as $row) { + + $obj->page->isloadedcontent=true; + $obj->page->title=$row['title']; + + $obj->page->description=$row['descript']; + + $obj->page->keywords=$row['keywords']; + $obj->page->content=$row['content']; + $obj->page->h1=$row['h1']; + $obj->page->script=$row['script']; + + break; + } + + return $s; + } + + // Loading data (Загрузка данных) + function Load(&$obj){ + $this->LoadFromDB($obj); + return ''; + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2secur.php b/k2shop/k2shop/app/sys/k2secur.php new file mode 100644 index 0000000..340761e --- /dev/null +++ b/k2shop/k2shop/app/sys/k2secur.php @@ -0,0 +1,244 @@ +admin_menus=[]; + + // Супер-админу список не нужен, т.к. он может все + if ($k2->auth->isSuperAdmin()) return; + + $mnu=$k2->sql->sel('SELECT namemenu, module_name, active, url FROM k2admin_menus WHERE (del=0) '); + + foreach ($mnu['data'] as $el){ + $this->admin_menus[$el['namemenu']]=['active'=>$el['active'], 'url'=>$el['url'] ]; + } + } + + + + + // Загрузка прав + function loadMenuPrav(){ + global $k2; + $this->k2admin_menus_prava=[]; + + // Супер-админу список не нужен, т.к. он может все + if ($k2->auth->isSuperAdmin()) return; + + + $add_roles=',1000001'; + if ($k2->auth->isAuth()){ + $add_roles.=',1000000'; + } + + $roleid=$k2->auth->roleid; + if (trim($k2->auth->roleid)=='' or !$k2->auth->isAuth()){ + $roleid='1000001'; + } + + + $prav=$k2->sql->sel("select + p.pravrepid, p.menuid, p.username, p.r, p.w, p.i, p.d, p.c, p.exp, p.imp, + p.settable, p.cutpast, p.enable, p.magazinsid, am.namemenu, am.module_name + + from k2admin_menus_prava p + + join k2roles r + on p.roleid=r.roleid + + join k2admin_menus am + on p.menuid=am.menuid + + where (p.roleid in (:roleid $add_roles )) + and(p.del=0)and(p.active=1) + + order by r.order_roles + + ", ['roleid'=>/*$k2->auth->roleid*/$roleid] ); + + foreach ($prav['data'] as $el){ + + if (!isset($this->k2admin_menus_prava[$el['namemenu']])){ + $this->k2admin_menus_prava[$el['namemenu']]= + [ + 'r'=>$el['r'], + 'w'=>$el['w'], + 'i'=>$el['i'], + 'd'=>$el['d'], + 'c'=>$el['c'], + 'exp'=>$el['exp'], + 'imp'=>$el['imp'], + 'settable'=>$el['settable'], + 'cutpast'=>$el['cutpast'], + 'enable'=>$el['enable'], + 'magazinsid'=>$el['magazinsid'] + ]; + } + } + + //var_dump($this->k2admin_menus_prava); + + } + + + + // Поиск прав для заданного объекта и текущей роли или пользователя + // $class_name - название класса. + function searchPrav($class_name){ + global $k2; + + $rez=[]; + + if (isset($this->k2admin_menus_prava[$class_name])){ + $rez=$this->k2admin_menus_prava[$class_name]; + } + + return $rez; + } + + + + // Защита строк + function mySecurEncode($str){ + $rez=$str; + + $rez=str_replace('', '#k2-2#?', $rez); + + $rez=str_replace('', '#k2-4#?', $rez); + + $rez=str_replace('', '#k2-6#?', $rez); + + return $rez; + } + + function mySecurDecode($str){ + $rez=$str; + + $rez=str_replace('#k2-1#?', '', $rez); + + $rez=str_replace('#k2-3#?', '', $rez); + + $rez=str_replace('#k2-5#?', '', $rez); + + return $rez; + } + + + // Protection of variables in $ _GET (Защита переменных в $_GET) + function SecurGet(){ + // Экранируем все переменные в GET + foreach ($_GET as $inx => $val) { + $_GET[$inx] = $this::mySecurEncode($_GET[$inx]); + } + } + + // Protection of variables in $ _POST (Защита переменных в $_POST) + function SecurPost(){ + // Экранируем все переменные в POST + foreach ($_POST as $inx => $val) { + $_POST[$inx] = $this::mySecurEncode($_POST[$inx]); + } + } + + // Protection of the variables in the Cookies (Защита переменных в Cookies) + function SecurCook(){ + // Экранируем все переменные в COOKIES + foreach ($_COOKIE as $inx => $val) { + /*$_SAVECOOKIE*/ $_COOKIE[$inx] = $this::mySecurEncode($_COOKIE[$inx]); + $_SAVECOOKIE[$inx] = $_COOKIE[$inx]; + } + } + + + // Protection of all parameters (Защита всех параметров) + // Escapes parameters in all variables (Экранирует параметры во всех переменных) + // used with caution, because thereafter, the program can not run portion (применять осторожно, т.к. после этого, могут не работать программные части) + function SecurAll(){ + $this->SecurGet(); + $this->SecurPost(); + $this->SecurCook(); + } + + // Get Protection variable or POST (Защита переменной Get или POST) + function secur($value){ + $rez = $this::mySecurEncode($value); + return $rez; + } + + + // Protected receive $ _GET parameters (Защищенное получение параметров $_GET) + function get($varname, $safe=true){ + + $rez=''; + + if (isset($_GET[$varname])){ + $rez=$_GET[$varname]; + }else{ + $rez=''; + } + + if ($safe){ + $rez=$this->secur($rez); + } + + return $rez; + } + + // Protected receive parameters $ _POST (Защищенное получение параметров $_POST) + function post($varname, $safe=true){ + $rez=''; + + if (isset($_POST[$varname])){ + $rez=$_POST[$varname]; + }else{ + $rez=''; + } + + if ($safe){ + $rez=$this->secur($rez); + } + + return $rez; + } + + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2sendMess.php b/k2shop/k2shop/app/sys/k2sendMess.php new file mode 100644 index 0000000..96924a9 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2sendMess.php @@ -0,0 +1,80 @@ +check_connect(); + + } + /** + * Отправка сообщений + * @global type $k2 + * $kol_mess- количество писем + * + */ + + function mailsSend($kol_mess=''){ + global $k2; + if($kol_mess==''){ + $const = $k2->ins_comp('k2const'); + $kol_mess=$const->getConst('kol_mess'); + } + + $ksql=$k2->ins_comp('k2sql'); + + $rez = ''; + //Получение порции + $re = $ksql->sel("SELECT MAX(CAST(portions AS SIGNED)) + FROM k2message" + ); + $portions=$re['data'][0][0]+1; + + $mail=$ksql->sel('SELECT id_message, date_formation, email, subj, message FROM k2message WHERE status=0 ORDER BY date_formation DESC LIMIT '.$kol_mess); + + + foreach($mail['data'] as $item){ + //if($mailto<>''){ + $headers = "Content-type: text/html; charset=utf-8\r\n"; + $mailto = $item['email']; + //$mailto = 'vasylyuk@corp2.net'; + $subj = $item['subj']; + $mess = $item['message']; + mail($mailto, $subj, $mess, $headers); + + $ksql->upd( + "UPDATE k2message + SET + status=:status, + date_send=:date_send, + portions=:portions + + WHERE (id_message=:id_message)", + ['id_message'=>$item['id_message'], + 'status'=>1, + 'portions'=>$portions, + 'date_send'=>'{now}' + ] + ); + + + + $rez .= 'Сообщение отправлено...'; + /* }else{ + $rez . 'Email отсутствует!!'; + }*/ + } + } +} diff --git a/k2shop/k2shop/app/sys/k2site.php b/k2shop/k2shop/app/sys/k2site.php new file mode 100644 index 0000000..b87531f --- /dev/null +++ b/k2shop/k2shop/app/sys/k2site.php @@ -0,0 +1,1468 @@ +'/k2shop/k2shop/libs/phpgrid/phpgrid-full-v2.0/lib/']; + + public $logo = ''; // Logo (Логотип) + + public $tag_comp = []; // Tags component (the array is removed from the template) (Теги компонент (массив извлекается из шаблона)) + + public $hidecomments = true; // Hide the comments (Скрывает комментари) + + public $pathway; // Компонента "Хлебная крошка" + + public $main_path_tpl = 'HOME'; + + public $siteid = ''; + + public $projid = ''; + + public $mainfirmid = '1'; + + public $cliadmpanel = true; // Определяет вывод админ панели для не админа + + public $cabinet = ''; + + public $reg_menu="
  • {Registration}
  • +
  • {Partners}
  • "; + + public $unreg_menu="
  • {Exit}
  • "; + + public $lang='
    +
    + '; + public $is_slug = false; + public $option=''; + + public $langscript=' + '; + public $ish1 = false; + public $imgLogo = ''; + public $lng_tpl_ua = ''; + public $lng_tpl_ru = ''; + public $lng_tpl_en = ''; + public $lng_tpl_es = ''; + public $lng_tpl_ar = ''; + public $cart = ''; + public $mainmenuid = ''; + public $curmenuid = ''; + public $is_get_right = true; + public $adminlogo = 'К2® + Корпорация 2®'; + public $versiontext = 'Version {ver}'; + public $admcopyright = 'Copyright © 2000-2020 К2 ®. Все права защищены.'; + public $userimage = 'User Image'; + + public $is_pathway = true; + + public $is_dblog = true; + + protected function init_obj(){ + global $k2; + $this->addJS('jquery.min.js',$this->libs['jquery.min.js']."js/jquery.min.js"); + $this->addCSS('font-awesome.min.css',"//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"); + $this->addCSS('w3.css',"/public/css/w3.css"); + $this->pathway=$k2->ins_comp('k2pathway'); + if ($this->main_path_tpl !== '') { + $this->pathway->add('/', $this->main_path_tpl); + } + //Вызываем стили кнопки редактирования включаемых областей + if( ($k2->auth->isAdmin()) && ($k2->auth->isDesignMode()) ) { + $inc = $k2->ins_comp('k2inc'); + $this->addHead('style', $inc->inc_edit_button_template); + $this->addCSS('jqx.base.css',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/styles/jqx.base.css"); + + $this->addJS('jqxcore.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxcore.js"); + $this->addJS('jqxloader.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxloader.js"); + $this->addJS('jqxtooltip.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxtooltip.js"); + $this->addJS('jqxwindow.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxwindow.js"); + $this->addJS('jqxbuttons.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxbuttons.js"); + $this->addJS('jqxpanel.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxpanel.js"); + $this->addJS('jqxtabs.js',"/k2shop/k2shop/libs/jqwidgets/jqwidgets/jqxtabs.js"); + + + } + } + + + + // Replacing an array of values (Замена значений по массиву) + // $arr - an array with the list of replacements (массив с перечнем замен) + // $html - processed html (обрабатываемый html) + function arrReplace($arr, &$html){ + if (is_array($arr) || is_object($arr)) + { + foreach ($arr as $key) { + $html = str_replace($key[0], $key[1], $html); + } + } + + } + + + // Installation SEO (Установка SEO) + function setSEO(&$html){ + global $k2; + + // Replacement before certain tags (Замена переопределенными тегами) + foreach ($this->tegs as $key => $value) { + $html = str_replace($key, $value, $html); + } + + + // Replacing the main tag (Замена основными тегами) + $arr= [ + ['{seo}', $this->seo()], + ['{scriptend}', $this->getScriptend()], + ['{title}', $this->getTitle()], + ['{namesite}', $this->getNamesite()], + ['{keywords}',$this->getKeywords()], + ['{description}',$this->getDescription()], + ['{h1}',$this->getH1()], + ['{class}',$this->getBodyClass()], + ['{cli_logo}', $this->getLogo()], + ['{version}', $this->versiontext], + ['{ver}', $k2->version], + ['{admcopyright}', $this->admcopyright], + ['{userimage}', $this->userimage], + ['{firstword}', strtoupper($k2->auth->login{0})], + ['{username}', $k2->auth->username], + ['{login}', $k2->auth->login], + ['{rolename}', $k2->auth->rolename], + ['{fullusername}', $k2->auth->getFullUserName()], + ['{adminlogo}', $this->adminlogo], + ['{email}', $k2->auth->email], + ['{sociallink}', $this->getSocial()], + ['{searchform}', $this->getSearch()], + ['{notification}', $this->getNotification()], + ['{firmphone}', $this->getRequisites('phone_firm')], + ['{firmaddress}', $this->getRequisites('adress_firm')], + ['{firmemail}', $this->getRequisites('email')], + ['{worktime}', $this->getRequisites('comment')], + //array('', ''), + //array('{altauth}', $k2->altauth->checkPassword()), + ['{auth}', $k2->auth->tempAuth()], // Recycle information on authorization (Заменяю информацию о авторизации) + ['{username}', $k2->auth->username], // Insert your username (Вставляет имя пользователя) + ['{login}', $k2->auth->login], // Inserts login (Вставляет логин) + ['{pathway}', $this->is_pathway ? $this->pathway->content() : ''], // Хлебная крошка + //['{authphoto}', $k2->auth->photo], // Inserts login (Вставляет логин) + ['{authphone}', $k2->auth->phone], // Inserts login (Вставляет логин) + ['{authcountryid}', $k2->auth->countryid], // Inserts login (Вставляет логин) + ['{authcityid}', $k2->auth->cityid], // Inserts login (Вставляет логин) + ['{id}', isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''], // Хлебная крошка + + ]; + + + // Stripping unidentified tags (Зачистка не установленных тегов) + foreach ($this->clear_tegs as $key => $value) { + $html=str_replace($key, $value, $html); + } + $html = str_replace('{design}', $this->Translate("{lnDesign}"), $html); + $html = str_replace('{profile}', $this->Translate("{lnProfile}"), $html); + if(!$k2->auth->isAuth()){ + $html = str_replace('{sign_out}', $this->Translate("{lnSignIn}"), $html); + } else { + $html = str_replace('{sign_out}', $this->Translate("{lnSignOut}"), $html); + } + + $html = str_replace('{search}', $this->Translate("{lnSearch}"), $html); + $html = str_replace('{lnAdminPanel}', $this->Translate("{lnAdminPanel}"), $html); + $html = str_replace('{lnMainMenu}', $this->Translate("{lnMainMenu}"), $html); + $html = str_replace('{lnProfile}', $this->Translate("{lnProfile}"), $html); + return $this->arrReplace($arr, $html); + } + + + // Installation of the Admin (Установка Админ-части) + function setAdmin(&$html){ + + global $k2; + + if (!isset($k2->admin)){ + $k2->admin=$k2->ins_comp('k2admin'); + } + + $admin_html=$k2->admin->AdminPage($html); + $html=str_replace('{admin}', $admin_html, $html); + //$html=str_replace('{maincontent}', $admin_html, $html); + + } + + + // Replace the path to the templates in order to get the correct path (Заменяет пути в шаблонах для того, чтоб получить корректный путь) + function setPath(&$html){ + + $arr= [ + ['"css/', '"'.$this->path_template.'/css/'], + ['"js/', '"'.$this->path_template.'/js/'], + ['"bootstrap/css/', '"'.$this->path_template.'/bootstrap/css/'], + ['"images/', '"'.$this->path_template.'/images/'], + ['"style.css', '"'.$this->path_template.'/style.css'], + ['"bootstrap/', '"'.$this->path_template.'/bootstrap/'], + ['"plugins/', '"'.$this->path_template.'/plugins/'], + ['"libraries/', '"'.$this->path_template.'/libraries/'], + ['"assets/', '"'.$this->path_template.'/assets/'], + + ['{template_path}', $this->path_template] + ]; + + return $this->arrReplace($arr, $html); + } + + /** + * Находит и возвращает массив всех включаемых областей с тегом $tagName + * $tagName - string - Искомый тег + * @return array - массив с редактируемыми областями. + */ + function getTags($reqTagName) { + + $tagsArray = $this->tag_comp; + $tagToFind = $reqTagName; + + $incTagsArray = []; + + + foreach ($tagsArray as $tagName) { + if ( strpos($tagName,$tagToFind) ) { + array_push($incTagsArray, $tagName); + } + } + + return $incTagsArray; + } + + /** + * Декодируем все теги $reqTagName для подключения компоненты c нужным темплейтом. + * @return array - массив массивов декодированых тегов {inc ...} + */ + function getDecodedTags($reqTagName) { + + $tagsArray = $this->getTags($reqTagName); + + $resultArray = []; + + foreach ($tagsArray as $tagName) { + $resultArray[$tagName] = $this->decodeTag($tagName)[1]; + } + + return $resultArray; + } + + + // Displays include area (Вывод включаемой области) + function getInc($command){ + global $k2; + $inc = $k2->ins_comp('k2inc'); + $inc->incID = $command; + return $inc->content(); + } + + //вывод контента компоненты + function getInsComp($command){ + global $k2; + + $comparr = explode(" ",$command); + + $comp = explode("_",$comparr[0]); + $inscomp = $k2->ins_comp($comp[0], $comp[1]); + $func = $comparr[1]; + if ($func) { + $rez = $inscomp->$func(); + } else { + $rez = $inscomp->content(); + } + + return $rez; + } + + /** + * Вставляет контент из включаемых областей {inc ...} в зависимости от названия тега + * @param type $html string + * @return type string + */ + function incComponents(&$html){ + + $arr = []; + + + foreach($this->getDecodedTags('inc ') as $key => $value) { + + $content = $this->getInc($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + + /** + * + * @param type $html + * @return type + */ + function insComp(&$html) + { + $arr = []; + + + foreach($this->getDecodedTags('inscomp') as $key => $value) { + + $content = $this->getInsComp($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * + * @global type $k2 + * @param type $command + * @param type $curmenuid + * @return type + */ + function getAddMenuCont($command, $contentid, $curmenuid = '', $temp, $item = false) + { + global $k2; + $inc = $k2->ins_comp('k2inc'); + + $inc -> incID = $command; + $inc -> menuid = $curmenuid; + $inc -> contentID = $contentid; + $inc -> temp_name = $temp; + $inc -> is_item = $item; + + return $inc->content(); + } + + /** + * + * @param type $html + * @return type + */ + function contsComponents(&$html) + { + global $k2; + + $i = 0; + + foreach($this->getDecodedTags('conts') as $key => $value) { + $arr_cont = explode('_',$value); + $arr = []; + $content = ''; + $short = ''; + $count = $arr_cont[1]; + if(!$count){ + $count = 10; + } + $pageroll = $arr_cont[2]; + //$temp = $arr_cont[2]; + + $conts = $k2->ins_comp('k2cont'); + $col = $conts->getRecordsCol($arr_cont[0], $arr_cont[0], ''); + $p_name = $conts->getContsTitleByCommand($arr_cont[0]); + $records = $conts->getRecords($count, $arr_cont[0], $arr_cont[0], '', '' ,$start); + $p_num = $col[0]['p_num']; + if ($k2->get('item') !== '') { + + $contentid = $k2->get('item'); + if ($this->is_slug) { + $contentid = $conts->getIdBySlug($contentid); + } + $content .= $this->getAddMenuCont($arr_cont[0], $contentid, 2, $temp, true); + + $content = str_replace('{p_num}', $p_num, $content); + $content = str_replace('{p_name}', $p_name, $content); + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + + return $this->arrReplace($arr, $html); + } else { + $content .= $conts->above_tpl; + $start = 0; + if($pageroll==1){ + $pages = $k2->ins_comp('k2pageroll'); + + $pages->kol_page = $count; + $start = $pages->getPos(); + $col = $col[0][0]; + $pages->max_kol = $col; + $pages->mainurl = 'p/'.$k2->get('p'); + $records = $conts->getRecords($count, $arr_cont[0], $arr_cont[0], '', '' ,$start); + } + if($pageroll == 1){ + $short .= $pages->content(); + } + foreach ($records as $record) { + $short .= $this->getAddMenuCont($arr_cont[0], $record['contentid'], 2, $arr_cont[2]); + } + if($pageroll == 1){ + $short .= $pages->content(); + } + $content = str_replace('{command}', $arr_cont[0], $content); + $content = str_replace('{short_tpl}', $short, $content); + $content = str_replace('{p_num}', $p_num, $content); + $content = str_replace('{p_name}', $p_name, $content); + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + + $this->arrReplace($arr, $html); + } + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + return $this->arrReplace($arr, $html); + } + + + + /** + * Вставляет контент из включаемых областей {menu} в зависимости от названия тега + * @param type $html string + * @return type string + */ + function incMenuComponents(&$html){ + + $arr = []; + + + foreach($this->getDecodedTags('menu') as $key => $value) { + + $content = $this->getMenu($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * Заменяем все теги {slider ...} на соответствующий контент + * @param type $html + * @return type + */ + public function incSliderComponents(&$html){ + + $arr= []; + + foreach($this->getDecodedTags('slider') as $key => $value) { + + $content = $this->getSlider($value); + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + + } + return $this->arrReplace($arr, $html); + } + + /** + * Получает контент для слайдера по его имени из указанной компоненты + * @param type $sliderName - имя слайдера + * @return type - код слайдера + */ + public function getSlider($sliderName) { + global $k2; + $slider = $k2->ins_comp('k2slider'); + $slider->sliderName = $sliderName; + + return $slider->content(); + } + + /** + * Заменяем все теги {portfolio ...} на соответствующий контент + * @param type string $html + * @return type mixed + */ + public function incPortfolioComponents(&$html){ + + $arr = []; + + foreach($this->getDecodedTags('portfolio_new') as $key => $value) { + + $content = $this->getPortfolio($value); + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + + } + return $this->arrReplace($arr, $html); + } + + /** + * Получает контент для портфолио по его имени из указанной компоненты + * @param type string $portfolioOptions - опции портфолио + * @return type string - код портфолио + */ + public function getPortfolio($portfolioOptions) { + global $k2; + $portfolio = $k2->ins_comp('k2portfolio'); + $portfolio->portfolioRowItemsQty = $portfolioOptions; + + return $portfolio->content(); + } + + + /** + * Заменяет все теги {products ...} на соответствующий контент + * @param type $html + * @return type + */ + public function incProductsComponents(&$html){ + + $arr= []; + + foreach($this->getDecodedTags('products') as $key => $value) { + + $content = $this->getProducts($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * Получает контент для вывода продуктов в зависимости от указанного типа + * @param type $productContentType - тип контента | featured | categoryTab | recomended | list + * @return type string HTML + */ + public function getProducts($productContentType) { + global $k2; + + $products = $k2->ins_comp('shop','products'); + $products->productContentType = $productContentType; + + return $products->getProductsContent(); + } + + /** + * Заменяет все теги {filter ...} на соответствующий контент + * @param type $html + * @return type + */ + public function incFilterComponents(&$html){ + + $arr= []; + + foreach($this->getDecodedTags('filter2') as $key => $value) { + + $content = $this->getFilters($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * Получает контент для вывода продуктов в зависимости от указанного типа + * @param type $productContentType - тип контента | featured | categoryTab | recomended | list + * @return type string HTML + */ + public function getFilters($filterContentType) { + global $k2; + + $filer = $k2->ins_comp('shop','filter'); + $filer->filterContentType = $filterContentType; + + return $filer->getFilterContent(); + } + + /** + * + * @param type $html + * @return type + */ + public function incButtonComponents(&$html){ + + $arr= []; + + foreach($this->getDecodedTags('order_buttons') as $key => $value) { + + $content = $this->getButton($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * + * @global type $k2 + * @param type $filterContentType + * @return type + */ + public function getButton() { + global $k2; + + $button = $k2->ins_comp('k2transferpub','button'); + //$button->buttonContentType = $buttonContentType; + + return $button->getButtonContent(); + } + + + /** + * + * @param type $html + * @return type + */ + public function incCabinetComponents(&$html){ + + $arr= []; + + foreach($this->getDecodedTags('cabinet') as $key => $value) { + + $content = $this->getCabinet($value); + + $tagArr = [$key, $content]; + array_push($arr, $tagArr); + } + + return $this->arrReplace($arr, $html); + } + + /** + * + * @global type $k2 + * @param type $filterContentType + * @return type + */ + public function getCabinet() { + global $k2; + + $button = $k2->ins_comp('k2transferpub','cabinet'); + + return $button->getCabinetContent(); + } + + // Replacing the component template (Замена шаблон компонент) + function setComponents(&$html){ + + + $arr= [ + ['{logo}', $this->logo()], + ['{copyright}', $this->getCopyright()], + ['{counter}', $this->getCounter()], + + ['{menu}', $this->getMenu()], + ['{banner}', $this->getBanners()], + ['{lang}', $this->getLang()], + ['{lng}', $this->getLng()], + //['{cabinet}', $this->getCabinet()], + //array('{inc}', $this->getInc() ), + ['{maincontent}', $this->getContent(true).' {admin} '], + //['{cart}', $this->getCart()], + ]; + + return $this->arrReplace($arr, $html); + + } + + + // Removing the component and its parameters (Извлечение компоненты и её параметров) + // The function returns an array, the first element of which - the name of the component, and the second - a template. (Функция возвращает массив, в первом элементе которого - название компоненты, а во второй - шаблон.) + function decodeTag($tag){ + + // Убираем скобки, чтоб не мешали + $tag=str_replace('{', '', $tag); + $tag=trim(str_replace('}', '', $tag)); + + $pos=strpos($tag, ' '); + + if ($pos==false){ + $val=''; + $comp=$tag; + }else{ + $val=trim(substr($tag, $pos)); + $comp=trim(substr($tag, 0, $pos)); + } + + + return array($comp, $val); + } + + + // Return the name of the components depending on tag (Возвращаем название компоненты в зависимости от тега) + function getComponentName($tag){ + + $rez = ''; + + $arr = [ + ['menu', 'k2menu'], + ['banner', 'k2banners'], + //array('inc', 'k2inc') + ]; + + foreach ($arr as $key) { + + if (trim($key[0]) == trim($tag)){ + $rez = trim($key[1]); + break; + } + } + + return $rez; + + } + + + // Execution component parameters (Выполнение компонент с параметрами) + function setVarComponents(&$html){ + + global $k2; + + foreach ($this->tag_comp as $key) { + + $tag=$this->decodeTag($key); + + if (count($tag)>0){ + $componetname=$this->getComponentName($tag[0]); + + if (trim($componetname)<>''){ + + // Creating components (Создаем компоненты) + $comp=$k2->ins_comp($componetname,$tag[1]); + if (isset($comp)){ + $cont = $comp->content(); + } + + // Replace tags on components of the output result (Заменяем теги на результат вывода компоненты) + $html=trim(str_replace($key, $cont, $html)); + + } + } + + + } + + + return $html; + } + + + /** + * Возвращает меню в зависимости от указанного тега $menuId + * @param type $menuId - тег для идентификации меню + * @return type HTML код меню + */ + function getMenu(){ + + global $k2; + + $menu = $k2->ins_comp('k2menu'); + $menu->menuID = $menuId; + + return $menu->content(); + } + + + // Returns banner (Возврщает баннера) + function getBanners(){ + + global $k2; + + $menu=$k2->ins_comp('k2banners'); + + return $menu->content(); + + } + + // Return content (Вывод контента) + function getContent($isshow = false){ + + global $k2; + + $content = $k2->ins_comp('k2content'); + + // Setting the main content header (Установка заголовков главного контента) + if (trim($content->page->title)<>''){ + $this->title=$content->page->title; + } + + if (trim($content->page->description)<>''){ + $this->description=$content->page->description; + } + + if (trim($content->page->keywords)<>''){ + $this->keywords=$content->page->keywords; + } + + if (trim($content->page->h1)<>''){ + $this->h1=$content->page->h1; + } + + $cont = ''; + + if ($k2->message_on){ + $cont .= $k2->message->content(); + } + + $cont .= $content->content(); + + return $cont; + } + + + + // It retrieves the relative path of the directory where the template out of the way components are loaded file (Извлекает относительный путь каталога, где находится шаблон из пути загружаемого файла компоненты) + function getPathTemplate($path){ + global $k2; + $pathtmp=$path; + + $pathtmp=str_replace($k2->rootdir, '', $pathtmp); + $pathtmp=dirname($pathtmp); + + return $pathtmp; + } + + + // Returns the path to the logo (Возвращает путь к логотипу) + function logo(){ + return $this->logo; + } + + + + // We get the list of scripts and styles that you want to display in the head (Получаем список скриптов и стилей, которые нужно выводить в head) + function getHead(){ + global $k2; + $rez="\n"; + + foreach ($this->head as $key => $value) { + $rez.=$value."\n"; + } + + return $rez; + } + + function getScriptend(){ + global $k2; + $rez="\n"; + foreach ($this->scriptend as $key => $value) { + $rez.=$value."\n"; + } + + return $rez; + + } + + // Add style (Добавить стиль) + function addCSS($key, $filename){ + global $k2; + $this->head[$key]=""; + } + + + // Добавить стиль + function addCSS_Script($key, $script){ + global $k2; + $this->head[$key]=""; + } + + + // Add the script (Добавить скрипт) + function addJS($key, $filename){ + global $k2; + $this->head[$key]=""; + } + + // Add the script (Добавить Java-скрипт) + function addJavaScript($key, $script){ + global $k2; + $this->head[$key]=""; + } + + // Add the script (Добавить текст в заголовок) + function addHeadText($key, $text){ + global $k2; + $this->head[$key]=$text; + } + + //Add siteheart + function addSiteHeart($key, $script){ + global $k2; + + $json = '{}'; + if (!$k2->auth->isAuth()){ + $json = '{nick:"'.$k2->auth->login.'",id:"'.$k2->auth->userid.'",email:"'.$k2->auth->email.'"}'; + } + $time = time(); + $secret = "xbc6J40MY7"; + $user_base64 = base64_encode( json_encode($json) ); + $sign = md5($secret . $user_base64 . $time); + $auth = $user_base64 . "_" . $time . "_" . $sign; + + $script = str_replace('{authsite}', $auth, $script); + + $this->addJavaScriptEnd($key, $script); + } + + // Add the script to the end (Добавить Java-скрипт в конец) + function addJavaScriptEnd($key, $script){ + global $k2; + + $this->scriptend[$key]=""; + } + + // Add a script to the end of the file (Добавить скрипт в конец файла) + function addJSEnd($key, $filename){ + global $k2; + $this->scriptend[$key]=""; + } + + // Add custom text to the head (Добавить произвольный текст в head) + function addHead($key, $script){ + global $k2; + $this->head[$key]="$script"; + } + + // Add custom text to the head (Добавить произвольный текст в head) + function addTopHead($key, $script){ + global $k2; + $tophead = [$key=>$script]; + $this->head = $tophead + $this->head; + } + + // Add Taggs (Добавление тегов) + function addTeg($key, $script){ + global $k2; + $this->tegs[$key]="$script"; + } + + + // Tagging stripper (Добавление тегов для зачистки) + // By default, trimmed to the void. But, if necessary, another value can be set (По умолчанию, зачищается на пустоту. Но, при необходимости, можно устанавливать другое значение) + function addClearTeg($key, $script=''){ + global $k2; + $this->clear_tegs[$key]="$script"; + } + + + + + // Displays SEO-block (Выводит SEO-блок) + function seo(){ + $rez='{title}'."\n" + .''."\n" + .''."\n" + .''."\n"; + + $rez.=$this->getHead(); + + + return $rez; + } + + // Returns the name of the site (Возвращает название сайта) + function getNamesite(){ + return $this->namesite; + } + + // Returns the title of the page (Возвращает заголовок страницы) + function getTitle(){ + return $this->title; + } + + + // Установка заголовка + function setTitle($title=''){ + $this->title=$title; + } + + // Установка ключевых слов + function setKeywords($keywords=''){ + $this->keywords=$keywords; + } + + // Установка description + function setDescription($description=''){ + $this->description=$description; + } + + // Returns keywords page (Возвращает ключевые слова страницы) + function getKeywords(){ + return $this->keywords; + } + + // Returns a description of the page (Возвращает описание страницы) + function getDescription(){ + return $this->description; + } + + // Return header H1 (Возврат заголовка H1) + function getH1(){ + return $this->h1; + } + + // Setting header H1 (Установка заголовка H1) + function setH1($h1){ + $this->h1=$h1; + } + + + // Returns page copyright (Возвращает копирайт страницы) + function getCopyright(){ + return $this->copyright; + } + + // Inserts counter (Вставляет счетчик) + function getCounter(){ + return $this->counter; + } + + function getBodyClass(){ + global $k2; + $rez = ''; + if ($k2->lng == 'ar'){ + $rez = 'class="arabic"'; + } + return $rez; + } + + // Inserts cart (Вставляет корзину) + function getCart(){ + global $k2; + + $cart = $k2->ins_comp('k2newshop','cart'); +// + $rez = $cart->getCart(); +// +// + //$rez = $this->cart; + + //$rez = str_replace('{koltov}', $koltov, $rez); + + + return $rez; + } + + // Inserts lang (Вставляет переключатель языков) + function getLng(){ + global $k2; + $cur_lng_tpl = 'lng_tpl_'.$k2->lng; + $rez = $this->$cur_lng_tpl; + return $rez; + } + + // Inserts lang (Вставляет переключатель языков) + function getLang(){ + global $k2; + + $sql = 'select * from k2lang where lang_active=1 ORDER BY ord'; + + $rez = $this->lang; + try { + foreach ($k2->db->query($sql) as $value) { + $option .= $this->option; + $option = str_replace('{valtpl}', '{lng}', $option); + $option = str_replace('{LANG}', $value['commentlang'], $option); + $option = str_replace('{langname}', $value['langname'], $option); + $option = str_replace('{lng}', $value['langid'], $option); + $option = str_replace('{sel}','{'.$value['langid'].'sel}', $option); + }; + }catch (Exception $e) { + echo "Ошибка : ".$sql.$e->getMessage()."\n"; + } + + $rez = str_replace('{options}', $option, $rez); + $rez = str_replace('{'.$k2->lng.'sel}', 'selected', $rez); + + $rez .= $this->langscript; + $rez = str_replace('{lngtpl}', $k2->getUrl('&lng'), $rez); + return $rez; + } + + // Inserts lang (Вставляет логотип) + function getLogo(){ + global $k2; + + $rez=$this->imgLogo; + if($this->imgLogo<>''){ +// if($k2->auth->isAuth()){ +// $sql='select icon, type_acc_transfid from k2_partner_trans where login= "'.$k2->auth->login.'" '; +// +// foreach ($k2->db->query($sql) as $value) { +// if((($value['icon']!=='')&&($value['icon']!==null))&&($value['type_acc_transfid'])==1){ +// $rez=str_replace('{logopath}', $value['icon'], $rez); +// +// }else{ +// $rez=str_replace('{logopath}', 'img/logo2.png', $rez); +// } +// } +// }else{ +// $rez=str_replace('{logopath}', 'img/logo2.png', $rez); +// }; + + $rez=str_replace('{logopath}', 'img/logo2.png', $rez); + } + return $rez; + } + + + function getNotification () { + global $k2; + $not = $k2->ins_comp('k2notification'); + return $not->content(); + } + + function getSearch () { + global $k2; + $soc = $k2->ins_comp('k2search'); + return $soc->searchForm(); + } + + function getSocial () { + global $k2; + $soc = $k2->ins_comp('k2sociallink'); + return $soc->formSocLinks(); + } + + function getRequisites ($arg) + { + global $k2; + $k2->sql->db = $this->db; + $r = $k2->sql->sel("select firmid, name_firm, adress_firm, phone_firm, email, comment + from k2firms + where firmid=:firmid", + ['firmid'=>$this->mainfirmid]); + + $rez = $r['data'][0][$arg]; + + + return $rez; + } + + // Deleting comments (Удаление комментария) + function clearComment($tag1, $tag2, &$html){ + global $k2; + return $k2->parser->clearComment($tag1, $tag2, $html); + } + + + + // Deleting comments (Удаление комментариев) + function delComment(&$html){ + + $this->clearComment('',$html); + $this->clearComment('',$html); + $this->clearComment('',$html); + $this->clearComment('/*','*/',$html); + + } + + + // Gets the text located between the two tag values (Получает текст, находящийся между 2 значениями тега) + // Returned item with tags (Возвращается элемент вместе с тегами) + // After running, the script will not be reduced by the size of the analyzed (После выполнения, скрипт НЕ уменьшается на проанализированный размер) + // $tag1 - beginning tag (начало тега) + // $tag2 - tag end (конец тега) + // $pos - item number with which to search for tags (номер позиции, с которой искать теги) + function getTagValueSafe($tag1, $tag2, &$html){ + + global $k2; + + return $k2->parser->getTagValueSafe($tag1, $tag2, $html); + } + + + // Gets the text located between the two tag values (Получает текст, находящийся между 2 значениями тега) + // After the script is reduced by the size of the analyzed (После выполнения, скрипт уменьшается на проанализированный размер) + // $tag1 - beginning tag (начало тега) + // $tag2 - tag end (конец тега) + // $pos - item number with which to search for tags (номер позиции, с которой искать теги) + function getTagValue($tag1, $tag2, &$html){ + global $k2; + return $k2->parser->getTagValue($tag1, $tag2, $html); + } + + // Parsing elements and receiving array literals for further processing (Парсинг элементов и получение массива литералов для дальнейшей обработки) + function parsing(&$html){ + $strtp = $html; + + $pos = 0; + $tag = $this->getTagValue('{', '}', $strtp); + array_push($this->tag_comp,$tag); + + while (trim($strtp) <> '') { + + $tag = $this->getTagValue('{', '}', $strtp); + + if (trim($tag)<>''){ + array_push($this->tag_comp,$tag); + } + + } + + } + + /** + * Убираем в контенте экранирование оставщихся фигурных скобок + * @param type $html - код страницы string + */ + function parceEscapeBraces(&$html) { + + $html = str_replace ('\{', ' {', $html); + $html = str_replace ('\}', '} ', $html); + + } + + /** + * обработка фигурных скобок (добавление пробела до и после, иначе ошибка при обработке) + * @param type $html + */ + function addSpaceEscapeBraces(&$html) { + $html = str_replace ('>{', '> {', $html); + $html = str_replace ('}<', '} <', $html); + } + + + // Очистка не используемых тегов + function clearTags(&$html){ + $html = str_replace('{admin}', '', $html); + $html = str_replace('{edit}', '', $html); + } + + //генерация sitemap + function siteMap() + { + global $k2; + $path = $_SERVER['REQUEST_URI']; + + $pos = strpos($path, 'sitemap.xml'); + + if ($pos) { + $sitemap = $k2->ins_comp('k2sitemap'); + $map = $sitemap->buildSitemap(); + echo $map; + exit; + } + } + + + + + // Displays website (Выводит на экран сайт) + function show($isecho = true){ + + global $k2; + + $k2->log->mess('Запуск системы.',false); + if ($this->is_dblog){ + $k2->log->addDBLog($k2->getCurURL(), ''); + } + + if ($k2->auth->isAuth()){ + $k2->site->addTeg('{reg_menu}', $this->unreg_menu); + }else{ + $k2->site->addTeg('{reg_menu}', $this->reg_menu); + } + + // Sets Template + $temp=$k2->get('temp'); + if ($temp <> ''){ + $k2->template->cur = $temp; + + } + + // Enable admin part if included admin-part mode (Включаем админ-часть, если включен режим админ-части) + if ((isset($k2->auth))and($k2->auth->isAdminMode())){ + $k2->template->setAdmin(); + } + + + $site = $k2->template->getPathTemplate($k2->cur_tpl()); + + $this->path_template=$this->getPathTemplate($site); + + //чтение шаблона проекта + $html = file_get_contents($site); + + + + + $this->setComponents($html); + + + + // The conclusion of the administrative (Вывод административной части) + $adm = ''; + if ($this->cliadmpanel == true) { + if (/*$k2->auth->isAdmin()*/$k2->auth->isAuth()){ + $k2->admin = $k2->ins_comp('k2admin'); + $adm = $k2->admin->content(); + } + } else { + if ($k2->auth->isAdmin() || $k2->auth->roleid == '43fa9c5e6de98b6993316e95f8d3fbee'){ + $k2->admin = $k2->ins_comp('k2admin'); + $adm = $k2->admin->content(); + } + } + + + + $html = str_replace('{adm}', $adm, $html); + + + // Treat the admin part (Обрабатываем админ-часть) + if ((isset($k2->auth))and($k2->auth->isAdminMode())){ + $this->setAdmin($html); + } + if ($temp !== 'ajax') { + // Убираем экранирование фигурных скобок для их корректного отображения в контенте + $this->addSpaceEscapeBraces($html); + + // Get a list of parameters with dynamic content (Получаем список параметров с динамическим содержимым) + $this->parsing($html); + + + $this->setVarComponents($html); + + $this->setPath($html); + + + $this->siteMap(); + + if ($this->hidecomments){ + $this->delComment($html); + } + + + // Убираем экранирование фигурных скобок для их корректного отображения в контенте + $this->parceEscapeBraces($html); + + + //Заменяем теги {conts .. } на контент редактируемых областей. + $this->contsComponents($html); + + //Заменяем теги {inscomp .. } на контент компоненты. + $this->insComp($html); + + + + + $this->setSEO($html); + }else { + // Убираем экранирование фигурных скобок для их корректного отображения в контенте + $this->addSpaceEscapeBraces($html); + + // Get a list of parameters with dynamic content (Получаем список параметров с динамическим содержимым) + $this->parsing($html); + + //Заменяем теги {inc .. } на контент редактируемых областей. + $this->incComponents($html); + } + + + //Заменяем теги {inc .. } на контент редактируемых областей. + $this->incComponents($html); + + + + // Заменяем все теги {menu ...} на необходимый контент + //$this->incMenuComponents($html); + + // Заменяем все теги {slider ...} Необходимо в будущем переделать компоненту + //$this->incSliderComponents($html); + + // Заменяем все теги {portfolio ...} + //$this->incPortfolioComponents($html); + + // Заменяем все теги {products ...} + //$this->incProductsComponents($html); + + // Заменяем все теги {filter ...} + //$this->incFilterComponents($html); + + //$this->incButtonComponents($html); + + //$this->incCabinetComponents($html); + + + + $this->clearTags($html); + + + + // Проверяем на наличие в БД дефолтного меню для этого проекта / сайта / языка / + $menu = $k2->ins_comp('k2menu'); + + $menuId = $menu->isDefaultMenuExist(); + + // Если дефолтного меню нет... + if (!$menuId) { + // Создаем дефолтное меню (отменил из-за ложного срабатывания 30.04.2018 Rudjuk) + //!!!$menu->createDefaultMenu(); + // Если пользователь случайно убил пункт Главная в меню + } else if( !$menu->isMainMenuItemExist($menuId) ) { + + // Создаем его для меню текущего проекта (отменил из-за ложного срабатывания 30.04.2018 Rudjuk) + //!!!$menu->createMainMenuItem($menuId); + } + + if ($isecho){ + echo $html; + } else{ + return $html; + } + + } + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2stylecontrols.php b/k2shop/k2shop/app/sys/k2stylecontrols.php new file mode 100644 index 0000000..fdd5d5b --- /dev/null +++ b/k2shop/k2shop/app/sys/k2stylecontrols.php @@ -0,0 +1,175 @@ + 'apple', + 'form' => 'office2010blue', + 'grid' => 'office2010blue', // sunset + 'pivot' => 'office2007', + 'tabs' => 'office2007', + 'treegrid' => 'office2010blue', + 'tree' => 'office2007', + 'combobox' => 'office2007', + 'upload' => 'office2007', + 'listbox' => 'default', + 'combobox' => 'hay', + 'calendar' => 'default' + ); + + public $var_styles = array( // Style options (Варианты стилей) + 'slidemenu' + => array( + 'default' => 'default', + 'bluearrow' => 'Bluearrow', + 'redgray' => 'Redgray', + 'vista' => 'Vista', + 'black' => 'Black', + 'redcaro' => 'Redcaro', + 'darkgray' => 'Darkgray', + 'green' => 'Green', + 'outlook' => 'Outlook', + 'apple' => 'Apple', + 'violet' => 'Violet', + 'hay' => 'Hay', + 'inox' => 'Inox', + 'office2007'=> 'Office2007', + 'silver' => 'Silver', + 'simple' => 'Simple' + ) + , + 'form' + => array( + 'default' => 'default', + 'forest' => 'forest', + 'hay' => 'hay', + 'office2007' => 'office2007', + 'office2010blue' => 'office2010blue', + 'office2010silver' => 'office2010silver', + 'outlook' => 'outlook', + 'sunset' => 'sunset', + 'vista' => 'vista', + 'web20' => 'web20', + 'windows7' => 'windows7' + ), + 'grid' + => array( + 'default' => 'default', + 'office2010blue' => 'Office2010Blue', + 'outlook' => 'Outlook', + 'sunset' => 'Sunset' + ), + 'pivot' + => array( + 'default' => 'default', + 'office2007' => 'Office2007' + ), + 'tabs' + => array( + 'default' => 'default', + 'hay' => 'Hay', + 'silver' => 'Silver', + 'black' => 'Black', + 'inbox' => 'Inbox', + 'office2007' => 'Office2007', + 'outlook' => 'Outlook', + 'vista' => 'Vista' + ), + 'treegrid' + => array( + 'default' => 'Default', + 'office2010blue' => 'Office2010Blue', + 'outlook' => 'Outlook', + 'lightsky' => 'Light Sky', + 'sunset' => 'Sunset' + ), + 'tree' + => array( + 'default' => 'Default', + 'vista' => 'Vista', + 'hay' => 'Hay', + 'inbox' => 'Inbox', + 'office2007' => 'Office2007', + 'outlook' => 'Outlook', + 'silver' => 'Silver', + 'gray' => 'Gray', + 'graygreen' => 'GrayGreen', + 'pink' => 'Pink', + 'green' => 'Green', + 'darkgray' => 'Darkgray' + ), + 'upload' + => array( + 'default' => 'Default', + 'black' => 'Black', + 'hay' => 'Hay', + 'silver' => 'Silver', + 'inox' => 'Inox', + 'office2007' => 'Office2007', + 'outlook' => 'Outlook', + 'vista' => 'Vista' + ), + 'listbox' + => array( + 'default' => 'Default', + 'black' => 'Black', + 'forest' => 'Forest', + 'office2007' => 'Office2007', + 'office2010black' => 'Office2007 Black', + 'office2010blue' => 'Office2007 Blue', + 'office2010silver' => 'Office2007 Silver', + 'outlook' => 'Outlook', + 'sunset' => 'Sunset', + 'web20' => 'Web20', + 'windows7' => 'Windows 7', + 'vista' => 'Vista' + ), + 'combobox' + => array( + 'default' => 'Default', + 'black' => 'Black', + 'hay' => 'Hay', + 'silver' => 'Silver', + 'inox' => 'Inox', + 'office2007' => 'Office2007', + 'outlook' => 'Outlook', + 'vista' => 'Vista' + ), + 'calendar' + => array( + 'default' => 'Default', + 'sunset' => 'Sunset' + ) + + + + ); + + + + // Returns the name of the current style (Возвращает название текущего стиля) + function cur_style($stylename){ + $style=$this->cur_styles[$stylename]; + + if (!isset($style)){ + $style = 'default'; + } + + return $style; + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2sys.php b/k2shop/k2shop/app/sys/k2sys.php new file mode 100644 index 0000000..392e89d --- /dev/null +++ b/k2shop/k2shop/app/sys/k2sys.php @@ -0,0 +1,359 @@ + 'a', 'б' => 'b', 'в' => 'v', + 'г' => 'g', 'д' => 'd', 'е' => 'e', + 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', + 'и' => 'i', 'й' => 'y', 'к' => 'k', + 'л' => 'l', 'м' => 'm', 'н' => 'n', + 'о' => 'o', 'п' => 'p', 'р' => 'r', + 'с' => 's', 'т' => 't', 'у' => 'u', + 'ф' => 'f', 'х' => 'h', 'ц' => 'c', + 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', + 'ь' => '\'', 'ы' => 'y', 'ъ' => '\'', + 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', + + 'А' => 'A', 'Б' => 'B', 'В' => 'V', + 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', + 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', + 'И' => 'I', 'Й' => 'Y', 'К' => 'K', + 'Л' => 'L', 'М' => 'M', 'Н' => 'N', + 'О' => 'O', 'П' => 'P', 'Р' => 'R', + 'С' => 'S', 'Т' => 'T', 'У' => 'U', + 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', + 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', + 'Ь' => '\'', 'Ы' => 'Y', 'Ъ' => '\'', + 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', + 'ї' => 'Yi', 'є' => 'Ye', 'і' => 'i', + 'Ї' => 'YI', 'Є' => 'YE', 'І' => 'I' + ); + return strtr($string, $converter); + } + + // Convert string in the url in transliteration (Преобразование строки в url в транслитерации) + function str2url($str) { + // translation in translit (переводим в транслит) + $str = $this->rus2translit($str); + // lowercase (в нижний регистр) + $str = strtolower($str); + // Replace all unnecessary us "-" (заменям все ненужное нам на "-") + $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str); + // remove leading and trailing '-' (удаляем начальные и конечные '-') + $str = trim($str, "-"); + return $str; + } + + + // Converts text in HUL (Преобразует текст в ЧПУ) + // $name - item name (название пункта) + // nextid - key + function chpu($name,$nextid){ + return $this->str2url($name).'-'.$nextid; + } + + + // Getting the unique ID (Получение уникального ID) + function getGUID(){ + return $this->getID(); + } + + + // Generate password (Генерация пароля) + function generate_password($number=10) + { + $arr = ['a','b','c','d','e','f', + 'g','h','i','j','k','l', + 'm','n','o','p','r','s', + 't','u','v','x','y','z', + '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', + '(',')','[',']','!','?', + '&','^','%','@','$', + '<','>','/','|','+','-', + '{','}','~']; + // Generate password (Генерируем пароль) + $pass = ""; + for($i = 0; $i < $number; $i++) + { + // We calculate a random array index (Вычисляем случайный индекс массива) + $index = rand(0, count($arr) - 1); + $pass .= $arr[$index]; + } + return $pass; + } + + + + // Рекурсивное создание каталогов + function forceDir($dir){ + $rez=true; + + $new_name=trim($dir); + + $os=PHP_OS; + if ($os=='WINNT'){ + $new_name = str_replace("/", "\\", $new_name); + } + + if (!file_exists($new_name)){ + $rez=mkdir($new_name, 0775, true); + }else{ + $rez=is_dir($new_name); + } + + return $rez; + } + + /** + * формирование пути к файлу на основнании даты + * @return type + */ + function generateUploadDir($datecreate = '') + { + $path = ''; + + if ($datecreate == '') { + $datecreate = date("Y-m-d"); + } + + $arr_date = explode('-', $datecreate); + + $year = $arr_date[0]; + $month = $arr_date[1]; + $day = $arr_date[2]; + + $path = '/'.$year.'/'.$month.'/'.$day; + + return $path; + } + + /** + * преобразовывает 1 букву в верхний регистр при UTF-8 + * @param type $str + * @param type $encoding + * @return string + */ + function mb_ucfirst($str, $encoding='UTF-8') + { + $str = mb_ereg_replace('^[\ ]+', '', $str); + $str = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding). + mb_substr($str, 1, mb_strlen($str), $encoding); + return $str; + } + + // IP-адрес пользователя + function ip(){ + $ip=''; + + if (isset($_SERVER['REMOTE_ADDR'])){ + $ip = $_SERVER['REMOTE_ADDR']; + } + + // Переадресованный ip + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } + + // Реальный ip + if (isset($_SERVER['HTTP_X_REAL_IP'])){ + $ip = $_SERVER['HTTP_X_REAL_IP']; + } + + return $ip; + } + + + // Возвращает браузер клиента + function agent(){ + $rez=''; + + if (isset($_SERVER['HTTP_USER_AGENT'])){ + $rez=$_SERVER['HTTP_USER_AGENT']; + } + + return $rez; + } + + + // Возвращает расширение файла + function getExt($filename){ + $path_info = pathinfo($filename); + return $path_info['extension']; + } + + // Возвращает название каталога + function getDir($filename){ + $path_info = pathinfo($filename); + return $path_info['dirname']; + } + + // Возвращает название файла + function getFilename($filename){ + $path_info = pathinfo($filename); + return $path_info['filename']; + } + + // Возвращает полное название файла + function getFullname($filename){ + $path_info = pathinfo($filename); + return $path_info['basename']; + } + + + //Перевод даты в необходимый формат для записи в БД и проверка, что введена именно дата + function dateSecure ($date){ + + if (!preg_match(("/[0-9]{2}\.[0-9]{2}\.20[0-9]{2}/"), $date)){ + $this->err.='
    * '.$this->Translate("{lnMustSelectDate}").'.
    '; + return $date=false; + } + else { + list($d, $m, $y)=explode('.', $date); + $date = $y.'-'.$m.'-'.$d; + + return $date; + } + } + + //Перевод даты c временем в необходимый формат при чтении из базы + function datetimeFromBase ($date, $format = 'd.m.Y H:i:s'){ + return $date = date($format, strtotime($date)); + } + + // Печатает одномерный массив + // $arr - массив + // $print_key - печатать ли ключ + // $cols - количество столбцов + // $width_col - ширина столбцов + function echo_arr($arr, $print_key=false, $cols=3, $width_col=40){ + + if (empty($arr)) return ''; + + $total = sizeof($arr); + + $i=1; + foreach ($arr as $k=>$el){ + $s=''; + if ($print_key){ + $s.=$k.'. '; + } + + $s.="$el"; + printf("%-' ".$width_col."s",$s); + + if ($i % $cols ==0){ + echo "\n"; + } + + $i++; + } + } + + + // Печатает много-мерный массив + // $arr - массив, который выводим на экран + // $print_key - печатать ли ключ + // $width_col - ширина столбцов + // $elems - перечень выводимых элементов. Если пусто - выводится всё + function echo_arr_multy($arr, $print_key=false, $width_col=20, $elems=[]){ + + if (empty($arr)) return ''; + + $a=array_keys($arr); + $a2=array_keys($arr[$a[0]]); + + // Заполняем массив ключей всеми элементами + if (empty($elems)){ + if (!empty($arr)){ + foreach ($arr[$a[0]] as $k=>$v){ + $elems[]=$k; + } + } + } + + + // Выводим шапку + $s=''; + if ($print_key){ + printf("%-' ".$width_col."s","Key"); + } + + foreach ($elems as $k=>$v){ + printf("%-' ".$width_col."s",$v); + } + echo "\n"; + + if ($print_key){ + printf("%-'=".$width_col."s",""); + } + + foreach ($elems as $k=>$v){ + printf("%-'=".$width_col."s",""); + } + echo "\n"; + + + // Вывод информации о полях + foreach ($arr as $k=>$el){ + $s=''; + + if ($print_key){ + printf("%-' ".$width_col."s",$k); + + } + + // Выводим значения полей + $i=0; + foreach ($el as $kel=>$vel){ + printf("%-' ".$width_col."s",$vel); + $i++; + } + + echo "\n"; + } + + } + + + // Возвращает перечень файлов в указанном каталоге + function getFileList($dirname){ + $rez=[]; + $arr=scandir($dirname); + + foreach($arr as $a) { + if (($a<>'.')and($a<>'..')and($a<>'')){ + $rez[]=$a; + } + + } + + return $rez; + } + + +} + diff --git a/k2shop/k2shop/app/sys/k2template.php b/k2shop/k2shop/app/sys/k2template.php new file mode 100644 index 0000000..ac6c14e --- /dev/null +++ b/k2shop/k2shop/app/sys/k2template.php @@ -0,0 +1,172 @@ + 'public', + 'admin' => 'admin_lte', + 'print' => 'print', + 'ajax' => 'ajax' + ]; // Templates + + public $searcharr = ['/usr/def/php', + '/usr/{template}/php', + '/k2shop/usr/{template}/php', + '/usr/{domain}/php', + '/k2shop/k2shop/app/template/def/php', + '/k2shop/k2shop/app/template/{template}/php' + ]; + + public $cur='def'; // The name of the current template (Название текущего шаблона) + + + /** + * Получает из базы 1 шаблон для текущего сайта и отдает его название. + * В дальнейшем - получает из базы все доступные шаблоны для текущего сайта, выбирает нужный, согласно условиям и отдает его название. + * + */ + public function getTemplate(){ + global $k2; + + $cont = $k2->ins_comp('k2cont'); // Получаем отсюда значение свойства currentSiteID + $TemplateName = ''; + + // Если текущий сайт или проект отключены или не используются + if( $cont->currentProjectID == NULL ) { + return $TemplateName; + } + + $sqlQuery = 'SELECT t.templatename AS templatename + FROM k2temp AS t + LEFT JOIN k2sites AS s ON + t.siteid = s.siteid + LEFT JOIN k2proj AS p ON + p.projid = s.projid + WHERE t.siteid ='.$cont->currentSiteID.' AND s.site_active = 1 AND p.proj_active = 1 AND t.temp_active = 1 + LIMIT 1'; + + foreach ($k2->db->query($sqlQuery) as $templateItem) { + $TemplateName = $templateItem['templatename']; + } + + return $TemplateName; + } + + // Template search for a given key (Поиск шаблона по заданному ключу) + // $key - search key. Example: public, admin, print. + function findTemplate($key){ +// global $k2; +// $tpl=$this->cur; +// +// //Выбор шаблона из базы данных +// $sql = 'select adminpage from k2admin_design where active=1'; +// +// foreach ($k2->db->query($sql) as $value) { +// $this->templates[$key] = 'admin_'.$value['adminpage']; +// } +// +// if (isset($this->templates[$key])){ +// $tpl=$this->templates[$key]; +// } +// +// $tpl=$this->cur; + + if (isset($this->templates[$key])){ + $tpl=$this->templates[$key]; + } + + + return $tpl; + + } + + // Returns the name of a public template (Возвращает название публичного шаблона) + function getPublic(){ + return $this->findTemplate('public'); + } + + + + // Returns the name of the administrative template (Возвращает название шаблона администрирования) + function getAdmin(){ + return $this->findTemplate('admin'); + } + + // Returns the name of the print template (Возвращает название шаблона для печати) + function getPrint(){ + return $this->findTemplate('print'); + } + + // Sets the current public part (Устанавливает текущей публичную часть) + function setPublic(){ + $this->cur=$this->getPublic(); + } + + // Sets the current admin part (Устанавливает текущей админ-часть) + function setAdmin(){ + global $k2; + + if ($k2->get('temp')==''){ + $this->cur=$this->getAdmin(); + } + } + + // Set the current pattern for print (Устанавливает текущей шаблон для печати) + function setPrint(){ + $this->cur=$this->getPrint(); + } + + // Returns the name of the current template (Возвращает название текущего шаблона) + function cur(){ + global $k2; + + if ($k2->get('temp')<>''){ + $this->cur=$k2->get('temp'); + }else{ + + if (isset($k2->auth) && $k2->auth->isAdminMode()){ + $this->cur=$this->templates['admin']; + } + + if (isset($k2->auth) && $k2->auth->isAjaxMode()){ + $this->cur=$this->templates['ajax']; + } + + if (isset($k2->auth) && $k2->auth->isPrintMode()){ + $this->cur=$this->templates['print']; + } + } + + $rez=$this->cur; + + return $rez; + } + + // Get path to template (Получить путь к шаблону) + function getPathTemplate($templatename, $temp=''){ + global $k2; + return $k2->search_script($templatename, $temp, $this->searcharr,'.htm'); + + } + + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2timer.php b/k2shop/k2shop/app/sys/k2timer.php new file mode 100644 index 0000000..26ec4b5 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2timer.php @@ -0,0 +1,124 @@ +"; + + echo "Выполнено за: ".runtime()."
    "; + + runtime('start_sleep'); + sleep(4); + runtime('end_sleep'); + + runtime('prog3'); // Pinpoint execution of the subroutine 3 (Засекаем выполнение подпрограммы 3) / + // подпрограмма 3 + echo "Sub 3 is made of (Подпрограмма 3 выполнена за): ".runtime('prog3')."
    "; + + echo "Sleep marks: ".runtime('start_sleep','end_sleep')."
    "; +*/ + function runtime($type='0',$mark=NULL) + { + global $_runtime_microsec; + + /* It is necessary to return the difference? (Надо вернуть разницу?) */ + if( $mark!==NULL ) if( isset($_runtime_microsec[$type]) && isset($_runtime_microsec[$mark]) ) return sprintf("%f", $_runtime_microsec[$mark]-$_runtime_microsec[$type]); + + if( PHP_VERSION >= '5.0.0' ) + { + $mtime = microtime(true); + } + else + { + $mtime = microtime(); + $mtime = explode(" ", $mtime); + $mtime = $mtime[1] + $mtime[0]; + } + + /* Note the time (Засекаем время) */ + if( !is_array($_runtime_microsec) ) $_runtime_microsec = array(); + if( !isset($_runtime_microsec[$type]) ) + { + $_runtime_microsec[$type] = $mtime; + } + + /* Calculate the time (Вычисляем время) */ + $mtime -= $_runtime_microsec[$type]; + + /* Format the conclusion (Форматируем вывод) */ + $mtime = sprintf("%f", $mtime); + return $mtime; + } + + + // Getting the current time in microseconds (Получение текущего времени в микро-секундах) + function get_now(){ + $mtime = microtime(); + $mtime = explode(" ", $mtime); + $mtime = $mtime[1] + $mtime[0]; + return $mtime; + } + + // Measures the initial time of the process (started automatically in the constructor) (Замеряет начальное время процесса (запускается автоматически в конструкторе)) + function start_time(){ + $this->start_time = $this->get_now(); + return $this->start_time; + } + + // Measures the final time of the process (started forcibly) (Замеряет конечное время процесса (запускается принудительно)) + // The function returns the run-time program (Функция возвращает время выполнения программы) + // If you want to display a finite time - see property end_time (Если нужно вывести конечное время - смотрите свойство end_time.) + function end_time(){ + $this->end_time = $this->get_now(); + $this->delta_time = $this->end_time-$this->start_time; + return $this->delta_time; + } + + + // Проверяет включен ли отладочный режим + function isDebug(){ + $rez=''; + $isShowErr=ini_get('display_errors') or ini_get('display_startup_errors'); + + if ($isShowErr==1){ + $rez="
    Attention! Errors are displayed. It is not safe!

    \n"; + } + + return $rez; + } + + + function show(){ + $time=$this->end_time(); + //echo "
    Runtime Site: ".sprintf("%0.6f", $time)." s.

    \n"; + //echo $this->isDebug(); + } + + +} \ No newline at end of file diff --git a/k2shop/k2shop/app/sys/k2twig.php b/k2shop/k2shop/app/sys/k2twig.php new file mode 100644 index 0000000..78c64a6 --- /dev/null +++ b/k2shop/k2shop/app/sys/k2twig.php @@ -0,0 +1,17 @@ +check_connect()){ + echo 'Успешно подключились к базе данных.'; + }else{ + echo 'К базе данных не удалось подключиться.'; + } + + } + + // Получение версии базы данных + function getVerDB(){ + global $k2; + $rez=''; + + $sql="SELECT valuek2 FROM k2ver where (vark2='k2ver')"; + + try{ + foreach ($k2->db->query($sql) as $row) { + $rez=$row["valuek2"]; + } + }catch (Exception $e) { + echo "Failed to get the database version: ".$e->getMessage()."\n"; + } + + return $rez; + } + + + // Production version of the software (Получение версии программной части) + function getVer(){ + global $k2; + + $rez=$k2->version; + + return $rez; + + } + + + // Returns the version number of the indicator - to sort (Возвращает цифру индикатора версии - для сортировки) + function indivatorVer($ver){ + $rez=0; + $v=explode('.', $ver); + $n=pow(10,3*4); + foreach($v as $a) { + $rez=$rez+$n*$a; + $n=$n/pow(10,4); + } + + return $rez; + } + + + + // Returns a list of the update files (Возвращает список файлов обновления) + function getFileSQLUpdates(){ + global $k2; + + + $updatedir=$k2->rootdir.$this->update_path; + + $rez="Каталог, откуда берем обновления: $updatedir \n\n"; + + $rez.="Файлы обновления:\n"; + $arr=scandir($updatedir); + + //var_dump($arr); + + $verdb_ind=$this->indivatorVer($this->verdb); + $verprog_ind=$this->indivatorVer($this->verprog); + + $this->ver_arr= []; + + foreach($arr as $a) { + + //echo 'path='.$arr."\n"; + + if (($a<>'.')and($a<>'..')and($a<>'')){ + + $v=explode('_', $a); + $ordv=$this->indivatorVer($v[0]); + + //echo $ordv."\n"; + + // Take the only versions that are between the database version and the current version of the software (Берем только версии, которые находятся между версией базы данных и текущей версией программной части) + if (($ordv>$verdb_ind)&&($ordv<=$verprog_ind)){ + $this->ver_arr[]= [ + 'version'=>$v[0], + 'order'=>$ordv, + 'filename'=>$a + ]; + $rez.=$v[0]."\n"; + } + } + } + + //var_dump($this->ver_arr); + + + return $rez; + } + + + // Выполняет SQL скрипт + function execSQL($sql){ + global $k2; + $rez=''; + + try { + $k2->db->exec($sql); + }catch (Exception $e) { + $rez.="Execute SQL Error: ".$e->getMessage()."\n"; + } + + return $rez; + } + + + + + // Execute SQL script from a file (Выполнение SQL скрипта из файла) + function runScriptFromFile($filename){ + global $k2; + $rez=''; + + $fullfile=$k2->rootdir.$this->update_path.'/'.$filename; + $rez='Execute the script from the file: '.$fullfile."\n"; + + try{ + $sql=file_get_contents($fullfile); + }catch (Exception $e) { + $rez.="Error reading file $fullfile: ".$e->getMessage()."\n"; + } + + + $sqlarr=explode(';',$sql); + + foreach($sqlarr as $s) { + $s=trim($s); + if (trim($s)<>''){ + $rez.=$this->execSQL($s); + } + } + + + return $rez; + } + + + // Starts the database update from the update files (Запускает обновление базы данных из файлов обновления) + function runUpdates(){ + $rez="Updating the database (Обновляем базу данных)\n"; + + foreach($this->ver_arr as $v) { + $rez.=$this->runScriptFromFile($v['filename']); + + } + + return $rez; + } + + + // Сохранение версии + function saveVer(){ + $sql="update k2ver set valuek2='".$this->verprog."' where (vark2='k2ver')"; + + $rez=$this->execSQL($sql); + + return $rez; + + } + + + + + // Updating the database (Обновление базы данных) + function updateDB(){ + global $k2; + + $rez='=== updatek2 '.date("d.m.Y H:i:s").' ==='."\n"; + + $this->verdb=$this->getVerDB(); + echo 'Текущая версия базы данных: '.$this->verdb."\n"; + $this->verprog=$this->getVer(); + echo 'Текущая версия программной части: '.$this->verprog."\n"; + + $rez.='Version database: '.$this->verdb." order(".$this->indivatorVer($this->verdb).")\n"; + $rez.='Version of the program: '.$this->verprog." order(".$this->indivatorVer($this->verprog).")\n"; + + // Getting a list of updates (Формируем список обновлений) + $rez.=$this->getFileSQLUpdates(); + + // Upgrading the database (Выполняем обновление базы данных) + $rez.=$this->runUpdates(); + + // Change the version number (Изменяем номер версии) + $rez.=$this->saveVer(); + + // Write log (Записываем лог) + file_put_contents($k2->rootdir.'/var/log/updatelog.log', $rez, FILE_APPEND ); + + + return $rez; + } + + + function content(){ + $rez=$this->updateDB(); + return $rez; + } + + +} + -- 1.9.1