Exemplo n.º 1
0
 public static function init()
 {
     Once::exec(__FILE__, function () {
         //Список операций выполняющихся при любом запросе со спецсимволом в адресе [-~!] и при запросах без файлов
         //или при яном вызове в скрипте Router::init();
         //Собирается конфиг .infra.json из корня проекта
         //Теперь при первом обащении к классу расширения будет собираться его конфиг .infra.json из папки расширения
         Config::init();
         //Анализируется папка vendor Находятся все производители поддерживающие конфигурационные файлы .infra.json
         //Некий производитель angelcharly попадёт в список поиска, если у него есть библиотека с файлом .infra.json
         //Эту обработку можно убрать если производители прописаны вручную в config.path.search проекта
         //Без этой обработке, например, переопределения в кореновм .infra.json для расширения weather
         //не применятся к Weather::$conf и неinfrajs расширения будет работать со значениями по умолчанию
         //.infra.json в самих неinfrajs расширениях также не будет прочитан,
         //но значения конфига по умолчанию и так указаны в переменной класса, вроде Weather::$conf по этому не скажется на работе
         //В общем заполняем config.path.search путями до установленных расширений
         Search::init();
         //Автоматическая установка расширений
         //Cоздаются папка cache и для расширения mem создаётся папка cache/mem, если их нет
         //Наличие этих папок, например, обязательно для Search, который кэширует свою работу
         //Во время обновления запускаются тесты
         Update::init();
         //По дате авторизации админа выход и если браузер прислал информацию что у него есть кэш
         //Заголовок Cache-control:no-store в расширении Nostore::on() запретит создавать кэш, если станет ясно, что modfeied не нужен
         Access::modified();
         //Заголовки по умолчанию для Cache-Controll
         Nostore::init();
         //Вспомогательные заголовки с информацией о правах пользователя test debug admin
         Access::headers();
     });
 }
Exemplo n.º 2
0
 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;
 }
Exemplo n.º 3
0
 public static function exec($conds, $name, $fn, $args = array(), $re = false)
 {
     $name = 'Cache::exec' . $name;
     return Once::exec($name, function ($args, $r, $hash) use($name, $fn, $conds, $re) {
         $data = Mem::get($name . $hash);
         if (!$data) {
             $data = array('time' => 0);
         }
         $execute = Access::adminIsTime($data['time'], function ($cache_time) use($conds) {
             if (!sizeof($conds)) {
                 return false;
                 //Если нет conds кэш навсегда и develop не поможет
             }
             $max_time = 1;
             for ($i = 0, $l = sizeof($conds); $i < $l; $i++) {
                 $mark = $conds[$i];
                 $mark = Path::theme($mark);
                 if (!$mark) {
                     continue;
                 }
                 $m = filemtime($mark);
                 if ($m > $max_time) {
                     $max_time = $m;
                 }
                 if (!is_dir($mark)) {
                     continue;
                 }
                 foreach (glob($mark . '*.*') as $filename) {
                     $m = filemtime($filename);
                     if ($m > $max_time) {
                         $max_time = $m;
                     }
                 }
             }
             return $max_time > $cache_time;
         }, $re);
         if ($execute) {
             $cache = Nostore::check(function () use(&$data, $fn, $args, $re) {
                 $data['result'] = call_user_func_array($fn, array_merge($args, array($re)));
             });
             if ($cache) {
                 $data['time'] = time();
                 Mem::set($name . $hash, $data);
             } else {
                 Mem::delete($name . $hash);
             }
         }
         return $data['result'];
     }, array($args), $re);
 }
Exemplo n.º 4
0
function autoedit_theme($isrc)
{
    $src = Access::cache('autoedit_theme', function ($isrc) {
        $src = Path::theme($isrc);
        if ($src) {
            return $src;
        }
        $fdata = Load::srcInfo($isrc);
        $folder = Path::theme($fdata['folder']);
        if (!Path::theme($folder)) {
            return false;
        }
        array_map(function ($file) use(&$result, $fdata) {
            if ($file[0] == '.') {
                return;
            }
            $file = Path::toutf($file);
            $fd = Load::nameInfo($file);
            if ($fdata['id'] && $fdata['id'] != $fd['id']) {
                return;
            }
            if ($fdata['name'] && $fdata['name'] != $fd['name']) {
                return;
            }
            if ($fdata['ext'] && $fdata['ext'] != $fd['ext']) {
                return;
            } elseif ($result) {
                //Расширение не указано и уже есть результат
                //Исключение.. расширение tpl самое авторитетное
                if ($fd['ext'] != 'tpl') {
                    return;
                }
            }
            $result = $file;
        }, scandir(Path::theme($folder)));
        if (!$result) {
            return false;
        }
        return Path::theme($folder . $result);
    }, array($isrc), isset($_GET['re']));
    return $src;
}
Exemplo n.º 5
0
 public static function init()
 {
     Once::exec(__FILE__ . 'init', function () {
         $action = Ans::GET('-update');
         Config::init();
         $path = Path::$conf;
         if ($action) {
             Access::test(true);
             if (!Update::$is) {
                 Path::fullrmdir($path['cache']);
                 Update::exec();
             }
         }
         if ($path['fs'] && !Update::$is) {
             if (!is_dir($path['cache'])) {
                 Access::$conf['test'] = true;
                 Update::exec();
             }
             if (Access::isTest()) {
                 if (is_file($path['data'] . 'update')) {
                     unlink($path['data'] . 'update');
                     Access::$conf['test'] = true;
                     if (!Update::$is) {
                         Path::fullrmdir($path['cache']);
                         Update::exec();
                     }
                 }
             }
         }
         if (Update::$is) {
             if (is_file($path['data'] . 'update')) {
                 unlink($path['data'] . 'update');
             }
         }
     });
 }
Exemplo n.º 6
0
<?php

namespace infrajs\infra;

use infrajs\access\Access;
use infrajs\path\Path;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
}
require_once 'vendor/autoload.php';
Config::init();
Access::modified();
Access::headers();
Install::init();
Path::init();
Exemplo n.º 7
0
use infrajs\access\Access;
use infrajs\path\Path;
use infrajs\load\Load;
use infrajs\ans\Ans;
use infrajs\config\Config;
use infrajs\each\Each;
use infrajs\template\Template;
use infrajs\router\Router;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
    require_once 'vendor/autoload.php';
    Router::init();
}
Config::init();
Access::test(true);
header('Infrajs-Test: Start');
$type = Ans::GET('type');
/** type=auto - Запуск всех тестов. Выполняется из других скриптов Load::loadJSON('-tester/?type=auto');
 *  Если все result true выдать один положительный ответ result: true
 *  Если найдена ошибка то добавляется переадресация на страницу с ошибками type=errors без exit
 *  type=errors - показывает только ошибки и инструкцию для справления
 *  Если ошибок нет переадресовывает на -tester/
 **/
$ans = array();
$plugin = Ans::GET('plugin');
$conf = Config::get();
$list = array();
foreach ($conf as $name => $c) {
    if ($plugin && $plugin != $name) {
        continue;
Exemplo n.º 8
0
    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);
Exemplo n.º 9
0
$map = Access::cache('mdreader', function () {
    $map = array('vendors' => array());
    $dir = 'vendor/';
    array_map(function ($file) use(&$map, $dir) {
        if ($file == '.') {
            $dir = '';
            $file = '.';
            $vendor = $_SERVER['HTTP_HOST'];
        } else {
            if ($file[0] == '.') {
                return;
            } else {
                $vendor = Path::toutf($file);
            }
        }
        if (!is_dir($dir . $file)) {
            return;
        }
        $dir = $dir . $file . '/';
        if (empty($map['vendors'][$vendor])) {
            $map[$vendor] = array();
        }
        array_map(function ($file) use(&$map, $dir, $vendor) {
            if (!is_dir($dir . $file)) {
                return;
            }
            if ($dir == './') {
                if ($file == '.') {
                    $dir = '';
                    $file = '.';
                    $name = $_SERVER['HTTP_HOST'];
                } else {
                    if ($file[0] == '.') {
                        return;
                    } else {
                        $name = Path::toutf($file);
                    }
                }
                $sysdir = $dir . $file . '/';
                if ($sysdir == './' . Path::$conf['data']) {
                    return;
                }
                if ($sysdir == './' . Path::$conf['cache']) {
                    return;
                }
                if ($sysdir == './vendor/') {
                    return;
                }
            } else {
                if ($file[0] == '.') {
                    return;
                }
                $name = Path::toutf($file);
            }
            $dir = $dir . $file . '/';
            if (empty($map['vendors'][$vendor][$name])) {
                $map['vendors'][$vendor][$name] = array('src' => $dir . 'README.md', 'vendor' => $vendor, 'name' => $name, 'is' => is_file($dir . 'README.md'), 'list' => array());
            }
            array_map(function ($file) use(&$map, $dir, $vendor, $name) {
                if ($file[0] == '.') {
                    return;
                }
                if (!is_file($dir . $file)) {
                    return;
                }
                $ext = Path::getExt($file);
                if ($ext != 'md') {
                    return;
                }
                $res = array('src' => $dir . $file, 'vendor' => $vendor, 'name' => $name, 'file' => $file);
                $map['vendors'][$vendor][$name]['list'][] = $res;
                $map['names'][$dir] =& $map['vendors'][$vendor][$name];
            }, scandir($dir));
        }, scandir($dir));
    }, scandir($dir));
    return $map;
});
Exemplo n.º 10
0
$ans = array('id' => $id, 'type' => $type, 'msg' => '');
if (in_array($type, array('admin'))) {
    if (!$submit) {
        $ans['admin'] = Access::admin();
    } else {
        $ans['admin'] = Access::admin(array(@$_REQUEST['login'], @$_REQUEST['pass']));
        if (!$ans['admin']) {
            if (isset($_REQUEST['login'])) {
                return Ans::err($ans, 'Неправильный пароль!');
            } else {
                return Ans::ret($ans, 'Вы успешно вышли!');
            }
        }
    }
}
if (!Access::admin()) {
    return Ans::err($ans, 'Вам нужно авторизоваться');
}
if (in_array($type, array('mvdir', 'mkdir', 'cpdir', 'rmdir'))) {
    if ($id[0] != '~') {
        return Ans::err($ans, 'Путь должен начинаться с ~');
    }
    if ($type === 'mkdir' && !Path::theme($id, 'snd')) {
        return Ans::err($ans, 'Нет папки в которой нужно создать');
    }
    if ($type === 'mvdir' && !Path::theme($id, 'snd')) {
        return Ans::err($ans, 'Нет папки которую нужно перенести');
    }
    if ($type === 'cpdir' && !Path::theme($id, 'snd')) {
        return Ans::err($ans, 'Нет папки которую нужно скопировать');
    }
Exemplo n.º 11
0
<?php

use infrajs\event\Event;
use infrajs\view\View;
use infrajs\access\Access;
use WyriHaximus\HtmlCompress;
Event::one('Controller.onshow', function () {
    if (Access::debug()) {
        return;
    }
    $html = View::html();
    $parser = HtmlCompress\Factory::construct();
    $html = $parser->compress($html);
    View::html($html, true);
});
Exemplo n.º 12
0
			<p><a href="?">Проверить</a></p>
		</div>
<?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>
Exemplo n.º 13
0
<?php

namespace infrajs\infra;

use infrajs\access\Access;
use infrajs\event\Event;
use infrajs\ans\Ans;
use infrajs\path\Path;
use infrajs\session\Session;
if (!is_file('vendor/autoload.php')) {
    chdir(explode('vendor/', __DIR__)[0]);
    require_once 'vendor/autoload.php';
}
Access::admin(true);
$ans = array();
if (isset($_GET['get'])) {
    $name = Ans::REQ('name');
    $ans['id'] = Session::getId();
    $ans['data'] = Session::get($name);
} else {
    if (isset($_GET['clear'])) {
        Session::clear();
    } else {
        if (isset($_GET['set'])) {
            $ans = array();
            $name = Path::toutf($_REQUEST['name']);
            $val = Path::toutf($_REQUEST['val']);
            Session::set($name, $val);
        }
    }
}
Exemplo n.º 14
0
<?php

use infrajs\ans\Ans;
use infrajs\access\Access;
use infrajs\nostore\Nostore;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
    require_once 'vendor/autoload.php';
}
Nostore::on();
$ans = array();
$ans['test'] = Access::test();
$ans['debug'] = Access::debug();
$ans['admin'] = Access::admin();
return Ans::ret($ans);
Exemplo n.º 15
0
    chdir('../../../');
    //Согласно фактическому расположению файла
    require_once 'vendor/autoload.php';
}
ini_set("display_errors", 1);
$from = 'noreplay@' . $_SERVER['HTTP_HOST'];
$headers = 'From: ' . $from . "\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
$headers .= 'Reply-To: aky@list.ru' . "\r\n";
//echo 'Нативная проверка<br>';
//$r=mail('*****@*****.**','Проверка с сервера '.$_SERVER['HTTP_HOST'],'Текст проверочного сообщения',$headers);
//var_dump($r);
//return;//нельзя зачастую лимит стоит сколько писем за раз можно отправлять
//echo '<br>Сложная проверка<br>';
$conf = Access::$conf['admin'];
$ans = array();
if (!$conf['support']) {
    return Ans::err($ans, 'У администратора не указан email support');
}
$body = Path::theme('-mail/update.tpl');
$body = file_get_contents($body);
$body = str_replace(array("{host}", "{date}"), array($_SERVER['HTTP_HOST'], date('j.m.Y')), $body);
$subject = 'Выполнено обновление ' . $_SERVER['HTTP_HOST'];
$email_from = 'noreplay@' . $_SERVER['HTTP_HOST'];
$r = Mail::toSupport($subject, $email_from, $body);
if (!$r) {
    error_log('Не удалось отправить тестовое письмо.');
    if (Access::debug() && !Load::isphp()) {
        echo '<pre>Не удалось отправить <a href="/-mail/update.php">тестовое письмо</a>.</pre>' . "\n";
    }
}
Exemplo n.º 16
0
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);
    }
    $key = array_search('127.0.0.1', $debug);
    if ($key !== false) {
        array_splice($debug, $key, 1);
Exemplo n.º 17
0
<?php

use infrajs\router\Router;
use infrajs\ans\Ans;
use infrajs\config\Config;
use infrajs\access\Access;
use infrajs\load\Load;
use infrajs\nostore\Nostore;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
    require_once 'vendor/autoload.php';
    Router::init();
}
$action = Ans::GET('-tester');
if ($action == 'true') {
    Nostore::on();
    if (Access::test()) {
        $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>';
        }
    } else {
        $ans = array();
        die('<div class="alert alert-danger">Недостаточно прав для тестирования.</div>');
    }
}
Exemplo n.º 18
0
 public static function getPos(&$pos)
 {
     $args = array($pos['producer'], $pos['article']);
     return Access::cache('Catalog::getPos', function () use($pos) {
         Xlsx::addFiles(Catalog::$conf['dir'], $pos);
         $files = explode(',', @$pos['Файлы']);
         foreach ($files as $f) {
             if (!$f) {
                 continue;
             }
             $f = trim($f);
             Xlsx::addFiles(Catalog::$conf['dir'], $pos, $f);
         }
         $files = array();
         foreach ($pos['files'] as $f) {
             if (is_string($f)) {
                 $f = Path::theme($f);
                 //убрали звездочку
                 $d = Load::srcInfo(Path::toutf($f));
             } else {
                 $d = $f;
                 $f = $d['src'];
             }
             $d['size'] = round(filesize(Path::tofs($f)) / 1000000, 2);
             if (!$d['size']) {
                 $d['size'] = '0.01';
             }
             $d['src'] = Path::pretty($d['src']);
             $files[] = $d;
         }
         $pos['files'] = $files;
         if ($pos['texts']) {
             foreach ($pos['texts'] as $k => $t) {
                 $pos['texts'][$k] = Load::loadTEXT('-doc/get.php?src=' . $t);
             }
         }
         return $pos;
     }, $args);
 }
Exemplo n.º 19
0
use infrajs\load\Load;
use infrajs\access\Access;
use infrajs\ans\Ans;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
    require_once 'vendor/autoload.php';
}
$ans = array();
$ans['title'] = 'Общая проверка';
Access::test(true);
$res = Load::loadJSON('-autoedit/autoedit.php?type=editfile&id=~.infra.json');
if (Access::admin()) {
    if (!$res['result'] || !$res['isfile']) {
        return Ans::err($ans, 'Неудалось получить информацию о файле .infra.json');
    }
} else {
    if (!$res || $res['result']) {
        return Ans::err($ans, 'Неудалось обратиться за файлом .infra.json');
    }
}
$res = Load::loadJSON('-autoedit/autoedit.php?type=editfolder&id=~');
if (Access::admin()) {
    if (!$res['result'] || !sizeof($res['list'])) {
        return Ans::err($ans, 'Неудалось прочитать папку');
    }
} else {
    if (!$res || $res['result']) {
        return Ans::err($ans, 'Неудалось обратиться к папке');
    }
}
return Ans::ret($ans, 'Вроде ок, прочитали папку, посмотрели файл');
Exemplo n.º 20
0
    $p = explode(',', $lim);
    if (sizeof($p) != 2) {
        return Ans::err($ans, 'Некорректный параметр lim');
    }
    list($start, $count) = $p;
    $list = Access::cache(__FILE__, function ($dir) {
        $list = array();
        array_map(function ($file) use(&$list, $dir) {
            if ($file[0] == '.') {
                return;
            }
            if ($file[0] == '~') {
                return;
            }
            //Скрытый файл Word
            if (!is_file(Path::theme($dir) . $file)) {
                return;
            }
            $fd = Load::nameinfo($file);
            if (!in_array($fd['ext'], array('docx', 'html', 'tpl'))) {
                return;
            }
            $list[] = Rubrics::info(Path::toutf($dir . $file));
        }, scandir(Path::theme($dir)));
        Load::sort($list);
        return $list;
    }, array($dir));
    $list = array_slice($list, $start, $count);
    $ans['list'] = $list;
} else {
    if ($type == 'page') {
        if ($type == 'page') {
Exemplo n.º 21
0
<?php

use infrajs\access\Access;
use infrajs\ans\Ans;
use infrajs\nostore\Nostore;
$action = Ans::GET('-access');
if ($action == 'false') {
    if (Access::isTest()) {
        Access::$conf['test'] = true;
    } else {
        Access::$conf['test'] = false;
    }
    //Повышать права нельзя, если я не тестер, то нетестером и останусь!!!
    Access::$conf['debug'] = false;
    Access::$conf['admin'] = false;
    Nostore::on();
} else {
    if ($action == 'true') {
        Access::test(true);
        Access::adminSetTime();
        Nostore::on();
        //Страница с таким параметром не кэшируется в браузере и её можно всегда спокойно вызывать
        //Устанавливает будто админ только что заходил... это мягко обновит кэши шаблонов и проверит изменения файлов
    }
}
Exemplo n.º 22
0
<?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);
Exemplo n.º 23
0
//Кэшируется, если public разрешён, как статика, надолго
if (isset($_GET['js'])) {
    $isjs = 'js';
} else {
    if (isset($_GET['css'])) {
        $isjs = '';
    } else {
        die('Необходимо добавить параметр css или js');
    }
}
if (!Load::isphp()) {
    header('Infrajs-Cache: true');
}
$re = isset($_GET['re']);
//Modified re нужно обновлять с ctrl+F5
$debug = Access::debug();
$name = Ans::GET('name', 'string', '');
if ($debug || $re) {
    if (!Load::isphp()) {
        header('Infrajs-Cache: false');
    }
    if ($isjs) {
        $code = Collect::js($name);
    } else {
        $code = Collect::css($name);
    }
    $key = 'Infrajs::Collect::' . $isjs . true;
    //Кэш с zip
    Mem::delete($key);
    $key = 'Infrajs::Collect::' . $isjs . false;
    //Кэш без zip
Exemplo n.º 24
0
 public static function getHtml(&$layer)
 {
     //Вызывается как для основных так и для подслойв tpls frame. Расширяется в tpltpl.prop.js
     //if(@$layer['tplclient'])return '';
     $row = Layer::parsed($layer);
     //$row=$_SERVER['QUERY_STRING'],$layer['id'];
     //Нельзя кэшировать слои в которых показываются динамические данные, данные пользователя определяется заголовком у данных
     //Кэш создаётся от любого пользователя.
     //Чтобы узнать что кэш делать не нужно... это знают данные они либо js либо php
     //При загрузки данных те должны выкидывать заголовки не кэшировать, либо не выкидывать если это просто парсер Excel
     //Нас интересует зависит ли html слоя от пользователя, если зависит кэшировать нельзя
     //Зависит если используется $_SESSION, infra_session, infra_admin
     //примечательно что конект к базе не запрещает кэширование этого слоя
     //Узнавать о всём этом мы будем по заголовкам
     //Так чтобы следующий слой взялся уже нормально заголовки нужно заменять...
     //Тем более заменять заголовки нужно в любом случае если кэшируется чтобы и браузер кэшировал
     //Проблема при первом session_get конект к базе и вызов session_init в следующем подключении init не вызывается
     //но для следующего подключения нам нужно понять что есть динамика// По этому загловки отправляются в том числе и руками в скритпах  Cache-Control:no-cache
     $html = Access::cache('infrajs_getHtml', function () use(&$layer) {
         //Здесь мог быть установлен infrajs['com'] его тоже нужно вернуть/ А вот после loadTEXT мог быть кэш и ничего не установится
         $html = Tpl::_getHtml($layer);
         return $html;
     }, array($row));
     //Кэш обновляемый с последней авторизацией админа определяется строкой parsed слоя
     return $html;
 }
Exemplo n.º 25
0
}
$order = Ans::GET('order', ['descending', 'ascending']);
$ans['order'] = $order;
$list = Access::cache(__FILE__, function ($dir, $order) {
    $list = array();
    array_map(function ($file) use(&$list, $dir) {
        if ($file[0] == '.') {
            return;
        }
        $file = Path::toutf($file);
        if (!Path::theme($dir . $file)) {
            return;
        }
        $fd = Load::nameInfo($file);
        if (!in_array($fd['ext'], array('jpg', 'png'))) {
            return;
        }
        $slide = $fd;
        $slide['title'] = $fd['name'];
        $src = Rubrics::find($dir, $fd['name'], 'articles');
        if ($src) {
            $slide['title'] = Rubrics::article($src);
        }
        $list[] = $slide;
    }, scandir(Path::theme($dir)));
    Load::sort($list, $order);
    //$list = array_reverse($list);
    return $list;
}, array($dir, $order));
$list = array_slice($list, $start, $count);
$ans['dir'] = $dir;
$ans['list'] = $list;
Exemplo n.º 26
0
 public static function headers()
 {
     if (Access::isTest()) {
         //error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
         //ini_set('display_errors', 1);
         header('Infrajs-Test:true');
     } else {
         //error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
         header('Infrajs-Test:false');
         //ini_set('display_errors', 0);
     }
     if (Access::isDebug()) {
         header('Infrajs-Debug:true');
         Nostore::on();
         //Браузер не кэширует no-store.
     } else {
         header('Infrajs-Debug:false');
     }
     if (Access::isAdmin()) {
         header('Infrajs-Admin:true');
         Access::adminSetTime();
     } else {
         header('Infrajs-Admin:false');
     }
 }