Пример #1
0
 /**
  * @param array $args
  *
  * @return int
  * @throws \ManaPHP\Cli\Application\Exception
  */
 public function handle($args = null)
 {
     $this->_args = $args ?: $GLOBALS['argv'];
     $command = count($this->_args) === 1 ? null : $this->_args[1];
     if (!$this->cliRouter->route($command)) {
         $this->console->writeLn('command name is invalid: ' . $command);
         return 1;
     }
     $controllerName = $this->cliRouter->getControllerName();
     $actionName = lcfirst($this->cliRouter->getActionName());
     $this->console->writeLn('executed command is `' . Text::underscore($controllerName) . ':' . Text::underscore($actionName) . '`');
     $controllerClassName = null;
     foreach ([$this->alias->resolve('@ns.app\\Cli\\Controllers\\' . $controllerName . 'Controller'), 'ManaPHP\\Cli\\Controllers\\' . $controllerName . 'Controller'] as $class) {
         if ($this->_dependencyInjector->has($class) || class_exists($class)) {
             $controllerClassName = $class;
         }
     }
     if (!$controllerClassName) {
         $this->console->writeLn('``:command` command is not exists', ['command' => lcfirst($controllerName) . ':' . $actionName]);
         return 1;
     }
     $controllerInstance = $this->_dependencyInjector->getShared($controllerClassName);
     $actionMethod = $actionName . 'Command';
     if (!method_exists($controllerInstance, $actionMethod)) {
         $this->console->writeLn('`:command` sub command is not exists', ['command' => lcfirst($controllerName) . ':' . $actionName]);
         return 1;
     }
     $r = $controllerInstance->{$actionMethod}();
     return is_int($r) ? $r : 0;
 }
Пример #2
0
 /**
  * Returns the mapped source for a model
  *
  * @param \ManaPHP\Mvc\ModelInterface|string $model
  *
  * @return string
  */
 public function getModelSource($model)
 {
     $modelName = is_string($model) ? $model : get_class($model);
     if (!isset($this->_sources[$modelName])) {
         if ($this->_recallGetModelSource) {
             return Text::underscore(Text::contains($modelName, '\\') ? substr($modelName, strrpos($modelName, '\\') + 1) : $modelName);
         }
         $modelInstance = is_string($model) ? new $model() : $model;
         /** @noinspection NotOptimalIfConditionsInspection */
         if (!isset($this->_sources[$modelName])) {
             $this->_recallGetModelSource = true;
             $this->_sources[$modelName] = $modelInstance->getSource();
             $this->_recallGetModelSource = false;
         }
     }
     return $this->_sources[$modelName];
 }
Пример #3
0
 /**
  * @param string $key
  *
  * @return string
  */
 protected function _getFileName($key)
 {
     if ($key[0] === '!') {
         return $this->alias->resolve($this->_dir . '/' . str_replace(':', '/', substr($key, 1)) . $this->_extension);
     }
     if (Text::contains($key, '/')) {
         $parts = explode('/', $key, 2);
         $md5 = $parts[1];
         $file = $this->_dir . '/' . $parts[0] . '/';
         for ($i = 0; $i < $this->_level; $i++) {
             $file .= substr($md5, $i + $i, 2) . '/';
         }
         $file .= $md5;
     } else {
         $file = $this->_dir . '/' . $key;
     }
     return $this->alias->resolve(str_replace(':', '/', $file . $this->_extension));
 }
Пример #4
0
    public function createCommand()
    {
        $usage = 'format is invalid: {Module}:{A,B,C,D,E}';
        $arguments = $this->arguments->get();
        if (count($arguments) === 0) {
            $this->console->writeLn($usage);
            return 1;
        }
        $parts = explode(':', $arguments[0]);
        if (count($parts) !== 2) {
            $this->console->writeLn($usage);
            return 1;
        }
        $moduleName = Text::camelize($this->crossword->guess($this->application->getModules(), $parts[0]));
        if (!$moduleName) {
            return $this->console->error('module name is unknown: `:module`', ['module' => $parts[0]]);
        }
        $controllers = explode(',', $parts[1]);
        $controllerNamespace = $this->alias->resolve('@ns.app' . '\\' . $moduleName . '\\Controllers');
        foreach ($controllers as $controller) {
            $controller = Text::camelize($controller);
            $controllerName = $controller . 'Controller';
            $controllerFile = '@app/' . $moduleName . '/Controllers/' . $controllerName . '.php';
            if ($this->filesystem->fileExists($controllerFile)) {
                $this->console->writeLn('`:controller` controller exists already', ['controller' => $controllerNamespace . '\\' . $controller]);
                continue;
            }
            $controllerContent = <<<EOD
<?php
namespace {$controllerNamespace};

class {$controllerName} extends ControllerBase{
     public function indexAction()
     {
        
     }
}
EOD;
            $this->filesystem->filePut($controllerFile, $controllerContent);
            $this->filesystem->filePut('@app/' . $moduleName . '/Views/' . $controller . '/Index.sword', '');
            $this->filesystem->filePut('@app/' . $moduleName . '/Layouts/' . $controller . '.sword', '@content()');
        }
        return 0;
    }
Пример #5
0
 /**
  * Mwt constructor.
  *
  * @param array $options
  */
 public function __construct($options = [])
 {
     foreach (get_object_vars($this) as $field => $_) {
         if (!Text::startsWith($field, '_')) {
             $this->_fields[] = $field;
         }
     }
     if (isset($options['type'])) {
         $this->_type = $options['type'];
     }
     if (isset($options['keys'])) {
         $this->_keys = $options['keys'];
     } else {
         $this->_keys = [$this->configure->getSecretKey('mwt:' . $this->_type)];
     }
     if (isset($options['ttl'])) {
         $this->_ttl = $options['ttl'];
     }
 }
Пример #6
0
 /**
  * @param string|array $controllerAction
  * @param int          $duration
  * @param int          $ip_times
  * @param int          $user_times
  *
  * @return void
  * @throws \ManaPHP\Security\RateLimiter\Exception
  */
 public function limit($controllerAction, $duration, $ip_times, $user_times = null)
 {
     if ($controllerAction === null) {
         $resource = $this->dispatcher->getControllerName() . ':' . $this->dispatcher->getActionName();
         $this->limitAny($resource, $duration, $ip_times, $user_times);
     } else {
         if (is_array($controllerAction)) {
             $resource = basename($controllerAction[0], 'Controller') . ':' . lcfirst(Text::camelize($controllerAction[1]));
         } else {
             $parts = explode(':', $controllerAction);
             if (count($parts) !== 2) {
                 throw new RateLimiterException('`:controllerAction` controllerAction is invalid: the correct format is `controller:action`', ['controllerAction' => $controllerAction]);
             }
             $resource = Text::camelize($parts[0]) . ':' . lcfirst(Text::camelize($parts[1]));
         }
         if ($resource === $this->dispatcher->getControllerName() . ':' . $this->dispatcher->getActionName()) {
             $this->limitAny($controllerAction, $duration, $ip_times, $user_times);
         }
     }
 }
Пример #7
0
 /**
  * @description minify the ManaPHP framework source code
  * @return int
  */
 public function defaultCommand()
 {
     $ManaPHPSrcDir = $this->alias->get('@manaphp');
     $ManaPHPDstDir = $ManaPHPSrcDir . '_' . date('ymd');
     $totalClassLines = 0;
     $totalInterfaceLines = 0;
     $totalLines = 0;
     $fileLines = [];
     $sourceFiles = $this->_getSourceFiles($ManaPHPSrcDir);
     foreach ($sourceFiles as $file) {
         $dstFile = str_replace($ManaPHPSrcDir, $ManaPHPDstDir, $file);
         $content = $this->_minify($this->filesystem->fileGet($file));
         $lineCount = Text::contains($content, "\r") ? substr_count($content, "\r") : substr_count($content, "\n");
         if (Text::contains($file, 'Interface.php')) {
             $totalInterfaceLines += $lineCount;
             $totalLines += $lineCount;
         } else {
             $totalClassLines += $lineCount;
             $totalLines += $lineCount;
         }
         $this->console->writeLn($content);
         $this->filesystem->filePut($dstFile, $content);
         $fileLines[$file] = $lineCount;
     }
     asort($fileLines);
     $i = 1;
     $this->console->writeLn('------------------------------------------------------');
     foreach ($fileLines as $file => $line) {
         $this->console->writeLn(sprintf('%3d %3d %.3f', $i++, $line, $line / $totalLines * 100) . ' ' . substr($file, strpos($file, 'ManaPHP')));
     }
     $this->console->writeLn('------------------------------------------------------');
     $this->console->writeLn('total     lines: ' . $totalLines);
     $this->console->writeLn('class     lines: ' . $totalClassLines);
     $this->console->writeLn('interface lines:  ' . $totalInterfaceLines);
     return 0;
 }
Пример #8
0
 /**
  * @param string $uri
  *
  * @return bool|array
  * @throws \ManaPHP\Mvc\Router\Route\Exception
  */
 public function match($uri)
 {
     $matches = [];
     if ($this->_httpMethod !== null && $this->_httpMethod !== $_SERVER['REQUEST_METHOD']) {
         return false;
     }
     if (Text::contains($this->_compiledPattern, '^')) {
         $r = preg_match($this->_compiledPattern, $uri, $matches);
         if ($r === false) {
             throw new RouteException('`:compiled` pcre pattern is invalid for `:pattern`', ['compiled' => $this->_compiledPattern, 'pattern' => $this->_pattern]);
         } elseif ($r === 1) {
             return $matches;
         } else {
             return false;
         }
     } else {
         if ($this->_compiledPattern === $uri) {
             return $matches;
         } else {
             return false;
         }
     }
 }
Пример #9
0
 /**
  * Handles routing information received from the rewrite engine
  *
  *<code>
  * //Read the info from the rewrite engine
  * $router->handle();
  *
  * //Manually passing an URL
  * $router->handle('/posts/edit/1');
  *</code>
  *
  * @param string $uri
  * @param string $host
  * @param bool   $silent
  *
  * @return bool
  * @throws \ManaPHP\Mvc\Router\Exception
  * @throws \ManaPHP\Mvc\Router\NotFoundRouteException
  */
 public function handle($uri = null, $host = null, $silent = true)
 {
     if ($uri === null) {
         $uri = $this->getRewriteUri();
     }
     if ($this->_removeExtraSlashes) {
         $uri = rtrim($uri, '/');
     }
     $refinedUri = $uri === '' ? '/' : $uri;
     $this->fireEvent('router:beforeCheckRoutes');
     $module = null;
     $routeFound = false;
     for ($i = count($this->_groups) - 1; $i >= 0; $i--) {
         $group = $this->_groups[$i];
         $path = $group['path'];
         $module = $group['module'];
         if ($path === '' || $path[0] === '/') {
             $checkedUri = $refinedUri;
         } else {
             $checkedUri = (strpos($path, '://') ? $this->request->getScheme() . '://' : '') . $_SERVER['HTTP_HOST'] . $refinedUri;
         }
         /**
          * strpos('/','')===false NOT true
          */
         if ($path !== '' && !Text::startsWith($checkedUri, $path)) {
             continue;
         }
         /**
          * substr('a',1)===false NOT ''
          */
         $handledUri = strlen($checkedUri) === strlen($path) ? '/' : substr($checkedUri, strlen($path));
         /**
          * @var \ManaPHP\Mvc\Router\Group $groupInstance
          */
         if ($group['groupInstance'] === null) {
             $group['groupInstance'] = $this->_dependencyInjector->get($group['groupClassName']);
         }
         $groupInstance = $group['groupInstance'];
         $parts = $groupInstance->match($handledUri);
         $routeFound = $parts !== false;
         if ($routeFound) {
             break;
         }
     }
     $this->_wasMatched = $routeFound;
     if ($routeFound) {
         $this->_module = $module;
         $this->_controller = isset($parts['controller']) ? basename($parts['controller'], 'Controller') : 'index';
         $this->_action = isset($parts['action']) ? basename($parts['action'], 'Action') : 'index';
         $params = [];
         if (isset($parts['params'])) {
             $params_str = trim($parts['params'], '/');
             if ($params_str !== '') {
                 $params = explode('/', $params_str);
             }
         }
         unset($parts['controller'], $parts['action'], $parts['params']);
         $this->_params = array_merge($params, $parts);
     }
     $this->fireEvent('router:afterCheckRoutes');
     if (!$routeFound && !$silent) {
         throw new NotFoundRouteException('router does not have matched route for `:uri`', ['uri' => $uri]);
     }
     return $routeFound;
 }
Пример #10
0
 /**
  * Returns a SQL statement built based on the builder parameters
  *
  * @return string
  * @throws \ManaPHP\Mvc\Model\QueryBuilder\Exception
  */
 protected function _buildSql()
 {
     if (count($this->_union) !== 0) {
         return $this->_getUnionSql();
     }
     if (count($this->_models) === 0) {
         throw new QueryBuilderException('at least one model is required to build the query');
     }
     $sql = 'SELECT ';
     if ($this->_distinct) {
         $sql .= 'DISTINCT ';
     }
     if ($this->_columns !== null) {
         $columns = $this->_columns;
     } else {
         $columns = '';
         $selectedColumns = [];
         /** @noinspection ForeachSourceInspection */
         foreach ($this->_models as $alias => $model) {
             $selectedColumns[] = '[' . (is_int($alias) ? $model : $alias) . '].*';
         }
         $columns .= implode(', ', $selectedColumns);
     }
     $sql .= $columns;
     $selectedModels = [];
     /** @noinspection ForeachSourceInspection */
     foreach ($this->_models as $alias => $model) {
         if ($model instanceof $this) {
             if (is_int($alias)) {
                 throw new QueryBuilderException('if using SubQuery, you must assign an alias for it');
             }
             $selectedModels[] = '(' . $model->getSql() . ') AS [' . $alias . ']';
             /** @noinspection SlowArrayOperationsInLoopInspection */
             $this->_bind = array_merge($this->_bind, $model->getBind());
         } else {
             if (is_string($alias)) {
                 $selectedModels[] = '[' . $model . '] AS [' . $alias . ']';
             } else {
                 $selectedModels[] = '[' . $model . ']';
             }
         }
     }
     $sql .= ' FROM ' . implode(', ', $selectedModels);
     $joinSQL = '';
     /** @noinspection ForeachSourceInspection */
     foreach ($this->_joins as $join) {
         $joinModel = $join[0];
         /** @noinspection MultiAssignmentUsageInspection */
         $joinCondition = $join[1];
         /** @noinspection MultiAssignmentUsageInspection */
         $joinAlias = $join[2];
         /** @noinspection MultiAssignmentUsageInspection */
         $joinType = $join[3];
         if ($joinAlias !== null) {
             $this->_models[$joinAlias] = $joinModel;
         } else {
             $this->_models[] = $joinModel;
         }
         if ($joinType !== null) {
             $joinSQL .= ' ' . $joinType;
         }
         if ($joinModel instanceof $this) {
             $joinSQL .= ' JOIN (' . $joinModel->getSql() . ')';
             /** @noinspection SlowArrayOperationsInLoopInspection */
             $this->_bind = array_merge($this->_bind, $joinModel->getBind());
             if ($joinAlias === null) {
                 throw new QueryBuilderException('if using SubQuery, you must assign an alias for it');
             }
         } else {
             $joinSQL .= ' JOIN [' . $joinModel . ']';
         }
         if ($joinAlias !== null) {
             $joinSQL .= ' AS [' . $joinAlias . ']';
         }
         if ($joinCondition) {
             $joinSQL .= ' ON ' . $joinCondition;
         }
     }
     $sql .= $joinSQL;
     $wheres = [];
     if (is_string($this->_conditions)) {
         $this->_conditions = [$this->_conditions];
     }
     /** @noinspection ForeachSourceInspection */
     foreach ($this->_conditions as $k => $v) {
         if ($v === '') {
             continue;
         }
         if (is_int($k)) {
             $wheres[] = Text::contains($v, ' or ', true) ? "({$v})" : $v;
         } else {
             $wheres[] = "[{$k}]=:{$k}";
             $this->_bind[$k] = $v;
         }
     }
     if (count($wheres) !== 0) {
         $sql .= ' WHERE ' . implode(' AND ', $wheres);
     }
     if ($this->_group !== null) {
         $sql .= ' GROUP BY ' . $this->_group;
     }
     if ($this->_having !== null) {
         $sql .= ' HAVING ' . $this->_having;
     }
     if ($this->_order !== null) {
         $sql .= ' ORDER BY ' . $this->_order;
     }
     if ($this->_limit !== 0) {
         $sql .= ' LIMIT ' . $this->_limit;
     }
     if ($this->_offset !== 0) {
         $sql .= ' OFFSET ' . $this->_offset;
     }
     if ($this->_forUpdate) {
         $sql .= ' FOR UPDATE';
     }
     //compatible with other SQL syntax
     $replaces = [];
     foreach ($this->_bind as $key => $_) {
         $replaces[':' . $key . ':'] = ':' . $key;
     }
     $sql = strtr($sql, $replaces);
     /** @noinspection ForeachSourceInspection */
     foreach ($this->_models as $model) {
         if (!$model instanceof $this) {
             $sql = str_replace('[' . $model . ']', '[' . $this->modelsManager->getModelSource($model) . ']', $sql);
         }
     }
     return $sql;
 }
Пример #11
0
 /**
  * @param array        $rows
  * @param string       $attachmentName
  * @param array|string $columns
  *
  * @return static
  */
 public function setCsvContent($rows, $attachmentName, $columns = null)
 {
     if (is_string($columns)) {
         $columns = explode(',', $columns);
     }
     if (pathinfo($attachmentName, PATHINFO_EXTENSION) !== 'csv') {
         $attachmentName .= '.csv';
     }
     $this->setAttachment($attachmentName);
     $file = fopen('php://temp', 'r+');
     fprintf($file, "");
     if ($columns !== null) {
         if (Text::startsWith($columns[0], 'ID')) {
             $columns[0] = strtolower($columns[0]);
         }
         fputcsv($file, $columns);
     }
     foreach ($rows as $row) {
         if (is_object($row)) {
             if (method_exists($row, 'toArray')) {
                 $data = $row->toArray();
             } else {
                 $data = (array) $row;
             }
         } elseif (!is_array($row)) {
             $data = [$row];
         } else {
             $data = $row;
         }
         fputcsv($file, $data);
     }
     rewind($file);
     $content = stream_get_contents($file);
     fclose($file);
     $this->setContentType('text/csv');
     $this->setContent($content);
     return $this;
 }
Пример #12
0
 /**
  * @param string     $method
  * @param int|string $arguments
  *
  * @return array|false|int|\ManaPHP\Mvc\Model|static[]
  * @throws \ManaPHP\Mvc\Model\Exception
  */
 public static function __callStatic($method, $arguments)
 {
     switch (count($arguments)) {
         case 0:
             throw new ModelException('The `:method` requires one argument at least', ['method' => $method]);
             break;
         case 1:
             $arguments[] = null;
             break;
         case 2:
             break;
         default:
             throw new ModelException('The `:method` requires two arguments at most', ['method' => $method]);
     }
     if (!is_scalar($arguments[0])) {
         throw new ModelException('The first argument of `:method`  must be a scalar value', ['method' => $method]);
     }
     if (strpos($method, 'findFirstBy') === 0) {
         return static::findFirst([Text::underscore(substr($method, 11)) => $arguments[0]], $arguments[1]);
     } elseif (strpos($method, 'findBy') === 0) {
         return static::find([Text::underscore(substr($method, 6)) => $arguments[0]], $arguments[1]);
     } elseif (strpos($method, 'countBy') === 0) {
         return static::count([Text::underscore(substr($method, 7)) => $arguments[0]], '*', $arguments[1]);
     } else {
         return null;
     }
 }
Пример #13
0
 /**
  * Deletes data from a table using custom SQL syntax
  * <code>
  * //Deleting existing robot
  * $success = $connection->delete(
  *     "robots",
  *     "id = 101"
  * );
  * //Next SQL sentence is generated
  * DELETE FROM `robots` WHERE `id` = 101
  * </code>
  *
  * @param  string       $table
  * @param  string|array $conditions
  * @param  array        $bind
  *
  * @return int
  * @throws \ManaPHP\Db\Exception
  */
 public function delete($table, $conditions, $bind = [])
 {
     if (is_string($conditions)) {
         $conditions = [$conditions];
     }
     $wheres = [];
     /** @noinspection ForeachSourceInspection */
     foreach ($conditions as $k => $v) {
         if (is_int($k)) {
             $wheres[] = Text::contains($v, ' or ', true) ? "({$v})" : $v;
         } else {
             $wheres[] = "`{$k}`=:{$k}";
             $bind[$k] = $v;
         }
     }
     $sql = "DELETE FROM `{$table}` WHERE " . implode(' AND ', $wheres);
     return $this->execute($sql, $bind);
 }
Пример #14
0
 /**
  * @param string|array $url
  *
  * @return string
  */
 protected function _buildUrl($url)
 {
     if (is_string($url)) {
         return $url;
     }
     return $url[0] . (Text::contains($url[0], '?') ? '&' : '?') . http_build_query($url[1]);
 }
Пример #15
0
    /**
     * @description create a new module
     * @throws \Application\Exception
     * @throws \ManaPHP\Filesystem\Adapter\Exception
     */
    public function createCommand()
    {
        $modules = ['dd'];
        foreach ($modules as $module) {
            $module = Text::camelize($module);
            $moduleDir = $this->alias->resolve('@app/' . $module);
            if ($this->filesystem->dirExists($moduleDir)) {
                throw new Exception('`:module` module is exists already.', ['module' => $module]);
            }
            $this->filesystem->dirCreate($moduleDir . '/Models');
            $this->filesystem->dirCreate($moduleDir . '/Views');
            $this->filesystem->dirCreate($moduleDir . '/Views/Shared');
            $this->filesystem->dirCreate($moduleDir . '/Views/Layouts');
            $this->filesystem->dirCreate($moduleDir . '/Views/Widgets');
            $this->filesystem->dirCreate($moduleDir . '/Widgets');
            $this->filesystem->dirCreate($moduleDir . '/Controllers');
            //------------------------------
            $controllerBaseContent = <<<EOD
<?php

namespace Application\\{$module}\\Controllers;

use ManaPHP\\Mvc\\Controller;

class ControllerBase extends Controller
{

}
EOD;
            $this->filesystem->filePut($moduleDir . './Controllers/ControllerBase.php', $controllerBaseContent);
            //---------------------------------------
            $indexControllerContent = <<<EOD
<?php

namespace Application\\{$module}\\Controllers;

class IndexController extends ControllerBase
{
    public function indexAction(){
        echo __FILE__;
    }
}

EOD;
            $this->filesystem->filePut($moduleDir . '/Controllers/IndexController.php', $indexControllerContent);
            //-----------------------
            $moduleContent = <<<EOD
<?php
namespace Application\\{$module};

class Module extends \\ManaPHP\\Mvc\\Module
{
    public function registerServices(\$di)
    {

    }

    public function authorize(\$controller, \$action)
    {
        return true;
    }
}
EOD;
            $this->filesystem->filePut($moduleDir . '/Module.php', $moduleContent);
            //------------------------
            $routeGroupContent = <<<EOD
<?php
namespace Application\\{$module};

use ManaPHP\\Mvc\\Router\\Group;

class RouteGroup extends Group
{
    public function __construct()
    {
        parent::__construct(true);
    }
}
EOD;
            $this->filesystem->filePut($moduleDir . '/RouteGroup.php', $routeGroupContent);
            $viewLayoutsDefaultContent = <<<EOD
<!DOCTYPE html>
<html lang="en">
<head>
\t<meta charset="UTF-8">
\t<title>{$module}</title>
</head>
<body>
@content()\t
</body>
</html>
EOD;
            $this->filesystem->filePut($moduleDir . '/Views/Layouts/Default.sword', $viewLayoutsDefaultContent);
            $this->filesystem->filePut($moduleDir . '/Views/Layouts/Index.sword', $viewLayoutsDefaultContent);
            //----------
            $viewIndexContent = <<<EOD
        
    <h1>{$module}</h1>
EOD;
            $this->filesystem->filePut($moduleDir . '/Views/Index/Index.sword', $viewIndexContent);
        }
    }
Пример #16
0
 /**
  * Gets most possible client IPv4 Address. This method search in $_SERVER['REMOTE_ADDR'] and optionally in $_SERVER['HTTP_X_FORWARDED_FOR']
  *
  * @return string
  */
 public function getClientAddress()
 {
     if ($this->_clientAddress === null) {
         if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
             $this->_clientAddress = $_SERVER['REMOTE_ADDR'];
         } else {
             $client_address = $_SERVER['REMOTE_ADDR'];
             if (Text::startsWith($client_address, '127.0.') || Text::startsWith($client_address, '192.168.') || Text::startsWith($client_address, '10.')) {
                 $this->_clientAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
             } else {
                 $this->_clientAddress = $_SERVER['REMOTE_ADDR'];
             }
         }
     }
     return $this->_clientAddress;
 }
Пример #17
0
 /**
  * @param string $task
  *
  * @return void
  */
 public function reset($task)
 {
     $rc = new \ReflectionClass($this);
     foreach ($rc->getConstants() as $n => $field) {
         if (!Text::startsWith($n, 'FIELD_')) {
             continue;
         }
         $this->adapter->delete($this->_formatKey($task, $field));
     }
 }
Пример #18
0
 /**
  * @param array $table
  *
  * @return array
  */
 protected function _getByColumns($table)
 {
     $keyColumns = [];
     foreach ($this->db->fetchAll("SHOW INDEX FROM `{$table}`") as $row) {
         $keyName = $row['Key_name'];
         if (!isset($keyColumns[$keyName])) {
             $keyColumns[$keyName] = [];
         }
         $keyColumns[$keyName] = $row['Column_name'];
     }
     $columns = [];
     foreach ($keyColumns as $k => $v) {
         if (count($v) === 1) {
             $columns[$v] = Text::camelize($v);
         }
     }
     return $columns;
 }
Пример #19
0
 /**
  * Moves the temporary file to a destination within the application
  *
  * @param string       $dst
  * @param string|false $allowedExtensions
  *
  * @throws \ManaPHP\Filesystem\Adapter\Exception
  * @throws \ManaPHP\Http\Request\File\Exception
  */
 public function moveTo($dst, $allowedExtensions = 'jpg,jpeg,png,gif,doc,xls,pdf,zip')
 {
     $extension = pathinfo($dst, PATHINFO_EXTENSION);
     if ($extension) {
         $extension = ',' . $extension . ',';
         if (is_string($allowedExtensions)) {
             $allowedExtensions = ',' . str_replace(' ', '', $allowedExtensions) . ',';
             $allowedExtensions = str_replace(',.', ',', $allowedExtensions);
             if (!Text::contains($allowedExtensions, $extension, true)) {
                 throw new FileException('`:extension` file type is not allowed upload', ['extension' => $extension]);
             }
         }
         if (is_string(self::$_alwaysRejectedExtensions)) {
             $alwaysRejectedExtensions = ',' . str_replace(' ', '', self::$_alwaysRejectedExtensions) . ',';
             $alwaysRejectedExtensions = str_replace(',.', ',', $alwaysRejectedExtensions);
             if (Text::contains($alwaysRejectedExtensions, $extension, true)) {
                 throw new FileException('`:extension` file types is not allowed upload always', ['extensions' => self::$_alwaysRejectedExtensions]);
             }
         }
     }
     if ($this->_file['error'] !== UPLOAD_ERR_OK) {
         throw new FileException('error code of upload file is not UPLOAD_ERR_OK: :error', ['error' => $this->_file['error']]);
     }
     if ($this->filesystem->fileExists($dst)) {
         throw new FileException('`:file` file already exists', ['file' => $dst]);
     }
     $this->filesystem->dirCreate(dirname($dst));
     if (!move_uploaded_file($this->_file['tmp_name'], $this->alias->resolve($dst))) {
         throw new FileException('move_uploaded_file to `:dst` failed: :last_error_message', ['dst' => $dst]);
     }
     if (!chmod($this->alias->resolve($dst), 0644)) {
         throw new FileException('chmod `:dst` destination failed: :last_error_message', ['dst' => $dst]);
     }
 }
Пример #20
0
 /**
  * Renders a partial view
  *
  * <code>
  *    //Show a partial inside another view
  *    $this->partial('shared/footer');
  * </code>
  *
  * <code>
  *    //Show a partial inside another view with parameters
  *    $this->partial('shared/footer', array('content' => $html));
  * </code>
  *
  * @param string $path
  * @param array  $vars
  *
  * @throws \ManaPHP\Mvc\View\Exception
  * @throws \ManaPHP\Renderer\Exception
  */
 public function partial($path, $vars = [])
 {
     if (!Text::contains($path, '/')) {
         $path = $this->_controllerName . '/' . $path;
     }
     $this->_render("@views/{$path}", $vars, true);
 }
Пример #21
0
 /**
  * @param string $level
  * @param string $message
  * @param array  $context
  *
  * @return static
  */
 public function log($level, $message, $context)
 {
     $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
     $location = '';
     if (isset($traces[1])) {
         $trace = $traces[1];
         if (isset($trace['file'], $trace['line'])) {
             $location = str_replace($this->alias->get('@app'), '', str_replace('\\', '/', $trace['file'])) . ':' . $trace['line'];
         }
     }
     if (Text::contains($message, '%')) {
         $replaces = [];
         foreach ($context as $k => $v) {
             $replaces['%' . $k . '%'] = $v;
         }
         $message = strtr($message, $replaces);
     }
     $context['level'] = $level;
     $context['date'] = time();
     $context['location'] = $location;
     $eventData = ['level' => $level, 'message' => $message, 'context' => $context];
     $this->fireEvent('logger:log', $eventData);
     if ($this->_s2i[$level] > $this->_s2i[$this->_level]) {
         return $this;
     }
     $this->adapter->log($level, $message, $context);
     return $this;
 }
Пример #22
0
 /**
  * @param string $template
  *
  * @return string
  * @throws \ManaPHP\Debugger\Exception
  */
 public function save($template = 'Default')
 {
     if (Text::contains($_SERVER['HTTP_USER_AGENT'], 'ApacheBench')) {
         return '';
     }
     $file = date('/ymd/His_') . $this->random->getBase(32) . '.html';
     $this->filesystem->filePut('@data/debugger' . $file, $this->output($template));
     return $this->url->get('/?_debugger=' . $file);
 }
Пример #23
0
 /**
  * @param string $cmd
  *
  * @return bool
  */
 public function route($cmd)
 {
     $this->_controllerName = null;
     $this->_actionName = null;
     $command = $cmd ?: 'help:list';
     if (isset($this->_commandAliases[strtolower($command)])) {
         $command = $this->_commandAliases[strtolower($command)];
     }
     $parts = explode(':', $command);
     switch (count($parts)) {
         case 1:
             $controllerName = $parts[0];
             $actionName = null;
             break;
         case 2:
             $controllerName = $parts[0];
             $actionName = $parts[1];
             break;
         default:
             return false;
     }
     if ($this->_guessCommand && strlen($controllerName) <= 3) {
         $controllers = $this->_getControllers();
         $controllerName = $this->crossword->guess($controllers, $controllerName);
         if (!$controllerName) {
             return false;
         }
     } else {
         $controllerName = Text::camelize($controllerName);
     }
     if ($actionName === null) {
         $commands = $this->_getCommands($controllerName);
         if (count($commands) === 1) {
             $actionName = $commands[0];
         } else {
             return false;
         }
     } else {
         if ($this->_guessCommand && strlen($actionName) <= 2) {
             $commands = $this->_getCommands($controllerName);
             $actionName = $this->crossword->guess($commands, $actionName);
             if (!$actionName) {
                 return false;
             }
         } else {
             $actionName = lcfirst(Text::camelize($actionName));
         }
     }
     $this->_controllerName = $controllerName;
     $this->_actionName = $actionName;
     return true;
 }
Пример #24
0
 /**
  * @param string $controllerName
  *
  * @return static
  */
 public function setControllerName($controllerName)
 {
     $this->_controllerName = Text::camelize($controllerName);
     return $this;
 }
Пример #25
0
 /**
  * @param string|array $uri
  * @param array        $args
  * @param string       $module
  *
  * @return string
  * @throws \ManaPHP\Mvc\Url\Exception
  */
 public function get($uri, $args = [], $module = null)
 {
     if (is_array($uri)) {
         $tmp = $uri;
         $uri = $tmp[0];
         if (isset($tmp[1])) {
             $args = $tmp[1];
         }
         if (isset($tmp[2])) {
             $module = $tmp[2];
         }
     }
     /** @noinspection CallableParameterUseCaseInTypeContextInspection */
     if (is_string($args)) {
         $module = $args;
         $args = [];
     }
     if (!isset($this->_baseUrls[$module])) {
         if (isset($this->_baseUrls[ucfirst($module)])) {
             throw new UrlException('module name is case-sensitive: `:module`', ['module' => $module]);
         } else {
             throw new UrlException('`:module` is not exists', ['module' => $module]);
         }
     }
     if ($uri === '' || $uri[0] !== '/') {
         $baseUrl = $this->_baseUrls[$module];
         $strUrl = (strpos($baseUrl, '://') ? parse_url($baseUrl, PHP_URL_PATH) : $baseUrl) . '/' . $uri;
     } else {
         $strUrl = $this->_baseUrls[$module] . $uri;
     }
     if (Text::contains($strUrl, ':')) {
         foreach ($args as $k => $v) {
             $count = 0;
             $strUrl = str_replace(':' . $k, $v, $strUrl, $count);
             if ($count !== 0) {
                 unset($args[$k]);
             }
         }
     }
     if (count($args) !== 0) {
         $strUrl .= (Text::contains($strUrl, '?') ? '&' : '?') . http_build_query($args);
     }
     return $strUrl;
 }
Пример #26
0
 /**
  * @param string $attribute
  * @param string $filter
  * @param array  $parameters
  * @param mixed  $value
  *
  * @return mixed
  * @throws \ManaPHP\Http\Filter\Exception
  */
 protected function _sanitize($attribute, $filter, $parameters, $value)
 {
     $srcValue = $value;
     if (isset($this->_filters[$filter])) {
         $value = call_user_func_array($this->_filters[$filter], [$value, $parameters]);
     } elseif (function_exists($filter)) {
         $value = call_user_func_array($filter, array_merge([$value], $parameters));
     } else {
         throw new FilterException('`:name` filter is not be recognized', ['name' => $filter]);
     }
     if ($value === null) {
         if (is_string($this->_messages)) {
             if (!Text::contains($this->_messages, '.')) {
                 $file = '@manaphp/Http/Filter/Messages/' . $this->_messages . '.php';
             } else {
                 $file = $this->_messages;
             }
             if (!$this->filesystem->fileExists($file)) {
                 throw new FilterException('`:file` filter message template file is not exists', ['file' => $file]);
             }
             /** @noinspection PhpIncludeInspection */
             $this->_messages = (require $this->alias->resolve($file));
         }
         if (isset($this->_messages[$filter])) {
             $message = $this->_messages[$filter];
         } else {
             $message = $this->_defaultMessage;
         }
         $bind = [];
         $bind['filter'] = $filter;
         $bind['attribute'] = isset($this->_attributes[$attribute]) ? $this->_attributes[$attribute] : $attribute;
         $bind['value'] = $srcValue;
         foreach ($parameters as $k => $parameter) {
             $bind['parameter[' . $k . ']'] = $parameter;
         }
         throw new FilterException($message, $bind);
     }
     return $value;
 }