Commit 52e30f8b by semenov

Обновлен гайд по установке

parent 99b8ad7e
......@@ -28,7 +28,6 @@
* COMMON_ENV_CONFIG_DIR //Дирриктория с конфигами common для текущего окружения
* APP_ENV_CONFIG_DIR //Дирриктория с конфигами текущего приложения для текущего окружения
*/
define("APP_DIR", __DIR__);
define("APP_CONFIG_DIR", realpath(__DIR__ . '/../config'));
define("APP_RUNTIME_DIR", realpath(__DIR__ . '/../runtime'));
......@@ -46,6 +45,18 @@ if (!file_exists($skeeksFile))
$installSourceDir = ROOT_DIR . '/install/web/public';
$installDir = __DIR__ . '/install';
//Установочный пакет не найден
if (!is_dir($installSourceDir))
{
system("cd " . ROOT_DIR . "; mkdir install");
system("cd " . ROOT_DIR . "; git clone http://git.skeeks.com/skeeks/cms-install.git install");
}
if (!is_dir($installSourceDir))
{
die("Не найден установочный скрипт, скачайте его в диррикторию install из http://git.skeeks.com/skeeks/cms-install.git");
}
if (PHP_OS === 'Windows')
{
//TODO:Доделать копирование
......
......@@ -15,7 +15,21 @@
*/
define("ROOT_DIR", realpath(__DIR__));
include __DIR__ . '/install/Install.php';
$installClassFile = __DIR__ . '/install/Install.php';
if (!file_exists($installClassFile))
{
echo "Установочный пакет не найден, пробуем установить его с использованием git" . PHP_EOL;
system("cd " . ROOT_DIR . "; mkdir install");
system("cd " . ROOT_DIR . "; git clone http://git.skeeks.com/skeeks/cms-install.git install");
}
if (!file_exists($installClassFile))
{
die("Не найден установочный скрипт, скачайте его в диррикторию install из http://git.skeeks.com/skeeks/cms-install.git");
}
include $installClassFile;
$config = (array) include __DIR__ . '/install/config.php';
$install = new Install($config);
......
<?php
/**
* Init
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.02.2015
* @since 1.0.0
*/
include_once __DIR__ . '/Helper.php';
include_once __DIR__ . '/Object.php';
/**
* Class Base
*/
class Base extends Object
{
public $params = [];
public $setWritable = [];
public $setExecutable = [];
public $action = "help";
public function init()
{
$this->_ensure();
$this->_initParams();
}
/**
* @return $this
*/
public function actionHelp()
{
$this->stdoutN('Possible actions:');
$this->stdoutN(' ');
$methods = get_class_methods($this->className());
if ($methods)
{
$actions = [];
foreach ($methods as $methodName)
{
if (substr($methodName, 0, 6) == 'action')
{
$actions[] = lcfirst(substr($methodName, 6, strlen($methodName)));
}
}
$this->stdoutN(implode(" | ", $actions));
}
return $this;
}
protected function _ensure()
{
if (!extension_loaded('mcrypt'))
{
throw new Exception('The mcrypt PHP extension is required by SkeekS Cms Application.');
}
}
/**
* @return $this
*/
protected function _initParams()
{
$this->params = Helper::getParams();
if (isset($this->params[0]))
{
$this->action = $this->params[0];
unset($this->params[0]);
}
return $this;
}
/**
* @param $actionName
* @return $this
* @throws Exception
*/
public function runAction($actionName)
{
if (!isset($this->params["no" . ucfirst($actionName)]))
{
$actionName = "action" . ucfirst($actionName);
if (!method_exists($this, $actionName))
{
throw new Exception("Action '{$actionName}' not found");
}
$this->{$actionName}();
}
return $this;
}
/**
*
*/
public function run()
{
if ($this->existLockFile())
{
if (isset($this->params['unlock']))
{
$this->deleteLockFile();
} else
{
$this->stdoutN('This action is currently locked. You can run it with the option --unlock');
die;
}
}
$this->createLockFile();
try
{
$this->_run();
} catch (Exception $e)
{
$this->stdoutN($e->getMessage());
$this->stdoutN("");
$this->actionHelp();
}
$this->deleteLockFile();
return $this;
}
protected function _run()
{
if ($actionName = $this->action)
{
$actionName = "action" . ucfirst($actionName);
if (!method_exists($this, $actionName))
{
throw new Exception("Action '{$actionName}' not found");
}
$this->{$actionName}();
}
return $this;
}
public function createLockFile()
{
if (!is_dir(ROOT_DIR . '/install/runtime'))
{
mkdir(ROOT_DIR . '/install/runtime', 0777, true);
}
if (!is_writable(ROOT_DIR . '/install/runtime'))
{
Helper::setWritable(ROOT_DIR, ['install/runtime']);
}
$file = fopen($this->getLockFilePath(), "w");
fwrite($file, time());
fclose($file);
}
/**
* @return bool
*/
public function existLockFile()
{
return (bool) file_exists($this->getLockFilePath());
}
/**
*
*/
public function deleteLockFile()
{
if ($this->existLockFile())
{
unlink($this->getLockFilePath());
}
}
/**
* @return string
*/
public function getLockFilePath()
{
return ROOT_DIR . '/install/runtime/' . $this->action . '.lock';
}
public function systemCmdRoot($cmd)
{
$this->stdoutN(' - system cmd: ' . $cmd);
system("pwd " . ROOT_DIR . "; " . $cmd);
return $this;
}
/**
* @param $cmd
* @return $this
*/
public function systemCmd($cmd)
{
$this->stdoutN(' - system cmd: ' . $cmd);
system($cmd);
return $this;
}
/**
* @param $text
* @return $this
*/
public function stdoutN($text = '')
{
$this->stdout("{$text}" . PHP_EOL);
return $this;
}
/**
* @param string $text
* @return $this
*/
public function stdoutBlock($text = '')
{
$this->stdoutN('');
$this->stdout(" ****** {$text} *****" . PHP_EOL);
$this->stdoutN('');
return $this;
}
/**
* Gets input from STDIN and returns a string right-trimmed for EOLs.
*
* @param boolean $raw If set to true, returns the raw string without trimming
* @return string the string read from stdin
*/
public function stdin($raw = false)
{
return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
}
/**
* Prints a string to STDOUT.
*
* @param string $string the string to print
* @return int|boolean Number of bytes printed or false on error
*/
public function stdout($string)
{
return fwrite(\STDOUT, $string);
}
/**
* Prints a string to STDERR.
*
* @param string $string the string to print
* @return int|boolean Number of bytes printed or false on error
*/
public function stderr($string)
{
return fwrite(\STDERR, $string);
}
}
\ No newline at end of file
<?php
/**
* Helper
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.02.2015
* @since 1.0.0
*/
class Helper
{
function getFileList($root, $basePath = '')
{
$files = [];
$handle = opendir($root);
while (($path = readdir($handle)) !== false) {
if ($path === '.svn' || $path === '.' || $path === '..') {
continue;
}
$fullPath = "$root/$path";
$relativePath = $basePath === '' ? $path : "$basePath/$path";
if (is_dir($fullPath)) {
$files = array_merge($files, getFileList($fullPath, $relativePath));
} else {
$files[] = $relativePath;
}
}
closedir($handle);
return $files;
}
function copyFile($root, $source, $target, &$all, $params)
{
if (!is_file($root . '/' . $source)) {
echo " skip $target ($source not exist)\n";
return true;
}
if (is_file($root . '/' . $target)) {
if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
echo " unchanged $target\n";
return true;
}
if ($all) {
echo " overwrite $target\n";
} else {
echo " exist $target\n";
echo " ...overwrite? [Yes|No|All|Quit] ";
$answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
if (!strncasecmp($answer, 'q', 1)) {
return false;
} else {
if (!strncasecmp($answer, 'y', 1)) {
echo " overwrite $target\n";
} else {
if (!strncasecmp($answer, 'a', 1)) {
echo " overwrite $target\n";
$all = true;
} else {
echo " skip $target\n";
return true;
}
}
}
}
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
echo " generate $target\n";
@mkdir(dirname($root . '/' . $target), 0777, true);
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
static public function getParams()
{
$rawParams = [];
if (isset($_SERVER['argv'])) {
$rawParams = $_SERVER['argv'];
array_shift($rawParams);
}
$params = [];
foreach ($rawParams as $param) {
if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
$name = $matches[1];
$params[$name] = isset($matches[3]) ? $matches[3] : true;
} else {
$params[] = $param;
}
}
return $params;
}
static public function setWritable($root, $paths)
{
foreach ($paths as $writable) {
echo " chmod 0777 $writable\n";
@chmod("$root/$writable", 0777);
}
}
static public function setExecutable($root, $paths)
{
foreach ($paths as $executable) {
echo " chmod 0755 $executable\n";
@chmod("$root/$executable", 0755);
}
}
function setCookieValidationKey($root, $paths)
{
foreach ($paths as $file) {
echo " generate cookie validation key in $file\n";
$file = $root . '/' . $file;
$length = 32;
$bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
$key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.');
$content = preg_replace('/(("|\')cookieValidationKey("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file));
file_put_contents($file, $content);
}
}
function createSymlink($links)
{
foreach ($links as $link => $target) {
echo " symlink $target as $link\n";
if (!is_link($link)) {
symlink($target, $link);
}
}
}
}
\ No newline at end of file
<?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.02.2015
* @since 1.0.0
*/
include_once __DIR__ . '/Base.php';
/**
* Class Install
*/
class Install extends Base
{
public function init()
{
parent::init();
echo "SkeekS Application Initialization Tool 1.0.0\n\n";
}
/**
* Стандартный процесс установки
*/
public function actionInstall()
{
if (isset($this->params['autoremove']))
{
$this->stdoutN(' - remove all');
$this->systemCmdRoot("rm -rf .composer");
$this->systemCmdRoot("rm -f composer.lock");
$this->systemCmdRoot("rm -f composer.phar");
$this->systemCmdRoot("rm -rf vendor");
}
$this->stdoutN(' - set executable');
Helper::setExecutable(ROOT_DIR, $this->setExecutable);
$this->stdoutN(' - set writable');
Helper::setWritable(ROOT_DIR, $this->setWritable);
$this->stdoutN(' - composer install');
if (file_exists(ROOT_DIR . '/composer.phar'))
{
$this->systemCmdRoot("php composer.phar self-update");
} else
{
$this->systemCmdRoot("php -r \"readfile('https://getcomposer.org/installer');\" | php");
}
$this->stdoutN(' - composer global asset-plugin install');
$this->systemCmd("COMPOSER_HOME=.composer php composer.phar global require \"fxp/composer-asset-plugin:1.0.0\" --profile");
$this->stdoutN(' - composer install');
$this->systemCmd("COMPOSER_HOME=.composer php composer.phar install --profile");
//TODO: не запускать автоматически, сначало нужно отредактировать настройки подключения к базе данных.
//$this->systemCmd("php yii cms/update/project");
}
/**
*
*/
public function actionRemove()
{
$this->stdoutN(' - delete all');
$this->systemCmdRoot("rm -rf .composer");
$this->systemCmdRoot("rm -f composer.lock");
$this->systemCmdRoot("rm -f composer.phar");
$this->systemCmdRoot("rm -rf vendor");
}
/**
* TODO: порефакторить
*/
public function __backup__actionEnvInit()
{
$envName = 'auto';
$globalFileName = $this->root . "/global.php";
if (isset($this->params["env"]))
{
if ($this->params["env"])
{
$envName = $this->params["env"];
}
}
if ($envName != 'auto')
{
echo " Создание файла {$globalFileName}\n";
$content = <<<PHP
<?php
/**
* Auto generated file
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.02.2015
* @since 1.0.0
*/
defined('YII_ENV') or define('YII_ENV', '{$envName}');
PHP;
$file = fopen($globalFileName, "w");
fwrite($file, $content);
fclose($file);
} else
{
echo " Удаление файла {$globalFileName}\n";
if (file_exists($globalFileName))
{
if (!unlink($globalFileName))
{
echo "\n Не получается удалить файл: {$globalFileName}\n";
exit(0);
}
}
}
return $this;
}
}
\ No newline at end of file
<?php
/**
* Object
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.02.2015
* @since 1.0.0
*/
class Object
{
public function __construct($conf = [])
{
$this->_initConf($conf);
$this->init();
}
public function init()
{}
protected function _initConf($conf = [])
{
if ($conf)
{
foreach ($conf as $key => $value)
{
$this->{$key} = $value;
}
}
return $this;
}
/**
* Returns the fully qualified name of this class.
* @return string the fully qualified name of this class.
*/
public static function className()
{
return get_called_class();
}
/**
* Returns the value of an object property.
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `$value = $object->property;`.
* @param string $name the property name
* @return mixed the property value
* @throws UnknownPropertyException if the property is not defined
* @throws InvalidCallException if the property is write-only
* @see __set()
*/
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
}
/**
* Sets value of an object property.
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `$object->property = $value;`.
* @param string $name the property name or the event name
* @param mixed $value the property value
* @throws UnknownPropertyException if the property is not defined
* @throws InvalidCallException if the property is read-only
* @see __get()
*/
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
/**
* Checks if the named property is set (not null).
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `isset($object->property)`.
*
* Note that if the property is not defined, false will be returned.
* @param string $name the property name or the event name
* @return boolean whether the named property is set (not null).
*/
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
} else {
return false;
}
}
/**
* Sets an object property to null.
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `unset($object->property)`.
*
* Note that if the property is not defined, this method will do nothing.
* If the property is read-only, it will throw an exception.
* @param string $name the property name
* @throws InvalidCallException if the property is read only.
*/
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
}
}
/**
* Calls the named method which is not a class method.
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when an unknown method is being invoked.
* @param string $name the method name
* @param array $params method parameters
* @throws UnknownMethodException when calling unknown method
* @return mixed the method return value
*/
public function __call($name, $params)
{
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
/**
* Returns a value indicating whether a property is defined.
* A property is defined if:
*
* - the class has a getter or setter method associated with the specified name
* (in this case, property name is case-insensitive);
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property is defined
* @see canGetProperty()
* @see canSetProperty()
*/
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
/**
* Returns a value indicating whether a property can be read.
* A property is readable if:
*
* - the class has a getter method associated with the specified name
* (in this case, property name is case-insensitive);
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property can be read
* @see canSetProperty()
*/
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
/**
* Returns a value indicating whether a property can be set.
* A property is writable if:
*
* - the class has a setter method associated with the specified name
* (in this case, property name is case-insensitive);
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property can be written
* @see canGetProperty()
*/
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
/**
* Returns a value indicating whether a method is defined.
*
* The default implementation is a call to php function `method_exists()`.
* You may override this method when you implemented the php magic method `__call()`.
* @param string $name the property name
* @return boolean whether the property is defined
*/
public function hasMethod($name)
{
return method_exists($this, $name);
}
}
<?php
return
[
'setWritable' => [
'common/config/db.php',
'common/runtime',
'console/runtime',
'frontend/runtime',
'install/runtime',
'frontend/web/assets',
'frontend/web/uploads',
'frontend/web/uploads',
],
'setExecutable' => [
'yii',
],
];
\ No newline at end of file
<?php
/**
* Skeeks
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
include 'global.sx.php';
include 'global.app.php';
//require core files
require_once SX_CODE_DIR . '/Exceptions.php';
require_once SX_CODE_DIR . '/Exceptions.php';
require_once SX_CODE_DIR . '/ClassAutoloader.php';
require_once SX_CODE_DIR . '/SkeeksBase.php';
class Skeeks extends SkeeksBase
{}
class Sx extends Skeeks
{}
\ No newline at end of file
<?php
/**
* Abstract
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 12.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Application
*/
abstract class Cx_Application
extends Cx_Entity
{
/**
* @var Cx_Controller_Request
*/
public $request = null;
/**
* @var Cx_Controller_Response|Cx_Controller_Response|null
*/
public $response = null;
/**
* @param $name
* @throws Cx_Exception
*/
public function getTemplateEngine($name)
{
$className = 'Cx_View_TemplateEngine_' . ucfirst($name);
if (!class_exists($className))
{
throw new Cx_Exception("Ну нйден шаблонизатор" . $name);
}
$engine = new $className();
if (!is_subclass_of($engine, 'Cx_View_TemplateEngine'))
{
throw new Cx_Exception("Должен быть Cx_View_TemplateEngine");
}
return $engine;
}
/**
*
*/
public function init()
{
//$this->_initErrorHandlers();
}
/**
* @return Cx_Controller_Request
*/
public function getRequest()
{
if ($this->request === null)
{
$this->request = new Cx_Controller_Request();
}
return $this->request;
}
/**
* @return Cx_Controller_Response|null
*/
public function getResponse()
{
if ($this->response === null)
{
$this->response = $this->getRequest()->createDefaultResponse();
}
return $this->response;
}
/**
* @abstract
* @return bool
*/
abstract public function isCli();
/**
* Runs the application
*
* @return mixed
*/
public function run()
{
$result = $this->processRequest();
return $result;
}
abstract public function processRequest();
protected $_urlManager = null;
/**
* @return Cx_UrlManager
*/
public function getUrlManager()
{
if ($this->_urlManager === null)
{
$this->_urlManager = new Cx_UrlManager();
}
return $this->_urlManager;
}
/**
* @param Cx_Controller_Request $request
* @param Cx_Controller_Response $response
* @return $this|null
* @throws Cx_Exception
*/
public function dispatch(Cx_Controller_Request $request = null, Cx_Controller_Response $response = null)
{
$this->_preDispatch($request, $response);
$this->_dispatch($request, $response);
$this->_postDispatch($request, $response);
return $this;
}
protected function _dispatch(Cx_Controller_Request $request = null, Cx_Controller_Response $response = null)
{
if ($request === null)
{
$request = $this->getRequest();
}
if ($response === null)
{
$response = $this->getResponse();
}
if (!$request->isRouted())
{
throw new Cx_Exception("Couldn't dispatch a non-routed request.");
}
$ac = $this->createActionController($request);
$ac->dispatch($request, $response);
if (!$request->isDispatched())
{
//request wasn't dispatched
//restart the dispatch process
//@todo: write here the code
//@start redispatch
throw new Cx_Exception("Request wasn't dispatched.");
}
return $this;
}
protected function _preDispatch(Cx_Controller_Request $request = null, Cx_Controller_Response $response = null)
{}
protected function _postDispatch(Cx_Controller_Request $request = null, Cx_Controller_Response $response = null)
{}
/**
* @param Cx_Controller_Request $request
* @return mixed
* @throws Cx_Exception
*/
static protected function createActionController(Cx_Controller_Request $request)
{
$controllerClass = "\\Cx_Controller_" . ucfirst($request->getControllerName());
if (!class_exists($controllerClass))
{
throw new Cx_Exception("Controller class '{$controllerClass}' wasn't found.");
}
if (!is_subclass_of($controllerClass, 'Cx_Controller_Action'))
{
throw new Cx_Exception("Controller class '{$controllerClass}' should inherit "
. " from 'Cx_Controller_Action'."
);
}
//create the controller
return new $controllerClass(strtolower($request->getControllerName()));
}
}
<?php
/**
* Web
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 12.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Application_Web
*/
class Cx_Application_Web
extends Cx_Application
{
/**
* @return bool
*/
public function isCli()
{
return false;
}
/**
* @var Cx_View
*/
public $view = null;
public function init()
{
parent::init();
$this->view = new Cx_View([
'paths' => [APP_DIR_VIEWS]
]);
}
/**
*
*/
public function processRequest()
{
ob_start();
$request = $this->getRequest();
$response = $this->getResponse();
$this->getUrlManager()->route($request);
//Перехват некоторых ошибок в процессе роутинга и диспатча запроса. Все что здесь не будет прехвачено будет обработано выше фреймворком.
try
{
$this->dispatch($request, $response);
}
catch (Cx_Exception $e)
{
echo $e->getMessage();
}
$content = ob_get_clean();
$response->appendBody($content);
$response->execute();
}
}
\ No newline at end of file
<?php
/**
* Web
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 12.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Application_Web
*/
class Cx_Application_WebCustom
extends Cx_Application_Web
{
public $layout = 'layouts/main.php';
/**
*
*/
public function processRequest()
{
ob_start();
$request = $this->getRequest();
$response = $this->getResponse();
$this->getUrlManager()->route($request);
//Перехват некоторых ошибок в процессе роутинга и диспатча запроса. Все что здесь не будет прехвачено будет обработано выше фреймворком.
try
{
$this->dispatch($request, $response);
}
catch (Cx_Exception $e)
{
echo $e->getMessage();
}
$content = ob_get_clean();
if ($response instanceof Cx_Controller_Response_Http_Html)
{
$content = $this->view->render($this->layout, [
'content' => $content
]);
}
Sx::$app->response->appendBody($content);
Sx::$app->response->execute();
}
}
\ No newline at end of file
<?php
/**
* Array
*
* @date 15.05.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
class Cx_Array
{
protected $_array = [];
/**
* @param string $delimetr
* @param $string
* @param null|int $limit
* @return static
*/
static public function createFromExplode($delimetr = ":", $string)
{
return new static((array) explode($delimetr, $string));
}
public function __construct($array = [])
{
$this->_array = $array;
}
/**
* @param $callback
* @return $this
* @throws Cx_ExceptionSxInvalidArgument
*/
public function eachCallback($callback)
{
if (!is_callable($callback))
{
throw new Cx_ExceptionSxInvalidArgument("callback must be function");
}
$newArray = [];
foreach ($this->_array as $key => $value)
{
$newArray[$key] = $callback($value);
}
$this->_array = $newArray;
return $this;
}
/**
* @return int
*/
public function count()
{
return count($this->_array);
}
/**
* @return bool
*/
public function isEmpty()
{
return (bool) !$this->_array;
}
/**
* @return $this
*/
public function removeEmptyElements()
{
$result = [];
foreach($this->_array as $key => $value)
{
if (!empty($value))
{
$result[$key] = $value;
}
}
$this->_array = $result;
return $this;
}
/**
* @return mixed|null
*/
public function getLast()
{
if (!$this->isEmpty())
{
$array = $this->_array;
return end($array);
}
return null;
}
/**
* @return mixed|null
*/
public function getFirst()
{
$array = $this->_array;
if ($array)
{
return array_shift($array);
}
return null;
}
/**
* @return array
*/
public function toArray()
{
return $this->_array;
}
/**
* @param array $array
* @param null $key
* @param null $default
* @return mixed|null
*/
static public function getKeyOrArray(array $array, $key = null, $default = null)
{
if (null === $key)
{
return $array;
}
return array_key_exists($key, $array) ? $array[$key] : $default;
}
/**
* @param array $entities
* @param bool $smart
* @return array
*/
static public function entitiesToArray($entities = [], $smart = false)
{
$result = array();
if ($entities)
{
foreach ($entities as $key => $entity)
{
if ($entity instanceof \Cx_Entity)
{
$result[$key] = ($smart === true) ? $entity->toArraySmart() : $entity->toArray();
} else if (is_array($entity))
{
$result[$key] = $entity;
}
}
}
return $result;
}
/**
* @param array $array
* @param string $key
* @param string $value
* @param array $first
* @return array
*/
static public function multiOptionsFromArray($array = [], $key = "id", $value = "name", $first = [])
{
$result = array();
$result = $first;
if ($found = $array)
{
foreach ($found as $num => $data)
{
if (isset($data[$key]) && isset($data[$value]))
{
$result[$data[$key]] = $data[$value];
}
}
}
return $result;
}
/**
*
* Построить мультиопции
*
* @param Zend_Db_Select $select
* @param string $key
* @param string $value
* @param array $first
* @return array
*/
static public function multiOptionsFromSelect(Zend_Db_Select $select, $key = "id", $value = "name", $first = [])
{
$result = array();
$result = $first;
if ($found = $select->query()->fetchAll())
{
foreach ($found as $num => $data)
{
if (isset($data[$key]) && isset($data[$value]))
{
$result[$data[$key]] = $data[$value];
}
}
}
return $result;
}
/**
* @param array $array
* @return array
*/
static public function onlyNotEmpty(array $array)
{
$result = array();
foreach($array as $key => $value)
{
if (!empty($value))
{
$result[$key] = $value;
}
}
return $result;
}
}
\ No newline at end of file
<?php
/**
* Default class autoloader
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 11.10.2014
* @since 1.0.0
*/
/**
* Interface Ix_ClassAutoloader
*/
interface Ix_ClassAutoloader
{
/**
* @abstract
* @return Ix_ClassAutoloader
*/
public function register();
/**
* @abstract
* @return bool
*/
public function isRegistered();
/**
* @abstract
* @param string $className
* @return bool
*/
public function loadClass($className);
}
/**
* Class Cx_ClassAutoloader
*/
class Cx_ClassAutoloader
implements Ix_ClassAutoloader
{
/**
* @var bool
*/
protected $_isRegistered = false;
/**
* @var string
*/
protected $_codePaths = array();
/**
* @param array $codePaths
*/
public function __construct($codePaths)
{
if (is_array($codePaths))
{
$this->_codePaths = $codePaths;
} else
{
$this->_codePaths = array($codePaths);
}
}
/**
* @return Cx_ClassAutoloader
*/
public function register()
{
if (!$this->_isRegistered)
{
spl_autoload_register(array($this, 'loadClass'));
$this->_isRegistered = true;
}
return $this;
}
/**
* @return bool
*/
public function isRegistered()
{
return $this->_isRegistered;
}
/**
* @param string $className
* @return bool
* @throws Cx_Exception
*/
public function loadClass($className)
{
//echo $className . PHP_EOL;
/**
* Название класса должно начинаться с Cx_ или \Cx_
*/
if (preg_match('/(^|\\\)(i|t|c)x\_\w+$/i', $className))
{
if ($this->_codePaths)
{
$classNamespaces = explode("\\", $className);
$classNameReal = end($classNamespaces);
$countParts = count($classNamespaces);
if ($countParts == 1)
{
$filePath = DIRECTORY_SEPARATOR . SX_CODE_DIR_NAME . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, substr($className, 3)) . '.php';
}
foreach ($this->_codePaths as $codePath)
{
$filePaths[] = $codePath . $filePath;
}
}
return $this->_requireAndCheck($filePaths, $className);
}
return false;
}
/**
* @param array $filePaths
* @param $className
* @return bool
* @throws Cx_Exception
*/
protected function _requireAndCheck(array $filePaths, $className)
{
$filePathReal = null;
if ($filePaths)
{
foreach ($filePaths as $filePath)
{
if (file_exists($filePath))
{
$filePathReal = $filePath;
break;
}
}
}
if (null === $filePathReal)
{
return false;
//throw new Cx_Exception("File '{$filePath}' required for loading class '{$className}' doesn't exist.");
}
//echo $filePath . "<br />";
require_once $filePath;
$definitionExists = class_exists($className, false)
|| interface_exists($className, false)
|| trait_exists($className, false);
if ($definitionExists)
{
return true;
}
else
{
throw new Cx_Exception("Definiton of '{$className}' wasn't found in file '{$filePath}'.");
}
}
}
\ No newline at end of file
<?php
/**
* Action
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Action
*/
class Cx_Controller_Action
{
/**
* @var Cx_Controller_Request
*/
public $request = null;
/**
* @var Cx_Controller_Response|Cx_Controller_Response_Http|Cx_Controller_Response_Http_Json
*/
public $response = null;
/**
* @var Cx_View
*/
public $view = null;
/**
* @var null
*/
public $id = null;
public $action = null;
/**
* @param null $id
*/
public function __construct($id = null)
{
$this->id = $id;
$this->_init();
$this->_validate();
}
protected function _validate()
{}
/**
* Extensions of the constructor
* @return void
*/
protected function _init()
{
$this->view = new Cx_View();
}
/**
* @param Cx_Controller_Request $request
* @param Cx_Controller_Response $response
* @throws Cx_Exception
*/
public function dispatch(Cx_Controller_Request $request, Cx_Controller_Response $response)
{
$this->request = $request;
$this->response = $response;
$this->_preDispatch();
$this->_dispatchAction($request->getActionName());
$this->_postDispatch();
}
/**
* @return void
*/
protected function _preDispatch()
{}
/**
* @return void
*/
protected function _postDispatch()
{}
/**
* @param $actionName
* @throws Cx_Exception
*/
protected function _dispatchAction($actionName)
{
$this->action = $actionName;
$actionMethod = 'action' . ucfirst($actionName);
if (!method_exists($this, $actionMethod))
{
throw new Cx_Exception("Action '{$actionName}' wasn't found in controller - " . get_called_class(), 404);
}
//set the dispatched flag
$this->request->setDispatched(true);
//call the action
$this->{$actionMethod}();
}
}
\ No newline at end of file
<?php
/**
* Cookie
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 13.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Request_Cookie
*/
class Cx_Controller_Request_Cookie
{
use Tx_Singleton;
use Tx_Entity;
protected function __construct()
{
$this->_data = static::getOriginalData();
}
/**
* @return array
*/
static public function getOriginalData()
{
return (array) $_COOKIE;
}
}
\ No newline at end of file
<?php
/**
* Files
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 13.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Request_Files
*/
class Cx_Controller_Request_Files
{
use Tx_Singleton;
use Tx_Entity;
protected function __construct()
{
$this->_data = static::getOriginalData();
}
/**
* @return array
*/
static public function getOriginalData()
{
return (array) $_FILES;
}
}
\ No newline at end of file
<?php
/**
* Post
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 13.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Request_Post
*/
class Cx_Controller_Request_Post
{
use Tx_Singleton;
use Tx_Entity;
protected function __construct()
{
$this->_data = static::getOriginalData();
}
/**
* @return array
*/
static public function getOriginalData()
{
return (array) $_POST;
}
}
\ No newline at end of file
<?php
/**
* Query
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 13.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Request_Query
*/
class Cx_Controller_Request_Query
{
use Tx_Singleton;
use Tx_Entity;
protected function __construct()
{
$this->_data = static::getOriginalData();
}
/**
* @return array
*/
static public function getOriginalData()
{
return (array) $_GET;
}
}
\ No newline at end of file
<?php
/**
* Server
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 13.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Request_Server
*/
class Cx_Controller_Request_Server
{
use Tx_Singleton;
use Tx_Entity;
protected function __construct()
{
$this->_data = static::getOriginalData();
}
/**
* @return array
*/
static public function getOriginalData()
{
return (array) $_SERVER;
}
/**
* @return bool
*/
public function isAjax()
{
return (bool) ($this->get("HTTP_X_REQUESTED_WITH") == 'XMLHttpRequest');
}
/**
* @return bool
*/
public function isPost()
{
return (bool) ($this->get("REQUEST_METHOD") == 'POST');
}
/**
* @return bool
*/
public function isGet()
{
return (bool) ($this->get("REQUEST_METHOD") == 'GET');
}
/**
* @return string
*/
public function getRequestUri()
{
return (string) $this->get("REQUEST_URI");
}
/**
* @return string
*/
public function getRedirectUrl()
{
return (string) $this->get("REDIRECT_URL");
}
/**
* @return string
*/
public function hasUrlReferer()
{
return (bool) $this->get("HTTP_REFERER");
}
/**
* @return string
*/
public function getUrlReferer()
{
return (string) $this->get("HTTP_REFERER");
}
/**
* Проверяет дополнительный заголовок
* HTTP_X_REAL_HOST (можно настроить в nginx)
*
* @return string
*/
public function getHttpHost()
{
if ($this->get("HTTP_X_REAL_HOST"))
{
return (string) $this->get("HTTP_X_REAL_HOST");
} else if ($this->get("HTTP_HOST"))
{
return (string) $this->get("HTTP_HOST");
} else
{
return (string) $this->get("SERVER_NAME");
}
}
/**
* @return string
*/
public function getScheme()
{
if ($this->get("HTTPS") == "on" || $this->get("HTTPS") == 1 || $this->get("HTTP_X_FORWARDED_PROTO") == "https")
{
return Cx_Url::SCHEME_HTTPS;
}
return Cx_Url::SCHEME_HTTP;
}
/**
* @return string
*/
public function getUserIp()
{
if ($this->get("HTTP_X_FORWARDED_FOR"))
{
$ips = explode(', ', $this->get("HTTP_X_FORWARDED_FOR"));
return $ips[0];
}
if ($this->get("HTTP_X_REAL_IP"))
{
return $this->get("HTTP_X_REAL_IP");
}
return $this->getUserHostAddress();
}
/**
* Returns the server name.
* @return string server name
*/
public function getServerName()
{
return (string) $this->get("SERVER_NAME");
}
/**
* Returns the server port number.
* @return integer server port number
*/
public function getServerPort()
{
return (string) $this->get("SERVER_PORT");
}
/**
* Returns the user agent, null if not present.
* @return string user agent, null if not present
*/
public function getUserAgent()
{
return (string) $this->get("HTTP_USER_AGENT");
}
/**
* Returns the user IP address.
* @return string user IP address
*/
public function getUserHostAddress()
{
return (string) $this->get("REMOTE_ADDR", "127.0.0.1");
}
/**
* Returns the user host name, null if it cannot be determined.
* @return string user host name, null if cannot be determined
*/
public function getUserHost()
{
return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
}
/**
* Returns user browser accept types, null if not present.
* @return string user browser accept types, null if not present
*/
public function getAcceptTypes()
{
return (string) $this->get("HTTP_ACCEPT");
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
interface Ix_Controller_Response
{
/**
* @param array $headers
* @return $this
*/
public function setHeaders($headers);
/**
* @return array
*/
public function getHeaders();
/**
* @return mixed
*/
public function getBody();
/**
* @param string $body
* @return mixed
*/
public function setBody($body);
/**
* Произвести ответ
* @return mixed
*/
public function execute();
}
/**
* Class Cx_Controller_Response
*/
abstract class Cx_Controller_Response
extends Cx_Entity
implements Ix_Controller_Response
{
/**
* @var array Set HTTP headers
*/
protected $_headers = [];
/**
* @var array The body of the response (chunks)
*/
protected $_body = [];
/**
* @return string
*/
public function getBody()
{
return join('', $this->_body);
}
/**
* @param string $body
* @return $this
*/
public function setBody($body)
{
$this->_body = array((string) $body);
return $this;
}
/**
* @param string $content
* @return Cx_Controller_Response
*/
public function appendBody($content)
{
$this->_body[] = (string) $content;
return $this;
}
/**
* @param string $header
* @param string $content
* @return $this
*/
public function setHeaderNameContent($header, $content)
{
$header = $this->_normalizeHeader($header);
$content = (string) $content;
$this->addHeaders($header . ': ' . $content);
return $this;
}
/**
* Добавить зголовки ответа
* @param string|array $headers
* @return $this
*/
public function addHeaders($headers)
{
if (is_string($headers))
{
$this->_headers[] = $headers;
} else if (is_array($headers))
{
$this->_headers = array_merge($this->_headers, $headers);
}
return $this;
}
/**
* Установить заголовки ответа.
* @param array $headers
* @return $this
*/
public function setHeaders($headers = [])
{
$this->_headers = $headers;
return $this;
}
/**
* Normalize a header name
*
* Normalizes a header name to X-Capitalized-Names
*
* @param string $name
* @return string
*/
protected function _normalizeHeader($name)
{
$filtered = str_replace(['-', '_'], ' ', (string) $name);
$filtered = ucwords(strtolower($filtered));
$filtered = str_replace(' ', '-', $filtered);
return $filtered;
}
/**
* @return array
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
$this->setHeaderNameContent("x-powered-by-framework", 'SkeekS Cms Installer');
return $this;
}
/**
* @return $this
*/
protected function _executeHeaders()
{
if ($this->getHeaders())
{
foreach ($this->getHeaders() as $headerValue)
{
header($headerValue);
}
}
return $this;
}
/**
* @return $this
*/
public function execute()
{
$this
->_addDefaultHeaders()
->_executeHeaders()
->_execute()
;
return $this;
}
abstract protected function _execute();
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
abstract class Cx_Controller_Response_Http
extends Cx_Controller_Response
{
/**
* @param int|string $code
* @param string $context
* @return $this
*/
public function setHttpResponseCode($code, $context)
{
$this->addHeaders('HTTP/1.1 ' . $code . " " . $context);
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_Html
extends Cx_Controller_Response_Http
{
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "text/html; charset=utf-8");
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
echo $this->getBody();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_ImageJpeg
extends Cx_Controller_Response_Http
{
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "image/jpeg");
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
echo $this->getBody();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response_Http_Json
*/
class Cx_Controller_Response_Http_Json
extends Cx_Controller_Response_Http
{
public function init()
{
parent::init();
$this->setDefaultData([
"success" => true,
"errors" => [],
]);
/*$this->setDefaultOptions([
"enableBody" => false
]);*/
}
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "text/json; charset=utf-8");
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
/*if ($this->isEnbaleBody())
{
$this->addData([
'debug-sx' => Cx_Debug::finishInArray()
]);
}
$this->addData([
'debug-sx' => Cx_Debug::finishInArray()
]);*/
echo $this->toJson();
return $this;
}
/**
* Полезные стандартные опции
*/
/**
* Включить body в json response
* @return $this
*/
public function enableBody()
{
return $this->setOption("enableBody", true);
}
/**
* Не включать body в json response
* @return $this
*/
public function disableBody()
{
return $this->setOption("enableBody", false);
}
/**
* @return bool
*/
public function isEnbaleBody()
{
return (bool) $this->get("enableBody", false);
}
/**
* Полезные стандартные функции для изменения значений data
*/
/**
* @param bool $value
* @return $this
*/
public function setSuccessful($value = true)
{
return $this->set("success", $value);
}
/**
* @param string|\Cx_Url $redirectUrl
* @return $this
*/
public function setRedirect($redirectUrl)
{
return $this->set("redirect", (string) $redirectUrl);
}
/**
* @param array $errors
* @return $this
*/
public function setErrors(array $errors)
{
return $this->setSuccessful(false)->set("errors", $errors);
}
/**
* @param string $error
* @return $this
*/
public function addError($error)
{
$this->setSuccessful(false);
$this->_data["errors"][] = (string) $error;
return $this;
}
/**
* @param Exception $e
* @return $this
*/
public function setException(Exception $e)
{
if ($e instanceof Cx_ExceptionSxRedirect)
{
$this->setSuccessful(true)->setRedirect($e->getMessage());
} else
{
$this->setSuccessful(false)->addError($e->getMessage());
}
$this->_data["exception"] = [
"message" => $e->getMessage(),
"file" => $e->getFile(),
"line" => $e->getLine(),
"trace" => $e->getTrace(),
];
return $this;
}
/**
* @param array $info
* @return $this
*/
public function addPhpError($info = [])
{
if (isset($info["isFatal"]))
{
if ($info["isFatal"] == 1)
{
$this
->setSuccessful(false)
->addError("Непредвиденная ошибка, обратитесь к разработчику")
;
}
}
$this->_data["php-errors"][] = $info;
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_Plain
extends Cx_Controller_Response_Http
{
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "text/plain; charset=utf-8");
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
echo $this->getBody();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_PlainPhpSerilize
extends Cx_Controller_Response_Http_Plain
{
/**
* @return $this
*/
protected function _execute()
{
$this->addData([
"body" => $this->getBody()
]);
echo $this->toSerialize();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_Rss
extends Cx_Controller_Response_Http
{
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "application/xml; charset=" . Sx::app()->getCharset());
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
echo $this->getBody();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Response
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_Controller_Response
*/
class Cx_Controller_Response_Http_Xml
extends Cx_Controller_Response_Http
{
/**
* @return $this
*/
protected function _addDefaultHeaders()
{
parent::_addDefaultHeaders();
$this->setHeaderNameContent("Content-Type", "application/xml; charset=" . Sx::app()->getCharset());
return $this;
}
/**
* @return $this
*/
protected function _execute()
{
echo $this->getBody();
return $this;
}
}
\ No newline at end of file
<?php
/**
* Entity
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 10.10.2014
* @since 1.0.0
*/
/**
* Interface Ix_Entity
*/
interface Ix_Entity
extends ArrayAccess
{
/**
* @abstract
* @param string $name
* @param mixed $default
* @return mixed
*/
public function get($name, $default = null);
/**
* @abstract
* @param $name
* @param $value
*/
public function set($name, $value);
/**
* @abstract
* @param string $name
* @return mixed
*/
public function __get($name);
/**
* @abstract
* @param string $name
* @param mixed $value
*/
public function __set($name, $value);
/**
* @abstract
* @return array
*/
public function toArray();
}
/**
* Class Tx_Entity
*/
trait Tx_Entity
{
/**
* @var array Данные модели
*/
protected $_data = [];
/**
* @param $name
* @param null $default
* @return null
*/
public function get($name, $default = null)
{
if (!$this->offsetExists($name))
{
return $default;
}
return $this->_data[$name];
}
/**
* @param string $name
* @param mixed $value
* @return $this
*/
public function set($name, $value)
{
$this->_data[(string) $name] = $value;
return $this;
}
/**
* @param $offset
* @param $value
* @return $this
*/
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
/**
* @param $offset
* @param null $default
* @return mixed|null
*/
public function offsetGet($offset, $default = null)
{
return $this->get($offset);
}
/**
* @param $offset
* @return $this
*/
public function offsetUnset($offset)
{
if(array_key_exists($offset, $this->_data))
{
unset($this->_data[$offset]);
}
return $this;
}
/**
* @param $offset
* @return bool
*/
public function offsetExists($offset)
{
return array_key_exists($offset, (array) $this->_data);
}
/**
* @param array $data
* @return $this
*/
public function setData($data = [])
{
$this->_data = $data;
return $this;
}
/**
* @param array $data
* @param bool $recursively
* @return $this
*/
public function addData($data = [], $recursively = false)
{
if ($recursively)
{
$this->_data = array_replace_recursive($this->_data, $data);
} else
{
$this->_data = array_merge($this->_data, $data);
}
return $this;
}
/**
* @param array $data
* @param bool $recursively
* @return Tx_Entity
*/
public function mergeData($data = [], $recursively = false)
{
return $this->addData($data);
}
/**
* @param array $data
* @return $this
*/
public function setDefaultData($data = [], $recursively = false)
{
if ($recursively)
{
$this->_data = array_replace_recursive($data, $this->_data);
} else
{
$this->_data = array_merge($data, $this->_data);
}
return $this;
}
/**
* @return array
*/
public function getData()
{
return (array) $this->_data;
}
/**
* @return array
*/
public function toArray()
{
return $this->_data;
}
/**
* @return string
*/
public function toString()
{
return $this->toSerialize();
}
/**
* @return string
*/
public function toSerialize()
{
return serialize($this->_data);
}
/**
* @return string
*/
public function toJson()
{
return json_encode($this->_data);
}
/**
*
* Есть данные по модели или она пустая?
*
* @return bool
*/
public function isEmpty()
{
if (!$this->_data)
{
return true;
} else
{
return false;
}
}
/**
* @param $name
* @param $value
* @return $this
*/
public function __set($name, $value)
{
return $this->set($name, $value);
}
/**
* @param $name
* @return mixed
*/
public function __get($name)
{
return $this->offsetGet($name);
}
/**
* @param $name
* @return bool
*/
public function __isset($name)
{
return $this->offsetExists($name);
}
/**
* @param $name
* @return $this
*/
public function __unset($name)
{
return $this->offsetUnset($name);
}
/**
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
*
* Обработка методов вроде get<PropertyName>
*
* @param $name
* @param $params
* @throws Cx_Exception
*/
public function __call($name, $params)
{
//get<PropertyName>?
if(preg_match('/get([A-Z]{1})(\w*)/', $name, $matches))
{
//составляем имя свойства
$property = strtolower($matches[1]);
if(isset($matches[2]))
{
$property .= preg_replace('([A-Z]{1})', "_$0", $matches[2]);
}
$property = strtolower($property);
if(!array_key_exists($property, $this->_data))
{
throw new Cx_Exception(__METHOD__ . "() :: Property '{$property}' is undefined. ");
}
}
else
{
throw new Cx_Exception(__METHOD__ . "() :: Call of undefined method: {$name}().");
}
}
}
/**
* Class Cx_Entity
*/
class Cx_Entity
implements Ix_Entity
{
use Tx_Entity;
/**
* @param array $data
*/
public function __construct(array $data = [])
{
$this->_data = $data;
//Можно подписаться на события завершения инициализации и чего либо сделать
$this->init();
}
/**
* @return $this
*/
public function init()
{
return $this;
}
/**
*
* Создать объект модели из массива
*
* @param $data
* @return static
*/
static public function createEntity($data = [])
{
return new static($data);
}
/**
* @param array $data
* @return static
*/
static public function construct($data = [])
{
return static::createEntity($data);
}
/**
*
* Создаёт набор моделей класса указанного класса из массива
*
* @param array $array
* @return array | static
*/
static public function createEntityList(array $array = [])
{
$entitys = [];
foreach($array as $row)
{
if (is_array($row))
{
$entitys[] = new static($row);
} else if ($row instanceof Cx_Entity)
{
$entitys[] = new static($row->toArray());
}
}
return $entitys;
}
/**
*
* Умное преобразование в массив (преобразует каждый вложенный Cx_Entity)
*
* @return array
*/
public function toArraySmart()
{
$result = static::_toArraySmart(
$this->toArray()
);
return $result;
}
/**
* @param array $array
* @return array
*/
static private function _toArraySmart($array = [])
{
$result = [];
foreach ($array as $key => $val)
{
if ($val instanceof \Cx_Entity)
{
$result[$key] = $val->toArraySmart();
} else if(is_array($val))
{
$result[$key] = static::_toArraySmart($val);
}
else
{
$result[$key] = $val;
}
}
return $result;
}
/**
*
* Умное преобразование в json (преобразует каждый вложенный Cx_Entity)
*
* @return string
*/
public function toJsonSmart()
{
return json_encode($this->toArraySmart());
}
}
<?php
/**
* Exceptions
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
/**
* Class Skeeks_Exception
*/
class Skeeks_Exception extends Exception {}
class Cx_Exception extends Skeeks_Exception {}
\ No newline at end of file
<?php
class Cx_Install
{
}
\ No newline at end of file
<?php
/**
* interface Singleton
*
* @date 03.10.2014
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
interface Ix_Singleton
{
/**
* @abstract
* @static
* @return Ix_Singleton
*/
static public function getInstance();
}
/**
* Class Tx_Singleton
*/
trait Tx_Singleton
{
/**
* @var null
*/
static protected $_instance = null;
/**
* @return static
*/
static public function getInstance()
{
if (is_null(self::$_instance))
{
self::$_instance = new static();
}
return self::$_instance;
}
}
/**
* Class Cx_Singleton
*/
class Cx_Singleton
implements Ix_Singleton
{
use Tx_Singleton;
}
\ No newline at end of file
<?php
/**
* class Application
*
* Обложка для доступа к приложению + bootstraper
*
* @author Ayupov Vladimir
* @since 22.09.2010
*/
class SkeeksBase
{
/**
* @var Cx_Application|null Current application instance
*/
static public $app = null;
/**
* @var Cx_ClassAutoLoader|null
*/
static protected $_autoloader = null;
/**
* @static
* @param array|null $config
* @return Cx_Application_Web
*/
static public function createWebApplication(array $config = [])
{
return static::_createApplication('Cx_Application_Web', $config);
}
/**
* @static
* @param array|null $config
* @return Cx_Application_Cli
*/
static public function createCliApplication(array $config = [])
{
return static::_createApplication('Cx_Application_Cli', $config);
}
/**
* @param $class
* @param $config
* @return Cx_Application
*/
static public function createApplication($class, array $config = [])
{
return static::_createApplication($class, $config);
}
/**
* @param $class
* @param $config
* @return Cx_Application|null
* @throws Cx_Exception
*/
static protected function _createApplication($class, $config = [])
{
if (null !== static::$app)
{
throw new Cx_Exception("Application can only be created once.");
}
static::$app = new $class($config);
return static::$app;
}
/**
* @static
* @return Cx_ClassAutoLoader
*/
static public function getAutoloader()
{
//use framework classes loader
if (null === static::$_autoloader)
{
static::$_autoloader = new Cx_ClassAutoloader(
[APP_DIR, SX_DIR]
);
}
return static::$_autoloader;
}
}
// Registering default Skeeks class autoloader
spl_autoload_register([SkeeksBase::getAutoloader(), 'loadClass']);
\ No newline at end of file
<?php
/**
* Uri
*
* @date 21.03.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* Class Cx_Url
*/
class Cx_Url
extends Cx_Entity
{
const SCHEME_MULTI = "";
const SCHEME_HTTP = "http";
const SCHEME_HTTPS = "https";
/**
* @param $url
* @throws Cx_Exception
*/
static public function create($url)
{
if ($url instanceof Cx_Url)
{
$new = new static();
$new->setData($url->toArray());
return new static($new);
} else if ($url instanceof Cx_Url_Host)
{
$urlNew = new static();
$urlNew->setHost($url);
return $urlNew;
} else
{
if ($url)
{
return new static($url);
} else
{
throw new Cx_Exception("Url must be string or \\Cx_Url");
}
}
}
/**
*
* Если передан объект Cx_Url то просто вернет его
* Если нет то пересоберет
*
* @param $url
* @return Cx_Url
*/
static public function getInstance($url)
{
if ($url instanceof Cx_Url)
{
return $url;
} else
{
return static::create($url);
}
}
/**
* @param string $url
*/
public function __construct($url = "")
{
if ($url)
{
$this->_parse((string) $url);
}
$this->_init();
}
protected function _init()
{}
/**
* @param $url
* @return $this
*/
protected function _parse($url = "")
{
$this->_data = parse_url($url);
if ($this->offsetGet("host"))
{
$this->setHost($this->_data["host"]);
}
if ($this->isQuery())
{
$this->setQuery($this->_data["query"]);
}
return $this;
}
/**
* @return string
*/
public function toString()
{
$paths = [];
if ($this->getHost())
{
$paths[] = $this->getScheme() ? $this->getScheme() . ":" : "";
$paths[] = '//';
$paths[] = $this->getUser() ? $this->getUser() : "";
$paths[] = $this->getPass() ? ":" . $this->getPass() : "";
$paths[] = $this->getUser() || $this->getPass() ? '@' : '';
$paths[] = $this->getHost()->toString();
$paths[] = $this->getPort() ? ":" . $this->getPort() : "";
}
$paths[] = $this->getPath() ? $this->getPath() : '';
$paths[] = !$this->getQuery()->isEmpty() ? "?" . (string) $this->getQuery() : '';
$paths[] = $this->getFragment() ? "#" . (string) $this->getFragment() : '';
return implode($paths);
}
/**
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Есть query в строке
* @return bool
*/
public function isQuery()
{
return (bool) $this->offsetGet("query");
}
/**
* @return string
*/
public function getPass()
{
return (string) $this->get("pass");
}
/**
* @return string
*/
public function getScheme()
{
return (string) $this->get("scheme", static::SCHEME_HTTP);
}
/**
* @return Cx_Url_Host
*/
public function getHost()
{
return $this->get("host");
}
/**
* @return string
*/
public function getPath()
{
return (string) $this->get("path");
}
/**
* @return Cx_Url_Query
*/
public function getQuery()
{
if (!$this->get("query"))
{
$this->set("query", Cx_Url_Query::createEntity());
}
return $this->get("query");
}
/**
* @return string
*/
public function getPort()
{
return (string) $this->get("port");
}
/**
* @return string
*/
public function getUser()
{
return (string) $this->get("user");
}
/**
* @return string
*/
public function getFragment()
{
return (string) $this->get("fragment");
}
/**
* @param $value
* @return $this
*/
public function setScheme($value)
{
return $this->set("scheme", $value);
}
/**
* @param string|\Cx_Url_Host $host
* @return $this
*/
public function setHost($value)
{
if ($value && is_string($value))
{
$value = new Cx_Url_Host($value);
}
if (!$value instanceof Cx_Url_Host)
{
//throw new Cx_ExceptionSxInvalidArgument("host must be string or \\Cx_Url_Host");
}
return $this->set("host", $value);
}
/**
* @param $value
* @return $this
*/
public function setPath($value)
{
return $this->set("path", $value);
}
/**
* @param strintg|array|\Cx_Url_Query $value
* @return $this
*/
public function setQuery($value)
{
if (is_array($value))
{
$value = new Cx_Url_Query($value);
} else if (Cx_Validate::isValid(new Cx_Validator_Not_EmptyString(), $value))
{
$value = Cx_Url_Query::createFromString($value);
}
if (!Cx_Validate::isValid(new Cx_Validator_InstanceOf("Cx_Url_Query"), $value))
{
throw new Cx_ExceptionSxInvalidArgument("query must be string or \\Cx_Url_Query or array");
}
return $this->set("query", $value);
}
/**
* @param $value
* @return $this
*/
public function setPort($value)
{
return $this->set("port", $value);
}
/**
* @param $value
* @return $this
*/
public function setUser($value)
{
return $this->set("user", $value);
}
/**
* @param $value
* @return $this
* @throws Cx_Exception
*/
public function setPass($value)
{
return $this->set("pass", $value);
}
/**
* @param $value
* @return $this
*/
public function setFragment($value)
{
return $this->set("fragment", $value);
}
/**
* @return $this
*/
public function setCurrentHost()
{
$this
->setHost(Sx::app()->getHomeUrl()->getHost())
->setScheme(Sx::app()->getHomeUrl()->getScheme())
;
return $this;
}
/**
* @return Cx_Url_Headers
*/
public function getHeaders()
{
if ($this->get("headers", null) === null)
{
$this->set("headers", $this->getHeaders());
}
return $this->get("headers");
}
/**
* @return Cx_Url_Headers
*/
public function fetchHeaders()
{
return Cx_Url_Headers::fetchByUrl($this);
}
/**
* @var Cx_Url_Helper
*/
protected $_helper = null;
/**
* @return Cx_Url_Helper
*/
public function getHelper()
{
if ($this->_helper === null)
{
$this->_helper = new Cx_Url_Helper($this);
}
return $this->_helper;
}
/**
*
* Убирает лишние слэши из пути
*
* @param string $path
* @return string
*/
static public function removeSlashes($path = "")
{
if ($path)
{
$array = explode("/", $path);
$array = Cx_Helper_Array::onlyNotEmpty($array);
$path = "/" . implode("/", $array);
}
return $path;
}
}
\ No newline at end of file
<?php
/**
* Headers
*
* @date 15.05.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* Class Cx_Url_Headers
*/
class Cx_Url_Headers
extends \Cx_Entity
{
/**
* @param $url
* @return static
*/
static public function fetchByUrl($url)
{
//TODO:Усовершенстовать если совсем нусуществующий url то беда Варнинги
$url = \Cx_Url::getInstance($url);
$result = get_headers((string) $url, 1);
return new static($result);
}
/**
* @return string
*/
public function getFullHttp()
{
return (string) $this->get(0);
}
public function getHttpCode()
{
}
public function isRedirrect()
{
}
}
\ No newline at end of file
<?php
/**
* Хитрый хелпер урлов для нашего движка.
* Вынесен в отдельный класс, чтобы не портить и не нагромождать класс Cx_Url
* Helper
*
* @date 06.06.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* Class Cx_Url_Helper
*/
class Cx_Url_Helper
{
const PARAM_REFERER_NAME = "sx-ref";
/**
* @var Cx_Url
*/
protected $_url;
/**
* @param Cx_Url $url
*/
public function __construct(Cx_Url $url)
{
$this->_url = $url;
}
/**
* @param string $referer
* @return $this
*/
/*public function setReferer($referer = null)
{
if ($referer === null)
{
$request = Sx::app()->getFrontController()->getRequest();
if ($getReferer = $request->getQuery(Cx_Url_Helper::PARAM_REFERER_NAME))
{
$referer = $getReferer;
} else
{
$referer = $request->getUrl();
}
}
$this->_url->getQuery()->set(self::PARAM_REFERER_NAME, (string) $referer);
return $this;
}*/
/**
* @return string
*/
public function toString()
{
return (string) $this->_url;
}
/**
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
*
* перевод строки в транслит
*
* @param $str
* @return mixed
*/
static public function translitUtf($str)
{
if (preg_match('/[^A-Za-z0-9_\-]/', $str)) {
$tr = array(
"А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
"Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
"Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
"О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
"У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
"Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
"Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
"в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
"з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
"м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
"с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
"ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
"ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya",
//" "=> "_", "."=> "", "/"=> "_"
" "=> "-", "."=> "", "/"=> "_"
);
$str = strtr($str,$tr);
$str = preg_replace('/[^A-Za-z0-9_\-]/', '', $str);
}
return $str;
}
}
\ No newline at end of file
<?php
/**
* Uri
*
* @date 21.03.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* Class Cx_Url_Host
*/
class Cx_Url_Host
{
/**
* @param $file
* @return static
*/
static public function object($file = null)
{
if ($file instanceof static)
{
return $file;
} else
{
return new static($file);
}
}
/**
* @param string|Cx_Url $url
* @return Cx_Url_Host
* @throws Cx_ExceptionSxInvalidArgument
*/
static public function create($url)
{
if ($url instanceof Cx_Url_Host)
{
return new static($url->getHostName());
} else
{
if (Cx_Validate::isValid(new Cx_Validator_Not_EmptyString(), $url))
{
return new static($url);
} else
{
throw new Cx_ExceptionSxInvalidArgument("Url must be string or \\Cx_Url");
}
}
}
/**
* @param $url
* @return Cx_Url_Host
*/
static public function getInstance($url)
{
if ($url instanceof Cx_Url_Host)
{
return $url;
} else
{
return static::create($url);
}
}
protected $_hostName = "";
protected $_www = false;
/**
* @param string $url
*/
public function __construct($hostName)
{
$this->_parse((string) $hostName);
}
/**
* @param $url
* @return $this
*/
protected function _parse($hostName)
{
if (static::hostNameIsWwww($hostName))
{
$this->_www = true;
$this->_hostName = substr($hostName, 4, strlen($hostName));
} else
{
$this->_hostName = $hostName;
$this->_www = false;
}
return $this;
}
/**
* @return string
*/
public function getHostName()
{
return (string) $this->_hostName;
}
/**
* @return string
*/
public function toString()
{
$result = [];
if ($this->isWwww())
{
$result[] = "www.";
}
$result[] = $this->getHostName();
return implode($result);
}
/**
* @return Cx_Url
*/
public function getUrl()
{
return Cx_Url::create($this);
}
/**
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* @return $this
*/
public function enableWww()
{
$this->_www = true;
return $this;
}
/**
* @return $this
*/
public function disableWww()
{
$this->_www = false;
return $this;
}
/**
* @return bool
*/
public function isWwww()
{
return $this->_www;
}
/**
* @return bool
*/
static public function hostNameIsWwww($hostName)
{
if (substr($hostName, 0, 4) == "www.")
{
return true;
}
return false;
}
/**
* @return int
*/
public function getLevel()
{
return count(explode(".", $this->_hostName));
}
}
\ No newline at end of file
<?php
/**
* Uri
*
* @date 21.03.14
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* Class Cx_Url
*/
class Cx_Url_Query
extends Cx_Entity
{
protected $_encode = true;
/**
* @param $string
* @return static
*/
static public function createFromString($string)
{
parse_str($string, $data);
return new static($data);
}
/**
* @return string
*/
public function toString()
{
/*$aPairs = array();
foreach ($this->_data as $sKey => $sValue)
{
$aPairs[] = $sKey . '=' . ($this->isEncode() ? $this->urlencode($sValue) : $sValue);
}
print_r(http_build_query($this->_data));die;
return implode('&', $aPairs);*/
return http_build_query($this->_data);
}
/*public function urlencode($data)
{
if (is_array($data))
{
$result = [];
foreach ($data as $key => $value)
{
$result[urlencode($key)] = $this->urlencode($value);
}
return $result;
} else
{
return urlencode($data);
}
}*/
/**
* @return bool
*/
public function isEncode()
{
return (bool) $this->_encode;
}
/**
* @return $this
*/
public function enableEncode()
{
$this->_encode = true;
return $this;
}
/**
* @return $this
*/
public function disableEncode()
{
$this->_encode = false;
return $this;
}
}
\ No newline at end of file
<?php
/**
* UrlManager
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
class Cx_UrlManager
{
public $routeParamName = 'r';
/**
* @param Cx_Controller_Request $request
* @return Cx_Controller_Request
*/
public function route(Cx_Controller_Request $request)
{
$query = $request->getQuery();
$route = $query->get($this->routeParamName);
$controller = 'default';
$action = 'index';
if ($route)
{
$roteParts = explode('/', $route);
if (isset($roteParts[0]))
{
$controller = $roteParts[0];
}
if (isset($roteParts[1]))
{
$action = $roteParts[1];
}
}
$request->route($controller, $action, $query->toArray());
return $request;
}
/**
* @param $route
* @param array $params
* @return string
*/
public function createUrl($route, array $params = [])
{
$data = array_merge($params, [
$this->routeParamName = $route,
]);
return '/index.php?' . http_build_query($data);
}
}
\ No newline at end of file
<?php
/**
* View
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Interface Ix_View
*/
interface Ix_View
{
public function render($name);
public function addPath($path);
public function setPaths(array $paths = array());
public function getPaths();
public function setVar($name, $value);
public function setVars(array $vars);
public function getVar($name);
public function getVars();
/**
* @abstract
* @param string $name
* @return Ix_View_Helper
*/
static public function getHelper($name);
}
/**
* @TODO: list common view helper here
* @method Cx_View_Helper_Html_StaticInclude staticInclude()
* @method Cx_View_Helper_Html html()
* @method Cx_View_Helper_StaticKey staticKey()
*
* Class Cx_View
*/
class Cx_View
{
use Tx_Entity;
/**
* @var array Only admin-wise scripts can actually modify this. Strive to use "absolute" template paths, since they can be used within "dynamic" templates
*/
protected $_paths = [];
/**
* @static
* @var array
*/
static protected $_helpers = array();
/**
* @param array $config
*/
public function __construct($config = [])
{
if(is_array($config))
{
foreach($config as $k => $v)
{
if(in_array($k, array('paths', 'vars')))
{
$this->{'_' . $k} = $v;
}
}
}
}
/**
* @param string $path
* @return Cx_View
*/
public function addPath($path)
{
$this->_paths[] = $path;
return $this;
}
/**
* @param array $paths
* @return Cx_View
*/
public function addPaths(array $paths)
{
$this->_paths = array_merge($this->_paths, $paths);
return $this;
}
/**
* @param array $paths
* @return Cx_View
*/
public function setPaths(array $paths = array())
{
$this->_paths = $paths;
return $this;
}
/**
* @return array
*/
public function getPaths()
{
return $this->_paths;
}
/**
* @param $name
* @param array $vars
* @return string
* @throws Cx_Exception
*/
public function render($name, $vars = array())
{
$engineName = $this->_resolveEngineName($name);
if (!$engineName)
{
throw new Cx_Exception("Couldn't resolve template engine name from '{$name}'.");
}
//request the template engine
$engine = \Sx::$app->getTemplateEngine($engineName);
$this->_data = array_merge((array) $vars, (array) $this->_data);
//render!
$result = $engine->renderTemplateFile($this->_paths, $name, (array) $this->toArray());
return $result;
}
/**
* @param string $name
* @return string|null
*/
protected function _resolveEngineName($name)
{
$basename = basename($name);
if(strpos($name, '.') === false)
{
return null;
}
$chunks = explode('.', $basename);
return array_pop($chunks);
}
/**
*
* TODO: old function, don't use it;
*
* @param $name
* @param $value
* @return $this
*/
public function setVar($name, $value)
{
return $this->set($name, $value);
}
/**
*
* TODO: old function, don't use it;
*
* @param array $vars
* @return $this
*/
public function setVars(array $vars)
{
return $this->setData($vars);
}
/**
*
* TODO: old function, don't use it;
*
* @param $name
* @return null
*/
public function getVar($name)
{
return $this->get($name);
}
/**
* TODO: old function, don't use it;
* @return array
*/
public function getVars()
{
return $this->toArray();
}
/**
* TODO: old function, don't use it;
*
* @param array $vars
* @return $this
*/
public function mergeVars(array $vars)
{
return $this->addData($vars);
}
/**
* @static
* @param string $name
* @return Ix_View_Helper
*/
static public function getHelper($name)
{
if(!isset(static::$_helpers[$name]))
{
static::$_helpers[$name] = static::_createHelper($name);
}
$helper = static::$_helpers[$name];
return $helper;
}
/**
* @static
* @param string $name
* @return Ix_View_Helper
* @throws Cx_Exception
*/
static protected function _createHelper($name)
{
$class = \Sx::getClassName('Cx_View_Helper_' . $name);
if (!class_exists($class, true))
{
throw new Cx_Exception("View helper '{$name}' doesn't exist.");
}
return new $class;
}
/**
* @param string $name
* @param array $args
* @return mixed
*/
public function __call($name, $args)
{
$helper = static::getHelper($name);
return call_user_func_array($helper, $args);
}
}
\ No newline at end of file
<?php
/**
* TemplateEngine
* Любой движок, template должен ументь рендерить файлы, получая параметры
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Interface Ix_View_TemplateEngine
*/
interface Ix_View_TemplateEngine
{
/**
* @abstract
* @param array $paths List of paths
* @param string $name Name of the template file
* @param array $vars Template context
* @return string
*/
public function renderTemplateFile(array $paths, $name, array $vars = array());
}
/**
* Class Cx_View_TemplateEngine
*/
abstract class Cx_View_TemplateEngine
implements Ix_View_TemplateEngine
{}
\ No newline at end of file
<?php
/**
* Php
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
/**
* Class Cx_View_TemplateEngine_Php
*/
class Cx_View_TemplateEngine_Php
extends Cx_View_TemplateEngine_Phtml
{}
<?php
/**
* Phtml
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 07.10.2014
* @since 1.0.0
*/
/**
* Class Cx_View_TemplateEngine_Phtml
*/
class Cx_View_TemplateEngine_Phtml
extends Cx_View_TemplateEngine
{
use Tx_Entity;
/**
* @return array
*/
public function getVars()
{
return $this->toArray();
}
/**
* @abstract
* @param array $paths List of paths
* @param string $name Name of the template file
* @param array $vars Template context
* @return string
* @throws Cx_Exception
*/
public function renderTemplateFile(array $paths, $name, array $vars = array())
{
$templatePath = $this->_resolveTemplatePath($paths, $name);
if (!$templatePath)
{
throw new Cx_Exception("Couldn't find template '{$name}'. Used paths: " . join(', ', $paths) . '.');
}
if(!$this->_isSecurePath($templatePath))
{
throw new Cx_Exception("Template '{$templatePath}' is not secure to render.'");
}
//render (execute script)
$this->_data = $vars;
$output = $this->_render($templatePath);
$this->_data = array();
//return output
return $output;
}
/**
* @param array $paths
* @param string $name
* @return null|string
*/
protected function _resolveTemplatePath(array $paths, $name)
{
foreach($paths as $path)
{
$templatePath = $path . '/' . $name;
if (file_exists($templatePath))
{
return $templatePath;
}
}
return null;
}
/**
* @param string $path
* @return bool
*/
protected function _isSecurePath($path)
{
//@todo: change it!
//@todo: write validating code
return true;
}
/**
* @param string $path
* @return string
*/
protected function _render($path)
{
ob_start();
include $path;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
/**
* @static
* @param string $name
* @param array $arguments
* @return mixed|void
*/
public function __call($name, $arguments)
{
$helper = Cx_View::getHelper($name);
return call_user_func_array($helper, $arguments);
}
}
<?php
/**
* Должна быть определена в самом приложении
*/
if (!defined('APP_DIR'))
define('APP_DIR', SX_DIR);
/**
* Должна быть определена в самом приложении
*/
if (!defined('APP_DIR_VIEWS'))
define('APP_DIR_VIEWS', APP_DIR . '/views');
<?php
/**
* global.sx
* Файл глобальных переменных фреймворка.
* Эти переменные жестко конфигурируют фреймворк, и их нельзя переопределить переменными приложения
*
* @date 02.10.2014
* @copyright skeeks.com
* @author Semenov Alexander <semenov@skeeks.com>
*/
define('SX_DIR', dirname(__FILE__));
define('SX_CODE_DIR_NAME', 'code');
define('SX_CODE_DIR', SX_DIR . DIRECTORY_SEPARATOR . SX_CODE_DIR_NAME);
/**
*
*/
if (defined('SX_VERSION') || defined('SX_COPYRIGHT_NAME'))
{
die(base64_encode("aGFjayBhdHRhY2s="));
}
/**
* Текущая версия фреймворка
*/
define('SX_VERSION', '1.0.0');
/**
* Немного о себе
*/
define('SX_COPYRIGHT_NAME', 'SkeekS Cms Installer');
\ No newline at end of file
<?php
/**
* bootstrap
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
/**
* Обязательная переменная
*/
define('APP_DIR', dirname(__FILE__));
include __DIR__ . '../../fw/Skeeks.php';
$app = \Skeeks::createApplication('Cx_App');
$app->run();
\ No newline at end of file
<?php
/**
* Skeeks
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
class Cx_App extends Cx_Application_WebCustom
{
public $layout = 'layouts/default.php';
}
\ No newline at end of file
<?php
/**
* Default
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 20.02.2015
* @since 1.0.0
*/
class Cx_Controller_Default extends Cx_Controller_Action
{
protected function _init()
{
parent::_init();
$this->view->setPaths([APP_DIR_VIEWS . '/' . $this->id]);
}
public $noRender = false;
protected function _postDispatch()
{
if (Sx::$app->request->isAjax()) {
Sx::$app->response = new Cx_Controller_Response_Http_Plain();
}
if ($this->noRender)
{
return $this;
}
if (Sx::$app->request->isAjax())
{
return $this;
}
echo $this->view->render($this->action . '.php');
}
public function actionIndex()
{
$skeeksFile = ROOT_DIR . '/vendor/skeeks/cms/app-web.php';
$this->view->ready = '';
if (file_exists($skeeksFile))
{
if (!$this->installInProccess())
{
header("Location: /");
die;
$this->view->ready = '1';
}
}
$this->view->inProccess = 0;
$this->view->installTime = 0;
if (!$this->view->ready)
{
$this->view->inProccess = (int) $this->installInProccess();
$this->view->installTime = (int) $this->installTime();
}
if (Sx::$app->request->isAjax())
{
system('cd ' . ROOT_DIR . "; php init install --autoremove --unlock;");
}
}
public function actionCheckinstall()
{
if (Sx::$app->request->isAjax())
{
echo (int) $this->installTime();
}
}
/**
* Установка в процессе?
*
* @return bool
*/
protected function installInProccess()
{
$installLockFile = ROOT_DIR . '/install/runtime/install.lock';
return file_exists($installLockFile);
}
/**
* @return string
*/
protected function installTime()
{
if ($this->installInProccess())
{
return time() - file_get_contents(ROOT_DIR . '/install/runtime/install.lock');
}
return 0;
}
}
\ No newline at end of file
# Mod_Autoindex
<IfModule mod_autoindex.c>
# Запрещаем просмотр содержимого папок
Options -Indexes
</IfModule>
# Mod_Rewrite
<IfModule mod_rewrite.c>
Options +FollowSymlinks
# Включаем mod_rewrite
RewriteEngine On
# Если это папка или файл, открываем её/его
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# В противном случае перенаправляем на index.php
RewriteRule . index.php
</IfModule>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment