Loads the main routing framework and builds the application routes
@param bool $debug True if the system boots in debug mode
195388
public function load(bool $debug = false): void{
        $this->app = new Slim([
            'settings' => [
                'displayErrorDetails' => $debug
            ]
        ]);
        if (!$debug) {
            Error::registerSystemErrors($this->app);
        }
        $this->buildRoutes();
    }
585625
protected function createSerializer(array $config, $debug)
    {
        $builder = new SerializerBuilder;

        if (isset($config['cache_dir'])) {
            $builder->setCacheDir($config['cache_dir']);
        }

        if (isset($config['default_handlers'])) {
            $builder->addDefaultHandlers();
        }

        if (isset($config['handlers'])) {
            foreach ($config['handlers'] as $handler) {
                $builder->configureHandlers($handler);
            }
        }

        if (isset($config['event_listeners'])) {
            foreach ($config['event_listeners'] as $handler) {
                $builder->configureListeners($handler);
            }
        }

        $builder->addMetadataDirs(array_get($config, 'paths', [base_path('app')]));
        $builder->setDebug($debug);

        return $builder->build();
    }
117981
public function run($debug = false) {
        $this->debug    = $debug;
        $rqMethod       = strtolower($_SERVER ['REQUEST_METHOD']);
        $this->rqMehtod = ucfirst($rqMethod);
        if ($rqMethod != 'Get') {
            Request::getInstance()->addJsonPostBody();
        }
        $this->format = rqst('format', $this->format);
        if (!$this->format) {
            $this->format = 'json';
        }
        $format = $this->format;
        fire('restful\startCall', time(), $format);
        $rtime     = 0;
        $timestamp = rqst('timestamp');
        //时间检测，时差正负5分钟
        if ($timestamp && preg_match('/^2\d\d\d-(1[0-2]|0[1-9])-(0[1-9]|[12]\d|3[01])\s([01][0-9]|2[0-3]):([0-5]\d):([0-5]\d)(\sGMT)?$/', $timestamp)) {
            $timestampx = @strtotime($timestamp);
            if ($timestampx !== false) {
                $rtime = $timestampx;
            }
        }
        $ctime = time();
        if (($rtime + 300) < $ctime || $rtime - 300 > $ctime) {
            $this->httpout(408, 'Request Timeout');//非法请求
        }
        //时间检测结束
        $v   = irqst('v', 1);
        $api = rqst('api');//API
        if (empty($api)) {
            $this->httpout(400, 'Miss API');
        }
        $app_key = rqst('app_key');//APPKEY
        if (empty($app_key)) {
            return $this->generateResult($format, [
                'error' => [
                    'code' => 40000,
                    'msg'  => __('miss app_key@restful')
                ]
            ]);
        }
        $apis = explode('.', $api);
        if (count($apis) != 3) {
            $this->httpout(406, __('Invalid API@restful'));
        }
        $namesapce = $apis[0];
        $module    = App::getModuleById($namesapce);
        if (!$module) {
            $this->httpout(404, __('module not found@restful'));
        }
        $cls = ucfirst($apis[1]) . 'Api';
        $cls = $namesapce . '\\api\\v' . $v . '\\' . $cls;
        if (class_exists($cls) && is_subclass_of($cls, API::class)) {
            /**@var API $clz */
            $clz = new $cls($app_key, $v);
            $ann = new \ReflectionObject($clz);
            $rm  = $this->rqMehtod;
            try {
                if ($rm != 'Get') {
                    $m = $ann->getMethod($apis[2] . $rm);
                } else {
                    $m = $ann->getMethod($apis[2]);
                }
            } catch (\Exception $mre) {
                try {
                    if ($rm != 'Get') {
                        $tmp = $ann->getMethod($apis[2]);
                        if ($tmp) {
                            $this->httpout(405, __('unsupport request methd@restful'));
                        }
                    }
                } catch (\Exception $e) {

                }
                $m = false;
            }
            if (!$m) {
                $this->httpout(404, __('api not found@restful'));
            }

            $params  = [];//请求参数用于签名
            $dparams = [];//调用参数
            $ps      = $m->getParameters();
            /**@var \ReflectionParameter $p */
            foreach ($ps as $p) {
                $name = $p->getName();
                if (rqset($name)) {
                    $dparams[ $name ] = $params[ $name ] = rqst($name);
                } else if ($p->isOptional()) {
                    $dparams[ $name ] = $p->getDefaultValue();
                } else if (isset($_FILES[ $name ])) {
                    $dparams[ $name ] = $_FILES[ $name ];
                } else {
                    return $this->generateResult($format, [
                        'error' => [
                            'code' => 40001,
                            'msg'  => __('Miss param: %s@restful', $name)
                        ]
                    ]);
                }
            }
            $sign_method = rqst('sign_method');
            if ($sign_method != 'md5' && $sign_method != 'sha1' && $sign_method != 'hmac') {
                return $this->generateResult($format, [
                    'error' => [
                        'code' => 40002,
                        'msg'  => __('unsupport sign methd@restful')
                    ]
                ]);
            }

            $appSecret = $this->secretChecker->check($app_key);
            if (!$appSecret) {
                return $this->generateResult($format, [
                    'error' => [
                        'code' => 40003,
                        'msg'  => __('invalid app_key@restful')
                    ]
                ]);
            }
            //签名
            $sign = rqst('sign');
            $args = array_merge($params, [
                'v'           => $v,
                'app_key'     => $app_key,
                'api'         => $api,
                'timestamp'   => $timestamp,
                'sign_method' => $sign_method
            ]);
            //响应格式
            if (rqset('format')) {
                $args['format'] = $format;
            }
            //会话
            $session = rqst('session');
            if (rqset('session')) {
                $args['session'] = $session;
            }
            $allreqs = Request::getInstance()->requests();
            unset($allreqs['sign']);
            if (($extra = array_diff_key($allreqs, $args))) {
                return $this->generateResult($format, [
                    'error' => [
                        'code'   => 40004,
                        'msg'    => __('unknown params@restful'),
                        'params' => array_keys($extra)
                    ]
                ]);
            }
            //开发模式
            $dev = $this->debug;
            if (!$dev) {
                //验签
                $sign1 = $this->signChecker->sign($args, $appSecret, 'sha1', true);
                if ($sign !== $sign1) {
                    return $this->generateResult($format, [
                        'error' => [
                            'code' => 40005,
                            'msg'  => __('invalid sign@restful')
                        ]
                    ]);
                }
            }

            if ($session) {// 启动了session
                (new Session($this->expire))->start($session);
                $clz->sessionId = $session;
            }

            try {
                $this->api = $api;
                fire('restful\callApi', $api, $ctime, $args);
                $clz->setup();
                $rtn = $m->invokeArgs($clz, $dparams);

                return $this->generateResult($format, $rtn);
            } catch (RestException $re) {
                return $this->generateResult($format, [
                    'error' => [
                        'code' => $re->getCode(),
                        'msg'  => $re->getMessage()
                    ]
                ]);
            } catch (HttpException $he) {
                $this->httpout($he->getCode(), $he->getMessage());
            } catch (UnauthorizedException $un) {
                $this->httpout(401);
            } catch (\PDOException $pe) {
                return $this->generateResult($format, [
                    'error' => [
                        'code' => 40006,
                        'msg'  => __('Internal Error - database')
                    ]
                ]);
            } catch (\Exception $e) {
                log_error('[' . $api . '] failed! ' . $e->getMessage() . "\n" . var_export($dparams, true), 'api');

                return $this->generateResult($format, ['error' => ['code' => 40007, 'msg' => $e->getMessage()]]);
            } finally {
                $clz->tearDown();
                fire('restful\endApi', $api, time(), $args);
            }
        }
        // Not Implemented
        $this->httpout(501);

        return null;
    }
388470
public function cachedCompiler($outputDir = '', $debug = false)
    {
        $outputDir = $outputDir ?: CACHE . 'asset_compress' . DS;
        $debug = $debug ?: Configure::read('debug');

        return parent::cachedCompiler($outputDir, $debug);
    }
554213
public function execute($debug = false)
    {
        if (count($this->requests) === 0) {
            return false;
        }

        $curl = curl_init();

        if (!$curl) {
            return false;
        }

        $query = "api_key={$this->key}&api_action=batch&api_requestArray=" . json_encode($this->requests);

        $this->requests = [];

        if ($debug) {
            return $query;
        }

        curl_setopt($curl, CURLOPT_URL, 'https://api.linode.com/');
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);

        $result = curl_exec($curl);

        curl_close($curl);

        $json = json_decode($result, true);

        if (!$json) {
            throw new \RuntimeException('Empty response');
        }

        return $json;
    }
428185
public function boot() {

        if (!$this->isEnabled() ) {
            return;
        }

        $debugbar = $this;
        if ( !$this->isDataPersisted() ) {
            $this->selectStorage($debugbar); // for normal request and debugbar request both
        }
        if ($this->booted) {
            return;
        }
        $this->booted = true;
        if ( isset($_REQUEST['_url']) and $_REQUEST['_url']=='/favicon.ico'
            || isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI']=='/favicon.ico'|| !$this->isEnabled()) {
            return;
        }

        $this->initCollectors();

        $renderer = $this->getJavascriptRenderer();
        $renderer->setIncludeVendors($this->config->get('include_vendors', true));
        $renderer->setBindAjaxHandlerToXHR($this->config->get('capture_ajax', true));
        $renderer->setAjaxHandlerAutoShow($this->config->get('ajax_handler_auto_show', true));
    }
709986
public function debugPrint($debugMsg)
    {
        if ($this->debug) {
            if (is_array($debugMsg) || is_object($debugMsg)) {
                print_r($debugMsg);
            } else {
                echo $debugMsg;
            }

            return true;
        }

        return false;
    }
1168929
final public static function enableSmartyDebug(bool $status)
    {
        $sconfig = new SmartyConfig(FEnv::get("framework.env"));
        FEnv::set("framework.smarty.debug", $sconfig->getSmartyDebug());
    }
1226162
public function initialize($appenv, $debug)
    {
        $this->appenv = $appenv;
        $this->debug = $debug;
        putenv("APP_DEBUG=" . ($debug ? 'true' : 'false'));
        putenv("APP_ENV=" . $this->appenv);
    }
1345361
public function setDebugFile($debugFile) {
		$this->debugFile = $debugFile;
		$this->serializer->setDebugFile($debugFile);
		return $this;
	}
609499
public function loadConfigData()
    {
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
        $this->debug = array_key_exists('debug', $this->config) ? (bool)$this->config['debug'] : FALSE;
    }
359656
public function setDebug($debug)
    {
        $this->debug = strtolower((string) $debug);

        $message = sprintf("Set debug flag to [%s].", $this->debug);
        $this->log($message, Project::MSG_DEBUG);
    }
636378
public function startApp(bool $test = false, string $router = "routerjs")
    {
        $Router = new Router();
        $Middleware = new Middleware();

        // Session
        if (!$test) {
            if (session_status() == PHP_SESSION_NONE) {
                session_start();
            }
        }

        // Dotenv
        $dotenv = Dotenv::create($this->pathFramework);
        $dotenv->load(true);

        // Dev environment
        if (getenv('ENV') == 'dev') {
            error_reporting(-1);
            ini_set('display_errors', 'On');
            ini_set('display_startup_errors', 'On');
            ini_set('log_errors', 'On');
            Profiler::enable();

            // Tracy configuration
            Profiler::start('loadSettings');
            $c = require 'config/tracy.php';
            Profiler::finish('loadSettings');

            Profiler::start('initApp');
            $app = new App($c);
            Profiler::finish('initApp');

            // Container
            Profiler::start('RegisterDependencies');
            $container = $app->getContainer();

            // Session helper
            $container['session'] = function () {
                return new \Adbar\Session("app");
            };

            // Profile twig for tracy
            $container['twig_profile'] = function () {
                return new \Twig_Profiler_Profile();
            };

            // Twig
            $container['view'] = function ($container) {
                if (\Horyzone\Sim\Init::checkCache('CACHE')) {
                    $cache = $this->pathFramework.'storage/cache';
                } else {
                    $cache = false;
                }
                $view = new \Slim\Views\Twig($this->pathFramework.'app/src/Views', [
                    'cache' => $cache,
                    'debug' => true
                ]);

                $router = $container->get('router');
                $uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
                $view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
                $view->addExtension(new \Twig_Extension_Profiler($container['twig_profile']));
                $view->addExtension(new \Twig_Extension_Debug());
                $session = $container['session'];
                if (class_exists("\Symfony\Component\Translation\Translator")) {
                    if (!$session->has('lang')) {
                        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !is_null($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
                            $lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
                            if (file_exists($this->getConfigFolder().'translations/'.$lang.".yml")) {
                                $session->set('lang', $lang);
                            } else {
                                $session->set('lang', $this->langDefault);
                            }
                        } else {
                            $session->set('lang', $this->langDefault);
                        }
                    }
                    $translator = new \Symfony\Component\Translation\Translator(
                        $session->get('lang'),
                        null
                    );
                    $translator->setFallbackLocales([$this->langDefault]);
                    $translator->addLoader('yml', new \Symfony\Component\Translation\Loader\YamlFileLoader());

                    $directory = new \RecursiveDirectoryIterator(
                        $this->getConfigFolder().'translations/',
                        \FilesystemIterator::SKIP_DOTS
                    );
                    $it = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
                    $it->setMaxDepth(1);
                    foreach ($it as $fileinfo) {
                        if ($fileinfo->isFile() && $fileinfo->getFilename() != ".gitkeep") {
                            $lang = explode(".", $fileinfo->getFilename());
                            $translator->addResource(
                                'yml',
                                $this->getConfigFolder().'translations/'.$fileinfo->getFilename(),
                                $lang[0]
                            );
                        }
                    }
                    $view->addExtension(new \Symfony\Bridge\Twig\Extension\TranslationExtension($translator));
                }
                return $view;
            };

            // EntityManager de doctrine
            $container['em'] = function () {
                $connection = [
                    'url' => getenv("DB_DEV"),
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci'
                ];
                $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
                    ['app/src/Entity'],
                    true,
                    $this->pathFramework.'storage/cache/doctrine',
                    null,
                    false
                );
                return \Doctrine\ORM\EntityManager::create($connection, $config);
            };
            require $this->getConfigFolder()."container.php";
            Profiler::finish('RegisterDependencies');

            // Middlewares
            Profiler::start('RegisterMiddlewares');
            $app = $Middleware->chargeMiddleware($app, [
                "app" => $app,
                "container" => $container
            ], $this->getConfigFolder());
            Profiler::finish('RegisterMiddlewares');

            // Router
            Profiler::start('RegisterRoutes');
            // RouterJS
            if (!is_null($router) && class_exists("\Llvdl\Slim\RouterJs")) {
                $app->get('/'.$router, function ($req, $res, $args) {
                    $routerJs = new \Llvdl\Slim\RouterJs($this->router, false);
                    return $routerJs->getRouterJavascriptResponse();
                })->setName($router);
            }
            $app = $Router->chargeRouter($app, [
                "app" => $app,
                "container" => $container
            ], $this->getConfigFolder());
            Profiler::finish('RegisterRoutes');

            // Run app
            if (!$test) {
                Profiler::start('runApp, %s, line %s', basename(__FILE__), __LINE__);
                $app->run();
                Profiler::finish('runApp, %s, line %s', basename(__FILE__), __LINE__);
            }
            return $app;
        } else {
            // Prod environment
            $app = new App();

            // Container
            $container = $app->getContainer();

            // Session helper
            $container['session'] = function () {
                return new \Adbar\Session("app");
            };

            // Twig
            $container['view'] = function ($container) {
                if (\Horyzone\Sim\Init::checkCache('CACHE')) {
                    $cache = $this->pathFramework.'storage/cache';
                } else {
                    $cache = false;
                }
                $view = new \Slim\Views\Twig($this->pathFramework.'app/src/Views', [
                    'cache' => $cache,
                    'debug' => true
                ]);

                $router = $container->get('router');
                $uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
                $view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
                $session = $container['session'];
                if (class_exists("\Symfony\Component\Translation\Translator")) {
                    if (!$session->has('lang')) {
                        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !is_null($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
                            $lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
                            if (file_exists($this->getConfigFolder().'translations/'.$lang.".yml")) {
                                $session->set('lang', $lang);
                            } else {
                                $session->set('lang', $this->langDefault);
                            }
                        } else {
                            $session->set('lang', $this->langDefault);
                        }
                    }
                    $translator = new \Symfony\Component\Translation\Translator(
                        $session->get('lang'),
                        null
                    );
                    $translator->setFallbackLocales([$this->langDefault]);
                    $translator->addLoader('yml', new \Symfony\Component\Translation\Loader\YamlFileLoader());

                    $directory = new \RecursiveDirectoryIterator(
                        $this->getConfigFolder().'translations/',
                        \FilesystemIterator::SKIP_DOTS
                    );
                    $it = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
                    $it->setMaxDepth(1);
                    foreach ($it as $fileinfo) {
                        if ($fileinfo->isFile() && $fileinfo->getFilename() != ".gitkeep") {
                            $lang = explode(".", $fileinfo->getFilename());
                            $translator->addResource(
                                'yml',
                                $this->getConfigFolder().'translations/'.$fileinfo->getFilename(),
                                $lang[0]
                            );
                        }
                    }
                    $view->addExtension(new \Symfony\Bridge\Twig\Extension\TranslationExtension($translator));
                }
                return $view;
            };

            // EntityManager de doctrine
            $container['em'] = function () {
                $connection = [
                    'url' => getenv("DB_PROD"),
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci'
                ];
                $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
                    ['app/src/Entity'],
                    true,
                    $this->pathFramework.'storage/cache/doctrine',
                    null,
                    false
                );
                return \Doctrine\ORM\EntityManager::create($connection, $config);
            };
            require $this->getConfigFolder()."container.php";

            // Middlewares
            $app = $Middleware->chargeMiddleware($app, [
                "app" => $app,
                "container" => $container
            ], $this->getConfigFolder());

            // RouterJS
            if (!is_null($router) && class_exists("\Llvdl\Slim\RouterJs")) {
                $app->get('/'.$router, function ($req, $res, $args) {
                    $routerJs = new \Llvdl\Slim\RouterJs($this->router, false);
                    return $routerJs->getRouterJavascriptResponse();
                })->setName($router);
            }
            // Router
            $app = $Router->chargeRouter($app, [
                "app" => $app,
                "container" => $container
            ], $this->getConfigFolder());
            // Run app
            if (!$test) {
                $app->run();
            }
            return $app;
        }
    }
10655
public function boot()
    {
        $configPath = __DIR__ . '/../config/api-debugger.php';
        $this->publishes([$configPath => config_path('api-debugger.php')]);
        $this->mergeConfigFrom($configPath, 'api-debugger');

        // Register collections only for debug environment.
        $config = $this->app['config'];
        if ($config['api-debugger.enabled']) {
            $this->registerCollections($config['api-debugger.collections']);
        }
    }
1161950
public function my_setDebug($node_name, $bool)
    {
        if ($node_name == getNodeName()) {
            Start::setDebug($bool);
        } else {
            if (array_key_exists($node_name, $this->client)) {
                $this->client[$node_name]->setDebug($bool);
            }
        }
    }
547951
private static function _mainDispatcher($uri, $config) {
        $uriInfo = self::analizeUri();
        $uri = $uriInfo['uri'];
        $uriItems = explode('/', $uri);
        $attributes = [];

        foreach ($config['routes'] as $routePattern => $className) {
            if (preg_match('#' . $routePattern . '#', $uri)) {
                $class = $className;
                $itemCount = count(explode('/', str_replace('\\/', '/', $routePattern)));

                for ($i = 0; $i < $itemCount; $i++) {
                    unset($uriItems[$i]);
                }
                $attributes = array_values($uriItems);
                break;
            }
        }

        if (!$class) {
            $class = self::_getController($uri, 'App\\');
            $classUri = self::_getControllerBaseUri($class);
            
            if(strpos($uri, $classUri) === 0 && strlen($uri) > strlen($classUri)) {
                $attributesUri = substr($uri, strlen($classUri)+1);
                $attributes = explode('/', $attributesUri);
            }
        }
        
        return [
            'class' => self::fixNamespace($class ? $class : self::_getController($uri, 'App\\')),
            'method' => strtolower($_SERVER['REQUEST_METHOD']),
            'attributes' => $attributes
        ];
    }
736632
public function debug($msg = true)
    {
        if (is_bool($msg)) {
            $this->debug = $msg;

            return $this;
        }

        if (is_object($msg)) {
            throw $this->exception('Do not debug objects');
        }

        // The rest of this method is obsolete
        if ((isset($this->debug) && $this->debug)
            || (isset($this->app->debug) && $this->app->debug)
        ) {
            $this->app->outputDebug($this->owner, $msg);
        }
    }