Example #1
0
 /**
  * Стартуем
  * @param $content
  * @return void
  */
 public function run(&$content)
 {
     //Путь к файлу
     $__path = $this->file;
     //Счетчик времени
     $time = Boot::mktime();
     //Оборачиваем все в функцию
     $view = function ($params, $content) use($__path) {
         //Извлекаем переменные
         if (!empty($params)) {
             extract((array) $params);
         }
         //Запускаем отладчик
         ob_start();
         //Подключаем файл
         require $__path;
         //Выполняем сценарий
         $html = ob_get_contents();
         ob_end_clean();
         //Возвращаем данные
         return $html;
     };
     //Выполняем функцию
     $html = $view((array) Boot_Controller::getInstance()->view, $content);
     //Debug
     Boot::getInstance()->debug("  Rendered " . str_replace(APPLICATION_PATH . "/", "", $__path) . " (" . Boot::check_time($time) . "ms)");
     echo $html;
 }
Example #2
0
File: auth.php Project: pnixx/boot
 /**
  * Получаем инстанс
  * @static
  * @return Boot_Auth_Lib
  */
 public static function getInstance()
 {
     if (!self::$_instance instanceof Boot_Auth_Lib) {
         self::$_instance = new Boot_Auth_Lib();
         self::$_instance->skey = Boot::getInstance()->config->auth_skey;
     }
     return self::$_instance;
 }
Example #3
0
 /**
  * Обрабатываем библиотеки, в которых добавлена прослушка на ошибки
  * @param Throwable $e
  */
 public static function sendLibraryException($e)
 {
     if (Boot::getInstance()->library) {
         foreach (Boot::getInstance()->library->getLibraries() as $library) {
             if (in_array("Boot_Exception_Interface", class_implements($library, false))) {
                 $library->onException($e);
             }
         }
     }
 }
Example #4
0
 /**
  * Получение только разрешенных параметров
  * @return array
  */
 public function getValues()
 {
     $values = [];
     if (array_diff(array_keys($this->_params), $this->_permit)) {
         Boot::getInstance()->debug('  Unpermitted params: ' . implode(', ', array_diff(array_keys($this->_params), $this->_permit)));
     }
     foreach ($this->_params as $key => $param) {
         if (in_array($key, $this->_permit)) {
             $values[$key] = $param;
         }
     }
     return $values;
 }
Example #5
0
File: db.php Project: pnixx/boot
 /**
  * Конструктор
  */
 public function __construct()
 {
     //Получаем имя драйвера
     $db = Boot::getInstance()->config->db;
     $driver = $db->adapter;
     $host = $db->host;
     $port = $db->port;
     $user = $db->user;
     $pass = $db->password;
     $dbase = $db->dbase;
     //Инитим драйвер
     $this->_db = new $driver($host, $port, $user, $pass, $dbase);
     //Подключаемся к базе
     $this->_db->connect();
 }
Example #6
0
 /**
  * SQL query
  * @param	$query
  * @return postgres
  */
 public function query($query)
 {
     //Запоминаем время начала
     $time = Boot::mktime();
     //Делаем запрос
     $this->result = @pg_query($this->_connect, $query) or $this->error($query);
     //Debug
     Boot::getInstance()->debug("  SQL (" . Boot::check_time($time) . "ms) " . $query);
     //Return
     return $this;
 }
Example #7
0
File: flash.php Project: pnixx/boot
 public function set($name, $value)
 {
     $this->_flash[$name] = $value;
     setcookie('flash', serialize($this->_flash), null, "/", Boot::getInstance()->config->host);
 }
Example #8
0
File: mail.php Project: pnixx/boot
 /**
  * Обработка ошибки
  * @param Throwable $e
  * @return mixed
  */
 public static function onException($e)
 {
     if (APPLICATION_ENV == 'production' && ($e->getCode() >= 500 || $e->getCode() == 0) && isset(Boot::getInstance()->config->mail->error)) {
         self::send(Boot::getInstance()->config->mail->error, "Error", "<pre>Error " . $e->getCode() . ": " . $e->getMessage() . "\r\n" . $e->getTraceAsString() . "SERVER:\r\n" . var_export($_SERVER, true) . "POST:\r\n" . var_export($_POST, true) . "</pre>");
     }
 }
Example #9
0
File: debug.php Project: pnixx/boot
 /**
  * Обработка ошибки
  * @param Throwable $e
  * @return mixed
  */
 public static function onException($e)
 {
     Boot::getInstance()->debug("  Message: " . $e->getMessage() . "" . PHP_EOL . $e->getTraceAsString());
 }
Example #10
0
//Проходим по файлам, ищем ключи для перевода
$files = glob_recursive(APPLICATION_PATH . "/*.php", GLOB_NOSORT);
$files = array_merge($files, glob_recursive(APPLICATION_PATH . "/*.phtml", GLOB_NOSORT));
$keys = array();
foreach ($files as $file) {
    //"/_\(\"(.+)\"(?:,\s?(?:$\w+|\"\w+\"))?\)/"
    if (preg_match_all("/->_\\(\"([^\r\n]+?)\",?/", file_get_contents($file), $po) && isset($po[1])) {
        //		print_r($po);
        foreach ($po[1] as $i => $key) {
            $key = str_replace("\\\$", "\$", $key);
            if (isset($parse[$key]) == false) {
                echo $key . "\r\n";
                $parse[$key] = "";
            }
            $keys[] = $key;
        }
    }
}
//Получаем ключи, которых не нашли на сайте
$diff = array_diff(array_keys($parse), $keys);
//Проходим по ним и удаляем
foreach ($diff as $d) {
    unset($parse[$d]);
}
//Если файл старой версии существует, удаляем
if (file_exists(Boot::getInstance()->config->translate->dir . Boot::getInstance()->config->translate->lang . ".po")) {
    unlink(Boot::getInstance()->config->translate->dir . Boot::getInstance()->config->translate->lang . ".po");
}
//Записываем все значения в массив
file_put_contents(Boot::getInstance()->config->translate->dir . Boot::getInstance()->config->translate->lang . ".json", json_encode($parse, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
Example #11
0
File: boot.php Project: pnixx/boot
 /**
  * Инициализация для крона
  * @return void
  */
 public function cron()
 {
     define('APPLICATION_CLI', true);
     $this->root = realpath(dirname(__FILE__));
     header("Content-type: text/html; charset=UTF-8");
     //Загружаем класс ошибок
     require_once 'boot/exception/exception.php';
     require_once 'boot/exception/db.php';
     //Инклудим треды
     require_once SYSTEM_PATH . '/boot/trait/controller.php';
     foreach (glob(SYSTEM_PATH . '/boot/trait/' . '*.php') as $path) {
         require_once $path;
     }
     //Инклудим абстрактные классы
     foreach (glob(SYSTEM_PATH . '/boot/abstract/' . '*.php') as $path) {
         require_once $path;
     }
     //Инклудим интерфейсы
     foreach (glob(SYSTEM_PATH . '/boot/interface/' . '*.php') as $path) {
         require_once $path;
     }
     require_once 'library/log.php';
     //Устанавливаем отлавливатели ошибок
     set_error_handler('Boot_Exception::err_handler');
     set_exception_handler("Boot_Exception::ex");
     register_shutdown_function(function () {
         $error = error_get_last();
         if ($error) {
             Boot_Exception::err_handler($error['type'], $error['message'], $error['file'], $error['line'], null);
         } else {
             Boot::getInstance()->end();
         }
     });
     //Загружаем конфиг
     $this->config();
     //Загружаем драйвер БД
     $this->load_model();
     //Устанавливаем путь подключения моделей
     set_include_path(APPLICATION_PATH);
     spl_autoload_register(array("Boot", "autoload"));
     //Загружаем библиотеки
     $this->load_library();
     //Debug
     $this->debug(PHP_EOL . "Console at " . date("Y-m-d H:i:s O"));
     if (isset($_SERVER['argv'])) {
         $this->debug("  File: " . implode(" ", $_SERVER['argv']));
     }
 }
Example #12
0
 /**
  * @param $lang
  * @return array
  * @throws Exception
  */
 public function parseJSON($lang)
 {
     //Если раньше до этого не парсили
     if (!isset($this->_parse[$lang])) {
         //Проверяем существование файла
         if (file_exists($this->_dir . $lang . ".json")) {
             //Читаем файл
             $this->_parse[$lang] = json_decode(file_get_contents($this->_dir . $lang . ".json"), true);
         } else {
             $this->_parse[$lang] = [];
             Boot::getInstance()->debug("Файл перевода языка не найден: {$lang}.json", true);
         }
     }
     return $this->_parse[$lang];
 }
Example #13
0
 /**
  * Создание версии для файла
  * @param             $path
  * @param null|string $name
  * @param array       $process
  * @throws Boot_Exception
  */
 private function create_version($path, $name, array $process)
 {
     //Дебаг
     Boot::getInstance()->debug("  * Create image version: " . $this->storeDir() . '/' . $this->filename($name) . "");
     //Выбираем действие
     switch ($process[0]) {
         //Fill
         case "resize_to_fill":
             $this->processFill($path, $name, $process[1]);
             break;
             //Fit
         //Fit
         case "resize_to_fit":
             $this->processFit($path, $name, $process[1]);
             break;
             //Resize
         //Resize
         case "resize":
             $this->processResize($path, $name, $process[1]);
             break;
             //Неизвестный процесс
         //Неизвестный процесс
         default:
             throw new Boot_Exception("Unknown uploader process name: " . $process[0]);
     }
 }
Example #14
0
            $insert = "\$migration = " . var_export(array("change" => array($match[1] => array($table => $schema))), true) . ";";
            break;
        case Boot_Migration::TYPE_UP:
            $insert = "\$migration = " . var_export(array("up" => array("sql" => isset($argv[2]) ? $argv[2] : ""), "down" => array("sql" => isset($argv[3]) ? $argv[3] : "")), true) . ";";
            break;
        default:
            echo "Incorrect type of the migration";
            exit(127);
            break;
    }
    //Добавляем в файл
    file_put_contents(APPLICATION_ROOT . "/db/" . date("YmdHis") . "_" . $name . ".php", "<?\r\n/**\r\n * Boot framework\r\n * Author: P.Nixx\r\n * Site: pnixx.ru\r\n*/\r\n\r\n" . $insert);
    echo "create migration: " . APPLICATION_ROOT . "/db/" . date("YmdHis") . "_" . $name . ".php\r\n";
    if (isset($model)) {
        file_put_contents(APPLICATION_PATH . "/models/" . $table . ".php", $model);
        echo "create model: " . APPLICATION_PATH . "/models/" . $table . ".php\r\n";
    }
    //	if( isset($model_row) ) {
    //		if( is_dir(APPLICATION_PATH . "/models/row/") == false ) {
    //			mkdir(APPLICATION_PATH . "/models/row/");
    //			chmod(APPLICATION_PATH . "/models/row/", 0777);
    //		}
    //		file_put_contents(
    //			APPLICATION_PATH . "/models/row/" . $table . "_row.php",
    //			$model_row
    //		);
    //		echo "create row model: " . APPLICATION_PATH . "/models/row/" . $table . "_row.php\r\n";
    //	}
}
Boot::getInstance()->end();
Example #15
0
File: model.php Project: pnixx/boot
 /**
  * Подключаемся к БД
  * @return void
  */
 public function connect()
 {
     //Проверяем было ли подключение
     Boot::getInstance()->_connect = $this->_db->connect();
 }
Example #16
0
 /**
  * Запись в cookie
  * @static
  * @param      $name
  * @param      $value
  * @param bool $subdomain
  */
 public static function set($name, $value, $subdomain = false)
 {
     setcookie($name, $value, time() + 2678400, "/", $subdomain ? '.' . Boot::getInstance()->config->host : null);
 }
Example #17
0
 /**
  * Получение заголовка для label
  * @param $name
  * @param $params
  * @return string
  */
 private function getLabelTitle($name, $params)
 {
     //Если был указан заголовок
     if (isset($params["label"])) {
         return $params["label"];
     }
     //Если есть класс переводчика
     if (class_exists("Boot_Translate_Lib", false)) {
         return Boot::getInstance()->library->{"translate"}->_($name);
     }
     //Возвращаем имя
     return ucfirst($name);
 }
Example #18
0
 /**
  * Указываем лимит выборки
  * @param $limit
  * @param $offset
  * @return Select
  */
 public function limit($limit, $offset = null)
 {
     if ($limit) {
         $this->_limit = " LIMIT {$limit}" . ($offset ? (Boot::getInstance()->config->db == "mysql" ? "," : " OFFSET ") . $offset : "");
     } else {
         $this->_limit = null;
     }
     return $this;
 }
Example #19
0
File: view.php Project: pnixx/boot
 /**
  * Рендирит шаблон
  * @param string $file Путь к файлу от каталога /application/views без расширения
  * @param array  $params
  * @throws Boot_Exception
  */
 private function _render($file, $params = [])
 {
     //Строим полный путь
     $__path = null;
     //Проверяем наличие шаблона
     $paths = explode(PATH_SEPARATOR, get_include_path());
     foreach ($paths as $p) {
         if (file_exists(realpath($p) . '/' . $file . '.phtml')) {
             $__path = realpath($p) . '/' . $file . '.phtml';
             break;
         }
     }
     //Если не нашли шаблон
     if ($__path == null) {
         throw new Boot_Exception('View "' . $file . '.phtml" not exist');
     }
     //Счетчик времени
     $time = Boot::mktime();
     //Оборачиваем все в функцию
     $view = function ($params) use($__path) {
         //Извлекаем переменные
         if (!empty($params)) {
             extract((array) $params);
         }
         //Запускаем отладчик
         ob_start();
         //Подключаем файл
         require $__path;
         //Выполняем сценарий
         $html = ob_get_contents();
         ob_end_clean();
         //Возвращаем данные
         return $html;
     };
     //Выполняем функцию
     $html = $view($params);
     //Debug
     Boot::getInstance()->debug("  Rendered " . str_replace(APPLICATION_PATH . "/", "", $__path) . " (" . Boot::check_time($time) . "ms)");
     //Возвращаем результат
     return $html;
 }
Example #20
0
File: skey.php Project: pnixx/boot
 /**
  * Парсинг закрытого ключа
  * @static
  * @param $skey
  */
 public static function validKey($skey)
 {
     //Разбиваем
     $match = explode("_", $skey);
     //Если вроде всё правильно получили
     if ($match && count($match) == 3) {
         //Проверяем правильность ключа
         if (md5(Boot::getInstance()->config->default->skey . $match[2] . $match[1]) == $match[0]) {
             return true;
         }
     }
     return false;
 }
Example #21
0
 /**
  * Редирект
  * @param $url
  * @return void
  */
 public function _redirect($url)
 {
     //Debug
     Boot::getInstance()->debug("  Redirect to: " . $url . "");
     Boot::getInstance()->end();
     Boot_Flash::getInstance()->set("referer", "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
     header("Location: " . $url);
     exit;
 }
Example #22
0
 /**
  * Инициализация библиотеки во вьюхе и контроллере
  * @param Boot_View|Boot_Layout|Boot_Abstract_Controller $class
  * @return void
  */
 public function init(&$class)
 {
     $class->{$this->key} = Boot::getInstance()->library->{$this->key};
 }
Example #23
0
File: log.php Project: pnixx/boot
 /**
  * Очистка лога
  * @param $file
  */
 public static function clear($file)
 {
     //Добавляем в лог
     file_put_contents(Boot::getInstance()->config->log->dir . $file, "");
 }
Example #24
0
File: cache.php Project: pnixx/boot
 /**
  * При ошибке подключения
  * @param $message
  */
 private function error($message)
 {
     $this->connected = false;
     Boot::getInstance()->debug("  " . $message . "");
 }
Example #25
0
 /**
  * Offset to retrieve
  * @param mixed $offset
  * @return array Can return all value types.
  */
 public function offsetGet($offset)
 {
     Boot::getInstance()->debug('get: ' . $offset);
     $messages = [];
     if ($this->offsetExists($offset)) {
         foreach ($this->errors[$offset] as $message) {
             $messages[] = $message;
         }
     }
     return $messages;
 }
Example #26
0
 private static function getControllerRoute($param = null)
 {
     return (object) array("controller" => isset($param[0]) ? $param[0] : Boot::getInstance()->config->default->page, "action" => isset($param[1]) && $param[1] ? $param[1] : "index");
 }
Example #27
0
File: mail.php Project: pnixx/boot
 public static function send($mail, $title, $message, $from = null)
 {
     $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=utf-8' . "\r\n" . 'From: ' . ($from ? $from : 'info@' . Boot::getInstance()->config->host) . "\r\n";
     return mail($mail, $title, $message, $headers);
 }