public static function init() { $query = urldecode($_SERVER['REQUEST_URI']); header('Infrajs-Cache: true'); $html = Access::cache(__FILE__ . ':init', function ($query) { header('Infrajs-Cache: false'); Config::get(); $conf = Config::get('controller'); return Controller::check($conf['index']); }, array($query)); echo $html; exit; }
public static function apply() { //Поиск совпадения адреса с файлом //Редирект также кэшируется в modified, когда обращение к статике, по правилам Nostore Path::init(); //Контроллер... должен быть файл в корне index.json //Если сайт не использует контроллер то до этого места доходим только, когда 404 и лишний запуск не существенен //Либо следующая строчка обеспечивает формирование всего html если контроллер используется. $query = substr(urldecode($_SERVER['REQUEST_URI']), 1); $ch = substr($query, 0, 1); if (!in_array($ch, ['~', '!', '-'])) { Controller::init(); } $conf = Config::get('router'); Path::req($conf['404']); }
public static function exec() { if (!Update::$is) { Config::add('update', function ($name, $value, $conf) { if (!Update::$is) { return; } Path::req('-' . $name . '/' . $value); }); } Update::$is = true; //Пр появлении нового Config::get будет проверяться свойство update //Но нужно установить то что уже было установлено $conf = Config::$conf; foreach ($conf as $name => $v) { Update::update($name); } //И вообще всё установить нужно что ещё не установлено Config::get(); }
<?php use infrajs\config\Config; use infrajs\ans\Ans; use infrajs\path\Path; use infrajs\load\Load; use infrajs\access\Access; use infrajs\template\Template; use infrajs\mail\Mail; $ans = array(); $ans['popup'] = true; $conf = Config::get('subscribe'); if (empty($_REQUEST['email'])) { return Ans::err($ans, $conf['msg']); } if (strlen($_REQUEST['email']) > 1000) { return Ans::err($ans, 'Слишком много данных. ' . $conf['msg']); } $email = strip_tags($_REQUEST['email']); $email = trim($email); $email = Path::encode($email); $agent = $_SERVER['HTTP_USER_AGENT']; $ip = $_SERVER['REMOTE_ADDR']; session_start(); if (empty($_SESSION['submit_time'])) { $_SESSION['submit_time'] = 0; } if (time() - $_SESSION['submit_time'] < 60) { return Ans::err($ans, 'Письмо уже отправлено! Новое сообщение можно будет отправить через 1 минуту!'); } $_SESSION['submit_time'] = time();
use infrajs\sequence\Sequence; use infrajs\path\Path; use infrajs\path\URN; use infrajs\view\view; //Template::$conf['root']=URN::getAbsRoot(); //Sequence::set(Template::$scope, array('~root'), Template::$conf['root']); Template::$fs['load'] = function ($src) { return Load::loadTEXT($src); }; $fn2 = function ($name = null) { return $conf = Config::pub($name); }; Sequence::set(Template::$scope, array('infra', 'config'), $fn2); Sequence::set(Template::$scope, array('Config', 'get'), $fn2); Event::one('Controller.oninit', function () { Template::$scope['~conf'] = Config::get(); }); $fn3 = function () { return View::getPath(); }; Sequence::set(Template::$scope, array('infra', 'view', 'getPath'), $fn3); $fn4 = function () { return View::getHost(); }; Sequence::set(Template::$scope, array('infra', 'view', 'getHost'), $fn4); $fn5 = function ($s) { return Sequence::short($s); }; Sequence::set(Template::$scope, array('infra', 'seq', 'short'), $fn5); $fn6 = function ($s) { return Sequence::right($s);
public static function &pub($plugin = null) { if ($plugin) { $conf = Config::get($plugin); $pub = Config::pubclean($conf); return $pub; } $pub = array(); $conf = Config::get(); foreach ($conf as $i => $part) { $res = Config::pubclean($part); if (!is_null($res)) { $pub[$i] = $res; } } return $pub; }
<?php use infrajs\access\Access; use infrajs\event\Event; use infrajs\ans\Ans; use infrajs\path\Path; use infrajs\each\Each; use infrajs\config\Config; if (!is_file('vendor/autoload.php')) { chdir('../../../../'); require_once 'vendor/autoload.php'; } $ans = array(); $ans['title'] = 'Проверка наличия папок'; $conf = Config::get(); if ($conf['mem']['type'] == 'fs') { $dirs = Config::get('path'); if (!Path::theme($dirs['cache'])) { return Ans::err($ans, 'Нет папки ' . $dirs['cache']); } if (!Path::theme($dirs['data'])) { return Ans::err($ans, 'Нет папки ' . $dirs['data']); } return Ans::ret($ans, 'Обязательные папки есть'); } else { return Ans::ret($ans, 'Используется memcache. Папки не создаются.'); }
<?php use infrajs\update\Update; use infrajs\config\Config; use infrajs\load\Load; use infrajs\path\Path; $conf = Config::get(); $sys = array(); foreach ($conf as $name => $c) { if ($c['clutch']) { $sys[$name] = array(); $sys[$name]['clutch'] = $c['clutch']; } } $json = Load::json_encode($sys); file_put_contents(Path::$conf['cache'] . '/.infra.json', $json);
<?php use infrajs\access\Access; use infrajs\event\Event; use infrajs\ans\Ans; use infrajs\each\Each; use infrajs\config\Config; if (!is_file('vendor/autoload.php')) { chdir('../../../../'); require_once 'vendor/autoload.php'; } Access::test(true); $ans = array(); $ans['title'] = 'Тест на значение отладки debug и test'; $conf = Config::get('access'); if (Access::debug() && !is_string($conf['debug']) && !is_array($conf['debug'])) { $ans['class'] = 'bg-warning'; return Ans::ret($ans, 'Значение config.infra.debug = true'); } if (Access::test() && !is_string($conf['test']) && !is_array($conf['test'])) { $ans['class'] = 'bg-warning'; return Ans::ret($ans, 'Значение config.infra.test = true'); } $debug = $conf['debug']; if ($debug) { if (!is_array($debug)) { $debug = array($debug); } $key = array_search('::1', $debug); if ($key !== false) { array_splice($debug, $key, 1);
public static function checkFS() { $search = Cache::exec(array('composer.lock'), __FILE__ . 'init', function () { $search = array(); $ex = array_merge(array(Path::$conf['cache'], Path::$conf['data']), Path::$conf['search']); Search::scan('', function ($src, $level) use(&$search, $ex) { if (in_array($src, $ex)) { return true; } //вглубь не идём if ($level < 2) { return; } if ($level > 5) { return true; } if (!is_file($src . '.infra.json')) { return; } $r = explode('/', $src); array_pop($r); array_pop($r); $search[] = implode('/', $r) . '/'; return false; //вглубь не идём и в соседние папки тоже }); return $search; }); Path::$conf['search'] = array_values(array_unique(array_merge(Path::$conf['search'], $search))); if (Config::$all) { //Если все конфиги были уже обраны, нужно заного пробежаться по найденным for ($i = 0; $i < sizeof($search); $i++) { $tsrc = $search[$i]; if (!is_dir($tsrc)) { continue; } $files = scandir($tsrc); foreach ($files as $file) { if ($file[0] == '.') { continue; } if (!is_dir($tsrc . $file)) { continue; } Config::load($tsrc . $file . '/.infra.json', $file); } } } /*$comp = Load::loadJSON('composer.json'); if ($comp && !empty($comp['require'])) { foreach ($comp['require'] as $n => $v) { $r = explode('/', $n); if (sizeof($r) != 2) continue; $path = 'vendor/'.$r[0].'/'; if (!in_array($path, Path::$conf['search'])){ Path::$conf['search'][] = $path; } } }*/ }
//BREADCRUMBS TITLE if (!$md['group'] && $md['producer'] && sizeof($md['producer']) == 1) { //ПРОИЗВОДИТЕЛЬ if ($md['producer']) { foreach ($md['producer'] as $producer => $v) { break; } } else { $producer = false; } //is!, descr!, text!, name!, breadcrumbs! $ans['is'] = 'producer'; $name = Catalog::getProducer($producer); $ans['name'] = $name; $ans['title'] = $name; $conf = Config::get('catalog'); $ans['breadcrumbs'][] = array('title' => $conf['title'], 'add' => 'producer:'); $menu = Load::loadJSON('-catalog/menu.json'); $ans['breadcrumbs'][] = array('href' => 'producers', 'title' => $menu['producers']['title']); $ans['breadcrumbs'][] = array('add' => 'producer::producer.' . $name . '=1', 'title' => $name); $ans['breadcrumbs'][sizeof($ans['breadcrumbs']) - 1]['active'] = true; } else { if (!$md['group'] && $md['search']) { $ans['is'] = 'search'; $ans['name'] = $md['search']; $ans['title'] = Path::encode($md['search']); $ans['breadcrumbs'][] = array('title' => $conf['title'], 'add' => 'search:'); $menu = Load::loadJSON('-catalog/menu.json'); $ans['breadcrumbs'][] = array('href' => 'find', 'title' => $menu['find']['title']); $ans['breadcrumbs'][] = array('title' => $ans['name']); $ans['breadcrumbs'][sizeof($ans['breadcrumbs']) - 1]['active'] = true;
public static function loadCSS(&$js, $name) { $c = Config::get($name); if (empty($c['css'])) { return; } if (!empty($c['off'])) { return; } if (!empty($c['dependencies'])) { Each::exec($c['dependencies'], function &($name) use(&$js) { Collect::loadCSS($js, $name); $r = null; return $r; }); } if (!empty(Collect::$cssed[$name])) { return; } Collect::$cssed[$name] = true; $root = !empty($c['-collect']) && $c['-collect'] == 'root'; Each::exec($c['css'], function &($path) use($name, &$js, $root) { $r = null; if ($root) { $src = $path; } else { $src = '-' . $name . '/' . $path; } $js .= "\n\n" . '/*load css ' . $src . "*/\r\n"; if (!Path::theme($src)) { echo '<pre>'; throw new \Exception('Не найден файл ' . $src); } $js .= Load::loadTEXT('-csspath/?src=' . $src); return $r; }); }
<?php } elseif (isset($_REQUEST['logout'])) { Access::admin(false); ?> <div style="padding:50px 100px"> <p>Вы обычный посетитель</p> <p><a href="?">Проверить</a></p> </div> <?php } else { $r = Access::admin(); if ($r) { Config::get('template'); echo Template::parse('-admin/index.tpl'); ?> <div style="padding:50px 100px"> <p>Вы администратор</p> <p><a href="?logout">Выход</a></p> </div> <?php } else { ?> <div style="padding:50px 100px"> <p>Вы обычный посетитель</p> <p><a href="?login">Вход</a></p> </div> <?php }
use infrajs\ans\Ans; use infrajs\load\Load; if (!is_file('vendor/autoload.php')) { chdir('../../../'); require_once 'vendor/autoload.php'; Config::init(); } $ans = array('title' => 'Запуск шаблонизатора'); $tpl = '{infra.config(name).main}'; $data = array('name' => 'rubrics'); $html = Template::parse(array($tpl), $data); if (!$html) { return Ans::err($ans, $tpl . ' возрващает пустую строку ' . $html); } $tpl = '{infra.config(:rubrics).main}'; $data = true; $html = Template::parse(array($tpl), $data); if (!$html) { return Ans::err($ans, $tpl . ' возрващает пустую строку ' . $html); } $conf = Config::get('rubrics'); $tpl = '{list::test}{test:}1{:date}{date:}{~date(:F,~true)}'; $data = Load::loadJSON('-rubrics/?type=' . $conf['main'] . '&list'); if (sizeof($data['list'])) { //Это если есть данные иначе тест этот не проводим $html = Template::parse(array($tpl), $data); if (!$html) { return Ans::err($ans, ' возрващает пустую строку ' . $html); } } return Ans::ret($ans);
<?php use infrajs\load\Load; use infrajs\config\Config; use infrajs\router\Router; use infrajs\ans\Ans; if (!is_file('vendor/autoload.php')) { chdir('../../../'); require_once 'vendor/autoload.php'; Router::init(); } $js = 'if (!window.infra) window.infra={}; if (!window.infrajs) window.infrajs={}; infra.conf=(' . Load::json_encode(Config::pub()) . '); '; $js .= 'infra.config = function (name){ if(!name)return infra.conf; return infra.conf[name]; };'; $js .= 'window.Config = {}; Config.get = infra.config; Config.conf = infra.conf;'; return Ans::js($js);
<?php use infrajs\config\Config; use infrajs\router\Router; if (!is_file('vendor/autoload.php')) { chdir('../'); require_once 'vendor/autoload.php'; Router::init(); } $conf = Config::get('underconstruction'); header('location: https://source.unsplash.com/category/' . $conf['category']);
if ($take) { $ans['take'] = $take['date']; } else { $ans['take'] = false; } $ans['size'] = ceil(filesize($file) / 1000); $ans['time'] = filemtime($file); preg_match("/\\.([a-zA-Z0-9]+)\$/", $file, $match); $ans['ext'] = strtolower($match[1]); } $ans['corable'] = in_array(strtolower($ans['ext']), $CORABLE); $ans['rteable'] = (bool) Path::theme('infra/lib/wymeditor/'); if ($ans['rteable']) { $ans['rteable'] = in_array(strtolower($ans['ext']), $RTEABLE); } $conf = Config::get('imager'); $imgext = $conf['images']; Each::forr($imgext, function &($e) use(&$ans) { if ($e == $ans['ext']) { $ans['image'] = true; } //Значит это картинка $r = null; return $r; }); if ($file) { //Если файл есть $p = explode('/', $file); //Имя с расширением $ans['file'] = array_pop($p); } else {
<?php use infrajs\access\Access; use infrajs\ans\Ans; use infrajs\config\Config; use infrajs\router\Router; if (!is_file('vendor/autoload.php')) { chdir('../../../'); require_once 'vendor/autoload.php'; Router::init(); } Access::debug(true); $plugin = Ans::GET('plugin', 'string', null); $conf = Config::get($plugin); echo '<h1>Конфиг ' . $plugin . '</h1><pre>'; print_r($conf);
use infrajs\path\Path; use infrajs\ans\Ans; use infrajs\view\View; use infrajs\load\Load; use infrajs\mail\Mail; use infrajs\template\Template; use infrajs\router\Router; use infrajs\config\Config; if (!is_file('vendor/autoload.php')) { chdir('../../../'); //Согласно фактическому расположению файла require_once 'vendor/autoload.php'; Router::init(); } $conf = Config::get('contacts'); $ans = array(); if (empty($_POST['name'])) { $persona = ''; } else { $persona = $_POST['name']; } if (empty($_POST['phone'])) { $phone = ''; } else { $phone = $_POST['phone']; } if (empty($_POST['email'])) { $email = ''; } else { $email = $_POST['email'];
<?php namespace infrajs\event; use infrajs\ans\Ans; use infrajs\config\Config; if (!is_file('vendor/autoload.php')) { chdir('../../../../'); require_once 'vendor/autoload.php'; } $ans = array(); $ans['title'] = 'Рекурсия в событиях'; Config::get('event'); $test = ''; Event::handler('ontestrec', function () use(&$test) { Event::handler('ontestrec', function () use(&$test) { $test .= 'b'; }); $test .= 'a'; }); $r = Event::fire('ontestrec'); if ($test != 'ab' || !$r) { return Ans::err($ans, 'Вложенная подписка ' . $test); } $test = ''; Event::handler('onfoo', function () use(&$test) { $r = Event::fire('onfoo'); //Реультат события без учёта текущего обработчика if (!$r) { return false; }
<?php namespace infrajs\layer\env; use infrajs\path\Path; use infrajs\event\Event; use infrajs\controller\Layer; use infrajs\config\Config; Config::get('controller'); Event::handler('Infrajs.oninit', function () { Env::init(); Layer::parsedAdd('envval'); }); Event::handler('layer.oncheck', function (&$layer) { Env::checkinit($layer); }, 'env:config,external'); Event::handler('layer.oncheck', function (&$layer) { Env::envtochild($layer); }, 'env:config,external'); Event::handler('layer.oncheck', function (&$layer) { Env::envframe($layer); }, 'env:config,external'); Event::handler('layer.oncheck', function (&$layer) { Env::envframe2($layer); }, 'env:config,external'); Event::handler('layer.oncheck', function (&$layer) { Env::envmytochild($layer); }, 'env:config,external'); Event::handler('layer.isshow', function (&$layer) { return Env::check($layer); }, 'env:counter,tpl,div,is');
Router::init(); } $ans = array(); $osrc = Ans::GET('src'); if (!$osrc) { return Ans::err($ans, 'Для работы необходимо передать параметр ?src= до папки с иллюстрациями: ' . $osrc); } $src = Path::theme($osrc); if (!$src) { return Ans::err($ans, 'Неправильный путь до папки с иллюстрациями: ' . $osrc); } $list = Access::cache(__FILE__, function ($src) { $list = array(); array_map(function ($file) use(&$list, $src) { if ($file[0] == '.') { return; } $fdata = Load::nameInfo($file); if (!in_array($fdata['ext'], array('jpg', 'jpeg', 'png'))) { return; } $list[] = $src . Path::toutf($file); }, scandir($src)); return $list; }, array($src)); $conf = Config::get('teremok'); $count = $conf['count']; $count = Ans::GET('count', 'int', $count); $list = array_slice($list, 0, $count); $ans['list'] = $list; return Ans::ret($ans);
<?php use infrajs\load\Load; use infrajs\access\Access; use infrajs\event\Event; use infrajs\config\Config; use infrajs\update\Update; $conf = Config::get('tester'); if ($conf['updatetest']) { Update::exec(); //Это отодвинет update testerа в конец очереди $ans = Load::loadJSON('-tester/?type=auto'); if (!$ans || !$ans['result']) { error_log('TESTER: There are errors in the tests /-tester/?type=errors ' . $ans['msg']); //if (Access::debug()) die('TESTER: There are errors in the tests <a href="/-tester/?type=errors">errors</a> <b>'.$ans['msg'].'</b>'); } else { echo '<div class="well">С обновлением выполнено <a href="/-tester/">тестирование</a>, ошибок не обнаружено</div>'; } }
public static function change($session_id, $pass = null) { $email = Session::getEmail(); $session_id_old = Session::initId(); if (!$email) { //Текущая сессия не авторизированная $email = Session::getEmail($session_id); if ($email) { //А вот новая сессия аторизированна, значит нужно объединить сессии и грохнуть старую $newans = Session::recivenews(); //Нужно это всё записать в базу данных для сессии 1 Session::writeNews($newans['news'], $session_id); //Теперь старую сессию нужно удалить полностью //Надо подчистить 2 таблицы if ($session_id_old) { //хз бывает ли такое что его нет $conf = Config::get(); $tables = $conf['session']['change_session_tables']; //Массив с таблицами в которых нужно изменить session_id неавторизированного пользователя, при авторизации $db = Db::pdo(); Each::forr($tables, function &() use($session_id_old, $session_id, &$db) { $sql = 'UPDATE images SET session_id = ? WHERE session_id = ?;'; $stmt = $db->prepare($sql); $stmt->execute(array($session_id, $session_id_old)); $r = null; return $r; }); $sql = 'DELETE from ses_records where session_id=?'; $stmt = $db->prepare($sql); $stmt->execute(array($session_id_old)); $sql = 'DELETE from ses_sessions where session_id=?'; $stmt = $db->prepare($sql); $stmt->execute(array($session_id_old)); } } } global $infra_session_data; $infra_session_data = array(); if (is_null($pass)) { $user = Session::getUser($session_id); $pass = md5($user['password']); } View::setCookie(Session::getName('pass'), $pass); View::setCookie(Session::getName('id'), $session_id); View::setCookie(Session::getName('time'), 1); Session::syncNow(); }