Ejemplo n.º 1
0
 /**
  * Start new or resume existing session.
  */
 public function sessionStart()
 {
     $session_params = session_get_cookie_params();
     // Verify php session id uniqueness
     $cookie_session_id = isset($_COOKIE[session_name()]) ? $_COOKIE[session_name()] : null;
     $session_id = null;
     while ($session_id === null && session_start()) {
         $session_id = session_id();
         if ($cookie_session_id === null) {
             if (isset($_SESSION['logged'])) {
                 Log::notifySlack(':bangbang: Session collision detected');
                 session_write_close();
                 $session_id = null;
             } else {
                 $_SESSION['logged'] = false;
             }
         }
     }
     if (!empty($cookie_session_id)) {
         // Reset lifetime countdown
         setcookie(session_name(), $session_id, time() + $session_params['lifetime'], $session_params['path'], $session_params['domain'], $session_params['secure'], true);
     }
     if (isset($_SESSION['logged'])) {
         if ($_SESSION['logged'] == true && $_SESSION['uID'] != 0) {
             $isLoaded = $this->getFromId($_SESSION['uID']);
             if ($isLoaded && $this->isActive() && !$this->isDeleted()) {
                 $this->logged = true;
             } else {
                 $this->logged = false;
                 $this->sessionDestroy();
             }
         }
     }
     $flashKey = defined('SESSION_FLASH_KEY') && SESSION_FLASH_KEY ? SESSION_FLASH_KEY : '_user_flash_messages';
     $this->flashMessages = isset($_SESSION[$flashKey]) ? $_SESSION[$flashKey] : array();
     $_SESSION[$flashKey] = array();
 }
Ejemplo n.º 2
0
 /**
  * Controller constructor.
  *
  * @param class $router
  */
 public function __construct($router)
 {
     global $_lang, $_user;
     // ToDo: Refactor this lines (csrf check)
     static $csrfChecked = false;
     if (!$csrfChecked && !is_a($this, 'e404') && !in_array($router->url['base'], array('/', '/image_upload/'))) {
         $csrfChecked = true;
         if (!$GLOBALS['_user']->checkCsrfToken()) {
             if (Config::get('slack.NOTIFY_ALL_ERRORS')) {
                 $logCookies = var_export($_COOKIE, true);
             }
             if ($GLOBALS['_user']->checkCsrfTokenExpired()) {
                 $GLOBALS['_user']->setCsrfCookie();
                 $error_code = 408;
             } else {
                 $error_code = 401;
             }
             if (Config::get('slack.NOTIFY_ALL_ERRORS')) {
                 $logData = array();
                 foreach ($_POST as $k => $v) {
                     if (!empty($v) && in_array($k, array('password', 'confirm_password'))) {
                         $logData[$k] = '*****';
                     } else {
                         if (!is_string($v)) {
                             $v = json_encode($v);
                         }
                         $logData[$k] = strlen($v) > 70 ? substr($v, 0, 70) . '...' : $v;
                     }
                 }
                 $logData = var_export($logData, true);
                 \Quaver\App\Model\Log::notifySlack("Error with csrf token in url: {$_SERVER['REQUEST_URI']}; with data {$logData}; and with cookies {$logCookies}");
             }
             // Dispatch the error
             if ($this->getType() === 'ajax' || $this->getType() === 'api') {
                 $this->respondAjaxRequest($error_code, $GLOBALS['_lang']->l('error401-text'));
             } else {
                 $router->dispatch("e{$error_code}");
             }
             exit;
         }
     }
     if ($GLOBALS['_user']->checkCsrfTokenExpired()) {
         $GLOBALS['_user']->setCsrfCookie();
     }
     $this->router = $router;
     $this->url = $router->url;
     // Getting all directories in /template
     $templatesDir = array(Config::get('app.THEME_PATH') . '/View', Config::get('app.THEME_BASE_PATH') . '/View');
     $resourcesDir = array(Config::get('app.THEME_PATH') . '/Resources' => Config::get('app.THEME_URL'), Config::get('app.THEME_BASE_PATH') . '/Resources' => Config::get('app.THEME_BASE_URL'));
     // Create twig loader
     $loader = new \Twig_Loader_Filesystem($templatesDir);
     $twig_options = array();
     if (Config::get('core.TEMPLATE_CACHE')) {
         $twig_options['cache'] = GLOBAL_PATH . '/Cache';
     }
     if (Config::get('core.CACHE_AUTO_RELOAD')) {
         $twig_options['auto_reload'] = true;
     }
     // Create twig object
     $this->twig = new \Twig_Environment($loader, $twig_options);
     // Create a custom filter to debug
     $filter = new \Twig_SimpleFilter('d', function ($string) {
         return d($string);
     });
     $this->twig->addFilter($filter);
     // Create a custom filter to translate strings
     $filter = new \Twig_SimpleFilter('t', function ($string) {
         return $GLOBALS['_lang']->typeFormat($string, 'd');
     });
     $this->twig->addFilter($filter);
     // Create a custom filter to get resources paths
     $filter = new \Twig_SimpleFilter('r', function ($resource, $urlQuery = null) use($resourcesDir) {
         foreach ($resourcesDir as $dir => $url) {
             $exists = file_exists("{$dir}/{$resource}");
             if ($exists || !isset($resourceUrl)) {
                 $resourceUrl = "{$url}/{$resource}" . ($urlQuery ? "?{$urlQuery}" : '');
                 if ($exists) {
                     return $resourceUrl;
                 }
             }
         }
         return $resourceUrl;
     });
     $this->twig->addFilter($filter);
     $function = new \Twig_SimpleFunction('csrf_token', function () {
         return $GLOBALS['_user']->getCsrfToken();
     });
     $this->twig->addFunction($function);
     $function = new \Twig_SimpleFunction('csrf_field', function () {
         $name = Config::get('app.CSRF_FIELD', 'csrf-token');
         $token = $GLOBALS['_user']->getCsrfToken();
         return '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($token) . '">';
     }, array('is_safe' => array('html')));
     $this->twig->addFunction($function);
     // Clear Twig cache
     if (Config::get('core.TEMPLATE_CACHE')) {
         if (isset($this->router->queryString['clearCache'])) {
             $this->twig->clearCacheFiles();
             $url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
             header("Location: {$url}");
             exit;
         }
     }
     // Debugbar Twig
     static $debugBarLoaded = false;
     if (!$debugBarLoaded && Config::get('core.DEBUG_BAR') === true) {
         $debugBarLoaded = true;
         $config = Config::getInstance();
         $twig = new \DebugBar\Bridge\Twig\TraceableTwigEnvironment($this->twig, $config->debugbar['time']);
         $config->debugbar->addCollector(new \DebugBar\Bridge\Twig\TwigCollector($twig));
     }
     // Set main vars
     $this->getGlobalTwigVars();
 }
Ejemplo n.º 3
0
 /**
  * Run Quaver instance.
  */
 public function run()
 {
     try {
         if ($this->router) {
             // Load default routes if not present
             if (!$this->router->routes) {
                 $this->addPath('/', Config::get('app.THEME_PATH') . '/Routes.yml', Config::get('app.THEME_QUAVER'));
             }
             // Load dashboard routes
             if (file_exists(Config::get('app.THEME_BASE_PATH') . '/Routes.yml')) {
                 $this->addPath('/', Config::get('app.THEME_BASE_PATH') . '/Routes.yml', Config::get('app.THEME_BASE_QUAVER'));
             }
             $route = $this->router->getCurrentRoute();
             $this->fixTrailingSlash($route);
         }
         if (Config::get('slack.NOTIFY_ALL_ERRORS')) {
             // This allows to catch memory limit fatal errors.
             $this->tmpBuffer = str_repeat('x', 1024 * 500);
             register_shutdown_function(function () {
                 $this->tmpBuffer = '';
                 Log::notifyLastError();
             });
         }
         if (php_sapi_name() !== 'cli') {
             // Load language
             $GLOBALS['_lang'] = new Lang();
             if (isset($_GET['lang'])) {
                 $lang_slug = substr($_GET['lang'], 0, 3);
                 if (is_object($GLOBALS['_lang']->getFromSlug($lang_slug))) {
                     $GLOBALS['_lang']->setCookie();
                 } else {
                     $GLOBALS['_lang']->getSiteLanguage();
                 }
             } else {
                 $GLOBALS['_lang']->getSiteLanguage();
             }
             // Load user
             $GLOBALS['_user'] = new User();
             $GLOBALS['_user']->sessionStart();
             // Maintenance mode
             if (Config::get('core.MAINTENANCE_MODE') && !$GLOBALS['_user']->isAdmin()) {
                 if ($this->router) {
                     $this->router->dispatch('maintenance');
                 }
             }
         }
         if ($this->router) {
             $this->router->route($route);
         }
     } catch (QException $e) {
         if (Config::get('core.DEV_MODE', false)) {
             throw $e;
         } else {
             $message = 'Error no controlado ' . $e->getMessage() . ' ' . $_SERVER['REQUEST_URI'];
             Log::notifySlack(":bangbang: {$message}");
             if (isset($GLOBALS['_lang']->id) && isset($GLOBALS['_lang']->strings)) {
                 $this->router->dispatch('e500');
             } else {
                 header('HTTP/1.0 500 Internal Server Error');
                 trigger_error("[500] {$url}", E_ERROR);
                 echo 'Algo no ha salido bien. Nuestro equipo técnico está trabajando para solucionar el problema tan pronto como sea posible.';
             }
         }
     }
 }