Beispiel #1
1
 /**
  * Handles a Request to convert it to a Response.
  *
  * When $catch is true, the implementation must catch all exceptions
  * and do its best to convert them to a Response instance.
  *
  * @param Request $request A Request instance
  * @param int     $type    The type of the request
  *                         (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  * @param bool    $catch   Whether to catch exceptions or not
  *
  * @return Response A Response instance
  *
  * @throws \Exception When an Exception occurs during processing
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     try {
         $match = $this->routeMatch;
         if (!$match) {
             $match = $this->router->match($request->getPathInfo());
         }
         if ($match) {
             list($module, $controller, $action) = $this->processRoute($match);
             $request->attributes->add(['_module' => $module, '_controller' => $controller, '_action' => $action]);
             $response = $this->dispatcher->dispatch($match['target'], $match['params']);
         } else {
             $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $request->getPathInfo()]);
             $response->setStatusCode(Response::HTTP_NOT_FOUND);
         }
     } catch (HttpException $e) {
         if (!$catch) {
             throw $e;
         }
         $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]);
         $response->setStatusCode($e->getStatusCode());
     } catch (Exception $e) {
         if (!$catch) {
             throw $e;
         }
         $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     //$response->setMaxAge(300);
     return $response;
 }
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     $match = $this->router->match($request->getPathInfo());
     $route = substr($request->getPathInfo(), strlen(rtrim($this->config['baseDir'], '/')));
     if ($match) {
         $tokenValid = false;
         $jwtCookie = $this->config['jwt']['cookieName'];
         $jwtKey = $this->config['jwt']['key'];
         // check token from cookie
         if ($request->cookies->has($jwtCookie)) {
             $jwt = $request->cookies->get($jwtCookie);
             try {
                 $decoded = JWT::decode($jwt, $jwtKey, ['HS256']);
                 if ($decoded->e > time()) {
                     $tokenValid = true;
                     $this->auth->init($decoded->uid);
                 }
             } catch (\Exception $e) {
                 $tokenValid = false;
                 if (!$catch) {
                     throw $e;
                 }
                 $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>']);
                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
                 return $response;
             }
         }
         $allowed = false;
         $isPublic = false;
         foreach ($this->config['publicArea'] as $publicRoute) {
             if (preg_match('/^' . addcslashes($publicRoute, '/') . '/', $route)) {
                 $isPublic = true;
                 break;
             }
         }
         if ($match['name'] == 'home') {
             $isPublic = true;
         }
         if ($isPublic) {
             if ($route == '/login' && $tokenValid) {
                 return new RedirectResponse($this->router->generate('dashboard'));
             }
             $allowed = true;
         } else {
             $allowed = $tokenValid;
         }
         if ($allowed) {
             $this->app->setRouteMatch($match);
             return $this->app->handle($request, $type, $catch);
         } else {
             $this->flash->warning('Sesi Anda telah habis atau Anda tidak berhak mengakses halaman ini, silakan login terlebih dahulu!');
             $response = $this->dispatcher->dispatch('User#login', []);
             $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
             return $response;
         }
     }
     $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $route]);
     $response->setStatusCode(Response::HTTP_NOT_FOUND);
     return $response;
 }
Beispiel #3
0
 public function testDispatching()
 {
     $dispatcher = new Dispatcher(['index', 'blog', 'projects', '_drafts/blog']);
     $dispatcher->map('blog', 'bloge');
     $dispatcher->alias('projects', 'projectos');
     $dispatcher->ignore('_drafts/blog');
     $this->assertEquals('blog', $dispatcher->dispatch('bloge'));
     $this->assertEquals('projects', $dispatcher->dispatch('projectos'));
     $this->assertEquals('projects', $dispatcher->dispatch('projects'));
     $this->assertEquals('', $dispatcher->dispatch('_drafts/blog'));
     $this->assertEquals('foobar', $dispatcher->dispatch('foobar'));
 }
Beispiel #4
0
 /**
  * Get content from listeners
  */
 public function getAuthenticationContent()
 {
     $content = '';
     if ($this->dispatcher->hasListeners(UserEvents::USER_AUTHENTICATION_CONTENT)) {
         $event = new AuthenticationContentEvent($this->request);
         $this->dispatcher->dispatch(UserEvents::USER_AUTHENTICATION_CONTENT, $event);
         $content = $event->getContent();
         // Remove post_logout session after content has been generated
         $this->request->getSession()->remove('post_logout');
     }
     return $content;
 }
Beispiel #5
0
 /**
  * 应用程序初始化
  */
 public static function start()
 {
     // 加载默认配置
     C(include CONF_PATH . '/convention.php');
     date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     // 环境变量
     putenv('LC_ALL=C');
     putenv('LANG="zh_CN.UTF-8"');
     spl_autoload_register(array('M3d', 'autoload'));
     require_array(array(LIB_PATH . '/Core/Dispatcher.class.php', LIB_PATH . '/Core/Model.class.php', LIB_PATH . '/Core/Action.class.php', LIB_PATH . '/Core/View.class.php', LIB_PATH . '/Core/Tool.class.php', LIB_PATH . '/Core/Plugin.class.php'));
     define('REQUEST_METHOD', strtolower($_SERVER['REQUEST_METHOD']));
     define('IS_GET', REQUEST_METHOD === 'get');
     define('IS_POST', REQUEST_METHOD === 'post');
     define('IS_PUT', REQUEST_METHOD === 'put');
     define('IS_DELETE', REQUEST_METHOD === 'delete');
     define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
     Tool::start();
     Plugin::start();
     // 加载全局配置
     C(include C('M3D_CONF_PATH') . '/config.php');
     // 加载project配置
     C(include PROJECT_PATH . '/conf/config.php');
     Dispatcher::dispatch();
     self::exec();
 }
Beispiel #6
0
 /**
  * 应用程序初始化
  * @access public
  * @return void
  */
 public static function init()
 {
     // 加载动态应用公共文件和配置
     load_ext_file(COMMON_PATH);
     // 定义当前请求的系统常量
     define('NOW_TIME', $_SERVER['REQUEST_TIME']);
     define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
     define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
     define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
     define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
     define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
     define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]) ? true : false);
     // URL调度
     Dispatcher::dispatch();
     if (C('REQUEST_VARS_FILTER')) {
         // 全局安全过滤
         array_walk_recursive($_GET, 'think_filter');
         array_walk_recursive($_POST, 'think_filter');
         array_walk_recursive($_REQUEST, 'think_filter');
     }
     // URL调度结束标签
     Hook::listen('url_dispatch');
     // 日志目录转换为绝对路径
     C('LOG_PATH', realpath(LOG_PATH) . '/' . MODULE_NAME . '/');
     // TMPL_EXCEPTION_FILE 改为绝对地址
     C('TMPL_EXCEPTION_FILE', realpath(C('TMPL_EXCEPTION_FILE')));
     return;
 }
Beispiel #7
0
 /**
  * Run the application.
  *
  * @return void
  */
 public function run()
 {
     $this->filter('before');
     $response = $this->dispatcher->dispatch($this->request, $this->response);
     $this->filter('after');
     $response->finish();
 }
Beispiel #8
0
 /**
  * 应用程序初始化
  *
  * @access public
  * @return void
  */
 public static function init()
 {
     // 加载动态应用公共文件和配置
     load_ext_file(COMMON_PATH);
     // 定义当前请求的系统常量
     define('NOW_TIME', $_SERVER['REQUEST_TIME']);
     define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
     define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
     define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
     define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
     define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
     // URL调度
     Dispatcher::dispatch();
     // URL调度结束标签
     Hook::listen('url_dispatch');
     define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]) ? true : false);
     // 日志目录转换为绝对路径
     C('LOG_PATH', realpath(LOG_PATH) . '/' . MODULE_NAME . '/');
     // TMPL_EXCEPTION_FILE 改为绝对地址
     C('TMPL_EXCEPTION_FILE', realpath(C('TMPL_EXCEPTION_FILE')));
     // 泛域名支持
     if (C('DIV_DOMAIN')) {
         $top_domain = top_domain();
         C('COOKIE_DOMAIN', $top_domain);
         C('SESSION_OPTIONS', array('domain' => $top_domain));
     }
     return;
 }
 /**
  * If RequestURI is proper URI and does not contain QueryParam then it will return proper o/p 
  */
 function testServiceDispatchingUriRawUrlWithoutQueryParam()
 {
     $_SERVER[ODataConstants::HTTPREQUEST_HEADER_METHOD] = ODataConstants::HTTP_METHOD_GET;
     $_SERVER[ODataConstants::HTTPREQUEST_HEADER_PROTOCOL] = ODataConstants::HTTPREQUEST_HEADER_PROTOCOL_HTTP;
     $_SERVER[ODataConstants::HTTPREQUEST_HEADER_HOST] = "localhost:8086";
     $_SERVER[ODataConstants::HTTPREQUEST_HEADER_URI] = "/NorthWind.svc/Customers";
     $_SERVER[ODataConstants::HTTPREQUEST_HEADER_QUERY_STRING] = null;
     try {
         $exceptionThrown = false;
         $dispatcher = new Dispatcher();
         //Service dispatched
         $dispatcher->dispatch();
         $contents = ob_get_contents();
         ob_end_clean();
         $this->assertContains("<feed xml:base=\"http://localhost:8086/NorthWind.svc", $contents);
         $this->assertContains("<id>http://localhost:8086/NorthWind.svc/Customers</id>", $contents);
         $absoluteUri = $dispatcher->getHost()->getAbsoluteRequestUriAsString();
         $this->assertEquals("http://localhost:8086/NorthWind.svc/Customers", $absoluteUri);
         $rawUrl = $dispatcher->getHost()->getWebOperationContext()->IncomingRequest()->getRawUrl();
         $this->assertEquals("http://localhost:8086/NorthWind.svc/Customers", $rawUrl);
     } catch (\Exception $exception) {
         if (ob_get_length()) {
             ob_end_clean();
         }
         $exceptionThrown = true;
         $this->fail('Without Query Params - An unexpected exception  has been thrown:' . $exception->getMessage());
     }
     if (!$exceptionThrown) {
         $this->assertTrue(TRUE);
     }
     $dispatcher->getHost()->getWebOperationContext()->resetWebContextInternal();
 }
Beispiel #10
0
 /**
  * 运行应用实例 入口文件使用的快捷方法
  * @access public
  * @return void
  */
 public static function run()
 {
     // 设置系统时区
     date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     // 加载动态项目公共文件和配置
     load_ext_file();
     // 项目初始化标签
     tag('app_init');
     // URL调度
     Dispatcher::dispatch();
     // 项目开始标签
     tag('app_begin');
     // Session初始化 支持其他客户端
     if (isset($_REQUEST[C("VAR_SESSION_ID")])) {
         session_id($_REQUEST[C("VAR_SESSION_ID")]);
     }
     if (C('SESSION_AUTO_START')) {
         session_start();
     }
     // 记录应用初始化时间
     if (C('SHOW_RUN_TIME')) {
         G('initTime');
     }
     App::exec();
     // 项目结束标签
     tag('app_end');
     // 保存日志记录
     if (C('LOG_RECORD')) {
         Log::save();
     }
     return;
 }
Beispiel #11
0
function _main_()
{
    $ph = new PluginHandler();
    $ph->register(new MyPlugin());
    $sd = new Dispatcher($ph);
    $sd->dispatch();
}
Beispiel #12
0
 /**
  * 应用程序初始化
  * @access public
  * @return void
  */
 public static function init()
 {
     // 加载动态应用公共文件和配置
     load_ext_file(COMMON_PATH);
     // URL调度
     //路由解析,把模块、控制器、方法赋予常量
     //MODULE_NAME = 模块名称
     //CONTROLLER_NAME  控制器
     //ACTION_NAME  方法
     Dispatcher::dispatch();
     // 定义当前请求的系统常量
     define('NOW_TIME', $_SERVER['REQUEST_TIME']);
     define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
     define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
     define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
     define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
     define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
     define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]) ? true : false);
     // URL调度结束标签
     Hook::listen('url_dispatch');
     // 日志目录转换为绝对路径
     C('LOG_PATH', realpath(LOG_PATH) . '/');
     // TMPL_EXCEPTION_FILE 改为绝对地址
     C('TMPL_EXCEPTION_FILE', realpath(C('TMPL_EXCEPTION_FILE')));
     return;
 }
Beispiel #13
0
 /**
  +----------------------------------------------------------
 * 应用程序初始化
  +----------------------------------------------------------
 * @access public
  +----------------------------------------------------------
 * @return void
  +----------------------------------------------------------
 */
 public static function init()
 {
     // 设置系统时区
     date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     // 加载动态项目公共文件和配置
     load_ext_file();
     // URL调度
     Dispatcher::dispatch();
     // 定义当前请求类型常量
     define('IS_GET', $_SERVER['REQUEST_METHOD'] == 'GET' ? true : false);
     define('IS_POST', $_SERVER['REQUEST_METHOD'] == 'POST' ? true : false);
     define('IS_PUT', $_SERVER['REQUEST_METHOD'] == 'PUT' ? true : false);
     define('IS_DELETE', $_SERVER['REQUEST_METHOD'] == 'DELETE' ? true : false);
     define('IS_AJAX', strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]) ? true : false);
     if (defined('GROUP_NAME')) {
         // 加载分组配置文件
         if (is_file(CONF_PATH . GROUP_NAME . '/config.php')) {
             C(include CONF_PATH . GROUP_NAME . '/config.php');
         }
         // 加载分组函数文件
         if (is_file(COMMON_PATH . GROUP_NAME . '/function.php')) {
             include COMMON_PATH . GROUP_NAME . '/function.php';
         }
     }
     // 系统变量安全过滤
     if (C('VAR_FILTERS')) {
         $filters = explode(',', C('VAR_FILTERS'));
         foreach ($filters as $filter) {
             // 全局参数过滤
             $_POST = array_map($filter, $_POST);
             $_GET = array_map($filter, $_GET);
         }
     }
     /* 获取模板主题名称 */
     $templateSet = C('DEFAULT_THEME');
     if (C('TMPL_DETECT_THEME')) {
         // 自动侦测模板主题
         $t = C('VAR_TEMPLATE');
         if (isset($_GET[$t])) {
             $templateSet = $_GET[$t];
         } elseif (cookie('think_template')) {
             $templateSet = cookie('think_template');
         }
         // 主题不存在时仍改回使用默认主题
         if (!is_dir(TMPL_PATH . $templateSet)) {
             $templateSet = C('DEFAULT_THEME');
         }
         cookie('think_template', $templateSet);
     }
     /* 模板相关目录常量 */
     define('THEME_NAME', $templateSet);
     // 当前模板主题名称
     $group = defined('GROUP_NAME') ? GROUP_NAME . '/' : '';
     define('THEME_PATH', TMPL_PATH . $group . (THEME_NAME ? THEME_NAME . '/' : ''));
     define('APP_TMPL_PATH', __ROOT__ . '/' . APP_NAME . (APP_NAME ? '/' : '') . basename(TMPL_PATH) . '/' . $group . (THEME_NAME ? THEME_NAME . '/' : ''));
     C('TEMPLATE_NAME', THEME_PATH . MODULE_NAME . (defined('GROUP_NAME') ? C('TMPL_FILE_DEPR') : '/') . ACTION_NAME . C('TMPL_TEMPLATE_SUFFIX'));
     C('CACHE_PATH', CACHE_PATH . $group);
     return;
 }
Beispiel #14
0
 public function testDispatchNotFoundRoute()
 {
     $dispatcher = new Dispatcher($this->router);
     $response = $dispatcher->dispatch('GET', '/not-found');
     assertThat($response, is(anInstanceOf('Rootr\\Response')));
     assertThat($this->readAttribute($response, 'status'), is(equalTo(404)));
     assertThat($this->readAttribute($response, 'body'), is(equalTo('Not Found')));
 }
 /**
  * Redirects user to action in application with validated response data available as POST data retrievable at
  * $this->request->data` at your app's controller.
  *
  * @param string $url Url in application to dispatch to
  * @param array $data A list with post data
  * @return void
  */
 protected function _dispatch($url, $data)
 {
     $CakeRequest = new CakeRequest($url);
     $CakeRequest->data = $data;
     $Dispatcher = new Dispatcher();
     $Dispatcher->dispatch($CakeRequest, new CakeResponse());
     $this->_stop();
 }
Beispiel #16
0
 public function run()
 {
     try {
         $this->initialize();
         $this->_dispatcher->dispatch();
     } catch (\Exception $e) {
         throw $e;
     }
 }
Beispiel #17
0
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     try {
         $response = $this->app->handle($request, $type, $catch);
         $responseBody = $response->getContent();
         $debugbarHead = $this->debugbarRenderer->renderHead();
         $debugbarBody = $this->debugbarRenderer->render();
         $response->setContent($responseBody . $debugbarHead . $debugbarBody);
         return $response;
     } catch (\Exception $e) {
         if (!$catch) {
             throw $e;
         }
         $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
         return $response;
     }
 }
 /**
  * @desc Redirect the request to the right controller using the url controller mappes list
  * @param UrlControllerMapper[] $url_controller_mappers the url controllers mapper list
  */
 public static function dispatch($url_controller_mappers)
 {
     try {
         $dispatcher = new Dispatcher($url_controller_mappers);
         $dispatcher->dispatch();
     } catch (NoUrlMatchException $ex) {
         self::handle_dispatch_exception($ex);
     }
 }
Beispiel #19
0
 /**
  * Logs every change on a node.
  *
  * @param \Claroline\CoreBundle\Entity\Resource\ResourceNode $node
  */
 public function logChangeSet(ResourceNode $node)
 {
     $uow = $this->om->getUnitOfWork();
     $uow->computeChangeSets();
     $changeSet = $uow->getEntityChangeSet($node);
     if (count($changeSet) > 0) {
         $this->dispatcher->dispatch('log', 'Log\\LogResourceUpdate', array($node, $changeSet));
     }
 }
Beispiel #20
0
 /**
  * @testdox dispatch should render output when only view exists
  */
 public function testDispatchShouldRenderOutputWhenViewExists()
 {
     // create a test view
     Filesystem::createDir('app/views/missing', 0777);
     Filesystem::write('app/views/missing/test.htm.php', 'working');
     $output = Dispatcher::dispatch(array('controller' => 'missing', 'action' => 'test') + self::$defaults);
     // destroy the test view
     Filesystem::delete('app/views/missing');
     $this->assertNotEquals('', $output);
 }
Beispiel #21
0
 /**
  * @param int
  * @return string
  */
 public function stream_read($n)
 {
     for (;;) {
         if (($n = stream_select($r = array($this->dispatcher->getProtocol()->getInputStream()), $w = NULL, $e = NULL, 5)) === FALSE) {
             throw new Error('stream_select() failed');
         }
         if ($n < 1) {
             // is connection alive?
             fflush($this->dispatcher->getProtocol()->getInputStream());
             continue;
         }
         if (feof($this->dispatcher->getProtocol()->getInputStream())) {
             throw new Eof();
         }
         $channel = $this->channel;
         $packet = $this->dispatcher->dispatch(function ($packet) use($channel) {
             list($packet_type) = parse('b', $packet);
             if ($packet_type === SSH_MSG_CHANNEL_DATA) {
                 list($local_channel) = parse('u', $packet);
                 return $local_channel === $channel;
             } else {
                 if ($packet_type === SSH_MSG_CHANNEL_EOF) {
                     return TRUE;
                 }
             }
             return FALSE;
         });
         if ($packet !== NULL) {
             list($packet_type) = parse('b', $packet);
             if ($packet_type === SSH_MSG_CHANNEL_DATA) {
                 list($local_channel, $data) = parse('us', $packet);
                 return $data;
             } else {
                 if ($packet_type === SSH_MSG_CHANNEL_EOF) {
                     $this->eof = TRUE;
                     return "";
                 } else {
                     throw new Error('Bad packet received from dispatcher.');
                 }
             }
         }
     }
 }
Beispiel #22
0
 /**
 +----------------------------------------------------------
 * 应用程序初始化
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @return void
 +----------------------------------------------------------
 */
 public static function init()
 {
     // 设置系统时区
     date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     // 加载动态项目公共文件和配置
     load_ext_file();
     // URL调度
     Dispatcher::dispatch();
     if (defined('GROUP_NAME')) {
         // 加载分组配置文件
         if (is_file(CONF_PATH . GROUP_NAME . '/config.php')) {
             C(include CONF_PATH . GROUP_NAME . '/config.php');
         }
         // 加载分组函数文件
         if (is_file(COMMON_PATH . GROUP_NAME . '/function.php')) {
             include COMMON_PATH . GROUP_NAME . '/function.php';
         }
     }
     // 系统变量安全过滤
     if (C('REQUEST_VARS_FILTER')) {
         // 全局安全过滤
         array_walk_recursive($_GET, 'think_filter');
         array_walk_recursive($_POST, 'think_filter');
         array_walk_recursive($_REQUEST, 'think_filter');
     }
     /* 获取模板主题名称 */
     $templateSet = C('DEFAULT_THEME');
     if (C('TMPL_DETECT_THEME')) {
         // 自动侦测模板主题
         $t = C('VAR_TEMPLATE');
         if (isset($_GET[$t])) {
             $templateSet = $_GET[$t];
         } elseif (cookie('think_template')) {
             $templateSet = cookie('think_template');
         }
         // 主题不存在时仍改回使用默认主题
         if (!is_dir(TMPL_PATH . $templateSet)) {
             $templateSet = C('DEFAULT_THEME');
         }
         cookie('think_template', $templateSet);
     }
     /* 模板相关目录常量 */
     define('THEME_NAME', $templateSet);
     // 当前模板主题名称
     $group = defined('GROUP_NAME') ? GROUP_NAME . '/' : '';
     define('THEME_PATH', TMPL_PATH . $group . (THEME_NAME ? THEME_NAME . '/' : ''));
     define('APP_TMPL_PATH', __ROOT__ . '/' . APP_NAME . (APP_NAME ? '/' : '') . basename(TMPL_PATH) . '/' . $group . (THEME_NAME ? THEME_NAME . '/' : ''));
     //网站公共文件目录
     define('WEB_PUBLIC_PATH', __ROOT__ . '/Public');
     //项目公共文件目录
     define('APP_PUBLIC_PATH', APP_TMPL_PATH . 'Public');
     C('TEMPLATE_NAME', THEME_PATH . MODULE_NAME . (defined('GROUP_NAME') ? C('TMPL_FILE_DEPR') : '/') . ACTION_NAME . C('TMPL_TEMPLATE_SUFFIX'));
     C('CACHE_PATH', CACHE_PATH . $group);
     return;
 }
Beispiel #23
0
 public function handleErrorsAsException($error_types = null)
 {
     $error_types = $error_types ?: E_ALL | E_STRICT;
     set_error_handler(function ($errno, $errstr, $errfile, $errline) {
         if (error_reporting() !== 0) {
             throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
         }
     }, $error_types);
     if (0 !== ($error_types & E_ERROR)) {
         register_shutdown_function(function () {
             $error = error_get_last();
             if ($error["type"] == E_ERROR) {
                 ob_clean();
                 $this->manageError(new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']));
                 $this->_dispatcher->dispatch($this->_router, $this->_framework->getView(), $this->_framework);
             }
         });
     }
     return $this;
 }
 public static function init()
 {
     // 设置系统时区 PHP5支持
     if (function_exists('date_default_timezone_set')) {
         date_default_timezone_set(config('DEFAULT_TIMEZONE'));
     }
     set_error_handler(array('App', 'appError'));
     set_exception_handler(array('App', 'appException'));
     loadCore('Trace');
     loadCore('Dispatcher');
     Dispatcher::dispatch();
     Trace::write();
 }
Beispiel #25
0
function execute_request(Request $request, Response $response, $dispatchPath)
{
    $dispatchList = (require $dispatchPath);
    $result = Dispatcher::dispatch($dispatchList, $request);
    if ($result[0] === false) {
        $response->set_status_code(404);
        $body = ErrorHandler::handleError(404, $request, 'Resource was not found');
        $response->write($body);
        return $response;
    } else {
        return \PHPMachine\DecisionCore::handleRequest($result[0], $request, $response);
    }
}
Beispiel #26
0
 /**
  * Intercept redirect and render amf response
  *
  * @param object $controller
  * @return void
  */
 function beforeRedirect(&$controller, $url, $status = null, $exit = true)
 {
     if ($controller->isAmf && $this->autoRedirect) {
         if (is_array($url)) {
             $url = Router::url($url);
         }
         $Dispatcher = new Dispatcher();
         $Dispatcher->dispatch($url);
         if ($exit) {
             exit;
         }
     }
 }
 /**
 +----------------------------------------------------------
 * 应用程序初始化
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @return void
 +----------------------------------------------------------
 */
 public static function init()
 {
     // 设定错误和异常处理
     set_error_handler(array('App', 'appError'));
     set_exception_handler(array('App', 'appException'));
     //[RUNTIME]
     // 检查项目是否编译过
     // 在部署模式下会自动在第一次执行的时候编译项目
     if (defined('RUNTIME_MODEL')) {
         // 运行模式无需载入项目编译缓存
     } elseif (is_file(RUNTIME_PATH . '~' . APP_CACHE_NAME . '.php') && (!is_file(CONFIG_PATH . 'config.php') || filemtime(RUNTIME_PATH . '~' . APP_CACHE_NAME . '.php') > filemtime(CONFIG_PATH . 'config.php'))) {
         // 直接读取编译后的项目文件
         C(include RUNTIME_PATH . '~' . APP_CACHE_NAME . '.php');
     } else {
         // 预编译项目
         App::build();
     }
     //[/RUNTIME]
     // 设置系统时区 PHP5支持
     if (function_exists('date_default_timezone_set')) {
         date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     }
     // 允许注册AUTOLOAD方法
     if (C('APP_AUTOLOAD_REG') && function_exists('spl_autoload_register')) {
         spl_autoload_register(array('Think', 'autoload'));
     }
     // Session初始化
     if (C('SESSION_AUTO_START')) {
         session_start();
     }
     // URL调度
     Dispatcher::dispatch();
     // 加载模块配置文件
     if (is_file(CONFIG_PATH . strtolower(MODULE_NAME) . '_config.php')) {
         C(include CONFIG_PATH . strtolower(MODULE_NAME) . '_config.php');
     }
     // 系统检查
     App::checkLanguage();
     //语言检查
     App::checkTemplate();
     //模板检查
     // 开启静态缓存
     if (C('HTML_CACHE_ON')) {
         HtmlCache::readHTMLCache();
     }
     // 项目初始化标签
     if (C('APP_PLUGIN_ON')) {
         tag('app_init');
     }
     return;
 }
Beispiel #28
0
 public static function dispatch(Request $request = null, Response $response = null)
 {
     if ($request === null) {
         $request = new Request();
     }
     if ($response === null) {
         $response = new Response();
     }
     $app = self::instance();
     $app->setRequest($request);
     $dispatcher = new Dispatcher(APP_CONTROLLERS_DIR);
     $dispatcher->dispatch($request, $response);
     $response->send();
 }
Beispiel #29
0
 public function dispatch(Route $route)
 {
     $protoView = $this->getBootstrap()->getResource("view") ? $this->getBootstrap()->getResource("view") : new View();
     $controllerPath = $this->getControllerPath();
     $router = $this->_router;
     $request = $this->_request;
     $protoView->addHelper("pull", function ($uri) use($controllerPath, $router, $request) {
         $request = clone $request;
         $request->setUri($uri);
         $routeObj = $router->match($request);
         $controllerClassName = $routeObj->getControllerName() . "Controller";
         $action = $routeObj->getActionName() . "Action";
         $classPath = realpath($controllerPath . DIRECTORY_SEPARATOR . $controllerClassName . ".php");
         if (file_exists($classPath)) {
             require_once $classPath;
             $controller = new $controllerClassName();
             $controller->setParams($routeObj->getParams());
             if (method_exists($controller, $action)) {
                 ob_start();
                 $controller->init();
                 $data = $controller->{$action}();
                 ob_end_clean();
                 return $data;
             } else {
                 throw new RuntimeException("Pull operation {$routeObj->getControllerName()} - {$routeObj->getActionName()} failed.", 404);
             }
         } else {
             throw new RuntimeException("Pull operation {$routeObj->getControllerName()} - {$routeObj->getActionName()} failed.", 404);
         }
     });
     $dispatcher = new Dispatcher($protoView);
     $dispatcher->setRouter($this->_router);
     $dispatcher->setRequest($this->_request);
     $dispatcher->setEventManager($this->getEventManager());
     $dispatcher->setBootstrap($this->_bootstrap);
     $dispatcher->setControllerPath($this->getControllerPath());
     try {
         $this->_page = $dispatcher->dispatch($route);
     } catch (Exception $e) {
         $errorRoute = new Route();
         $errorRoute->addParams(array('exception' => $e));
         $dispatcher->clearHeaders();
         $dispatcher->addHeader("", "", 404);
         $errorRoute->setControllerName("error");
         $errorRoute->setActionName("error");
         $this->_page = $dispatcher->dispatch($errorRoute);
     }
     return array('headers' => $dispatcher->getHeaders());
 }
Beispiel #30
0
 /**
  * 应用程序初始化
  * @access public
  * @return void
  */
 public static function init()
 {
     // 页面压缩输出支持
     if (C('OUTPUT_ENCODE')) {
         $zlib = ini_get('zlib.output_compression');
         if (empty($zlib)) {
             ob_start('ob_gzhandler');
         }
     }
     // 设置系统时区
     date_default_timezone_set(C('DEFAULT_TIMEZONE'));
     // 加载动态项目公共文件和配置
     load_ext_file();
     // URL调度
     Dispatcher::dispatch();
     // 定义当前请求的系统常量
     define('NOW_TIME', $_SERVER['REQUEST_TIME']);
     define('REQUEST_METHOD', $_SERVER['REQUEST_METHOD']);
     define('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
     define('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
     define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false);
     define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false);
     define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]) ? true : false);
     // URL调度结束标签
     tag('url_dispatch');
     // 系统变量安全过滤
     if (C('VAR_FILTERS')) {
         $filters = explode(',', C('VAR_FILTERS'));
         foreach ($filters as $filter) {
             // 全局参数过滤
             array_walk_recursive($_POST, $filter);
             array_walk_recursive($_GET, $filter);
         }
     }
     if (C('REQUEST_VARS_FILTER')) {
         // 全局安全过滤
         array_walk_recursive($_GET, 'think_filter');
         array_walk_recursive($_POST, 'think_filter');
         array_walk_recursive($_REQUEST, 'think_filter');
     }
     if (cookie('think_template') == '' && check_wap()) {
         cookie('think_template', 'w3g');
     }
     C('LOG_PATH', realpath(LOG_PATH) . '/');
     //动态配置 TMPL_EXCEPTION_FILE,改为绝对地址
     C('TMPL_EXCEPTION_FILE', realpath(C('TMPL_EXCEPTION_FILE')));
     return;
 }