File: /var/www/limestate-api/lib/Core.php
<?php
class Core
{
static $route = array();
static $data = array();
static $presenter = 'default';
static $action = 'default';
static $layout = true;
static $title = '';
/* Параметры зарезервированные системой */
static $reserved = array(
'signin', 'logout'
);
public static function getRoute()
{
$url = isset($_REQUEST['url']) ? $_REQUEST['url'] : $_SERVER['REQUEST_URI'];
$urlData = parse_url($url);
$url = $urlData['path'];
if ($url[0] == "/") $url = substr($url, 1);
if (strlen($url) && $url[strlen($url)-1] == "/") $url = substr($url, 0, -1);
$route = explode("/", $url);
return $route;
}
public static function isPost()
{
return $_SERVER['REQUEST_METHOD'] == 'POST';
}
/**
* Загружает в память все модели из директорий Models и lib
*
* @return void
*/
public static function autoLoader()
{
include(ROOT . 'lib/autoloader.php');
}
/**
* Загружает в память все файлы из директории в память (для классов)
*
* @param string $dirName — имя директории
* @return void
*
* @deprecated
*/
public static function autoDirLoader($dirName)
{
// Импортируем все необходимые модели (все модели)
$handle = opendir(ROOT . $dirName);
$files = array();
while ($e = readdir($handle)) {
if (in_array($e, array('.', '..')) || strpos($e, '.') === 0) continue;
if (strpos($e, '__') === 0) continue;
if (is_file(ROOT . $dirName . '/' . $e)) {
$files[] = ROOT . $dirName . '/' . $e;
}
}
sort($files);
foreach($files as $file) {
include_once($file);
}
}
/**
* Проверяет существование презентора (файла в директории presenter)
*
* @param string $presenterName — имя презентора (имя файла)
* @return boolean
*/
public static function isControllerExists($presenterName)
{
if ($presenterName == '' || is_numeric($presenterName)) {
return false;
}
return file_exists(ROOT . 'Controllers/' . ucfirst($presenterName) . 'Controller.php');
}
/**
* Подключает необходимый презентер и вызывает запрошенный метод
* @param $presenter — имя презентора
* @param $action — имя метода
* @param $data — массив параметров
* @return void
* @throws Exception
*/
public static function loadAction($presenter, $action, $data)
{
if ($presenter == 'default') $presenter = 'home';
if (self::isControllerExists($presenter))
{
if (!class_exists(ucfirst($presenter) . 'Controller'))
{
include_once(ROOT . 'Controllers/' . ucfirst($presenter) . 'Controller.php');
}
$class = ucfirst($presenter) . 'Controller';
$action = 'action' . ucfirst($action);
if (!method_exists($class, $action)) $action = 'action' . ucfirst($action);
if (method_exists($class, $action)) {
$r = new ReflectionMethod($class, $action);
$params = $r->getParameters();
$methodArgs = [];
foreach($params as $param) {
if (isset($data[$param->name])) {
$methodArgs[$param->name] = $data[$param->name];
}
}
if (count($params) == 1 && count($methodArgs) == 0 && isset($data[0])) {
$methodArgs = $data;
}
return call_user_func_array($class . '::' . $action, $methodArgs);
} else {
throw new Exception('Не существует метод ' . $action . ' в презенторе ' . $presenter);
}
} else {
throw new Exception('Не существует презентор: ' . $presenter);
}
}
public static function getTitle()
{
return empty(self::$title) ? 'TODO' : self::$title;
}
/**
* @param $title — заголовок страницы
*/
public static function setTitle($title)
{
self::$title = (string)$title;
}
/**
* Подменяет метод, вызываемый в презенторе
*
* @param $action — имя метода
* @param array $argv – передаваемые аргументы
*/
public static function changeAction($action, $argv = array())
{
self::$action = $action;
self::$data = $argv;
Core::loadAction(self::$presenter, self::$action, self::$data);
}
/**
* Возвращает ссылку по именам презентора и метода
*
* @param $presenter — имя презентора
* @param $action — имя метода
* @param string|bool $add — дополнительный параметр
* @return string — ссылка
*/
public static function buildRoute($presenter, $action, $add = false) {
$link = '';
if ($presenter != 'home') $link .= '/' . strtolower($presenter);
if ($action != 'default') $link .= '/' . strtolower($action);
if ($add !== false) $link .= '/' . $add;
return $link ? $link : '/';
}
public static function buildExternalRoute($presenter, $action, $add = false) {
$insideLink = self::buildRoute($presenter, $action, $add);
return 'http://' . $_SERVER['HTTP_HOST'] . $insideLink;
}
/**
* Разбирает URI и запускает необходимый код
* @throws Exception
*/
public static function route()
{
$route = self::getRoute();
define('IS_AJAX', (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'));
define('IS_API', isset($route[0]) && $route[0] == 'api');
if (IS_API) {
array_shift($route);
Api::$version = $route[0];
array_shift($route);
}
self::$route = $route;
if (isset($route[0]) && self::isControllerExists($route[0])) {
self::$presenter = $route[0];
array_shift($route);
if (isset($route[0]) && $route[0] != '' && !is_numeric($route[0])) {
self::$action = $route[0];
array_shift($route);
} else {
self::$action = 'default';
}
} else {
self::$presenter = 'home';
self::$action = $route[0] == '' ? 'default' : $route[0];
array_shift($route);
}
$isCrcValid = Api::checkCrc(Data::getVar('crc'));
if ($isCrcValid) {
$options = array_merge($route, Ajax::getOptions());
$data = Core::loadAction(self::$presenter, self::$action, $options);
Api::success($data);
} else {
Api::error(2, 'Неправильная контрольная сумма crc (' . Api::getValidCrc('foachbot') . ')');
}
}
/**
* Устанавливает длительное время жизни сессий, а также сохраняет её во внутренню директорию
*/
public static function initSession()
{
ini_set('session.gc_maxlifetime', 120960);
ini_set('session.cookie_lifetime', 120960);
ini_set('session.save_path', ROOT . 'tmp/sessions');
}
public static function checkDirectories()
{
$dirs = ['/tmp/sessions', 'uploads'];
foreach($dirs as $dir) {
if (!file_exists(ROOT . $dir)) {
try {
if (!mkdir(ROOT . $dir, 0755, true)) {
Core::loadTemplate('exceptions/setup', [
'title' => 'Can\'t create directory in ROOT directory',
'description' => 'Creationg ' . $dir . ' failed. Check permissions'
], false, true);
exit();
}
} catch (Exception $e) {
Core::loadTemplate('exceptions/setup', [
'title' => 'Can\'t create directory in ROOT directory',
'description' => 'Creationg ' . $dir . ' failed. Check permissions'
], false, true);
exit();
}
}
}
}
public static function load404()
{
http_response_code(404);
Core::loadTemplate('home/404', [], false);
exit();
}
}