Ejemplo n.º 1
0
 /**
  * Check for the user session
  *
  * @param  Application $application
  * @return void
  */
 public static function check(Application $application)
 {
     $sess = $application->getService('session');
     $action = $application->router()->getRouteMatch()->getAction();
     $route = $application->router()->getRouteMatch()->getRoute();
     $isInstall = substr($route, 0, strlen(APP_URI . '/install')) == APP_URI . '/install';
     // Special install check
     if (isset($sess->app_uri) && strpos($_SERVER['REQUEST_URI'], 'install/config') !== false) {
         if (BASE_PATH . APP_URI == BASE_PATH . $sess->app_uri && $application->config()['db']) {
             Response::redirect(BASE_PATH . APP_URI . '/install/user');
             exit;
         }
     }
     // If logged in, and a system URL, redirect to dashboard
     if (isset($sess->user) && ($action == 'login' || $action == 'register' || $action == 'verify' || $action == 'forgot' || $isInstall)) {
         Response::redirect(BASE_PATH . (APP_URI != '' ? APP_URI : '/'));
         exit;
         // Else, if NOT logged in and NOT a system URL, redirect to login
     } else {
         if (!isset($sess->user) && ($action != 'login' && $action != 'register' && !$isInstall && $action != 'unsubscribe' && $action != 'verify' && $action != 'forgot' && null !== $action) && substr($route, 0, strlen(APP_URI)) == APP_URI) {
             Response::redirect(BASE_PATH . APP_URI . '/login');
             exit;
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Check if the application requires an SSL connection
  *
  * @param  Application $application
  * @return void
  */
 public static function check(Application $application)
 {
     if ($application->config()['force_ssl'] && $_SERVER['SERVER_PORT'] != '443') {
         Response::redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
         exit;
     }
 }
 /**
  * Session remove method
  *
  * @return void
  */
 public function remove()
 {
     if ($this->request->isPost()) {
         $session = new Model\UserSession();
         $session->remove($this->request->getPost());
     }
     Response::redirect($this->request->getBasePath() . '?removed=' . time());
 }
Ejemplo n.º 4
0
 /**
  * Config index method
  *
  * @return void
  */
 public function index()
 {
     $this->prepareView('index.phtml', array('assets' => $this->project->getAssets(), 'acl' => $this->project->getService('acl'), 'phireNav' => $this->project->getService('phireNav')));
     $this->view->set('title', $this->view->i18n->__('Configuration'));
     $config = new Model\Config(array('acl' => $this->project->getService('acl')));
     if ($this->request->isPost()) {
         $config->update($this->request->getPost());
         Response::redirect($this->request->getBasePath() . '?saved=' . time());
     } else {
         $config->getAll();
         $this->view->merge($config->getData());
         $this->send();
     }
 }
Ejemplo n.º 5
0
 public function post()
 {
     $view = new View($this->viewPath . '/post.phtml');
     $view->title = 'Post Comment';
     $view->form = new Form\Post();
     if ($this->request->isPost()) {
         $view->form->addFilter('strip_tags')->addFilter('htmlentities', [ENT_QUOTES, 'UTF-8'])->setFieldValues($this->request->getPost());
         if ($view->form->isValid()) {
             $view->form->clearFilters()->addFilter('html_entity_decode', [ENT_QUOTES, 'UTF-8']);
             $post = new Model\Post();
             $post->save($view->form->getFields());
             Response::redirect('/');
             exit;
         }
     }
     $this->response->setBody($view->render());
     $this->response->send();
 }
Ejemplo n.º 6
0
 /**
  * Check if the user session is allowed with the ACL service
  *
  * @param  Application $application
  * @return void
  */
 public static function check(Application $application)
 {
     $application->module('app')->initAcl();
     $sess = $application->getService('session');
     $acl = $application->getService('acl');
     if (isset($sess->user) && isset($sess->user->role) && $acl->hasRole($sess->user->role)) {
         // Get routes with slash options
         $route = $application->router()->getRouteMatch()->getRoute();
         $routes = $application->router()->getRouteMatch()->getRoutes();
         if (isset($routes[$route]) && isset($routes[$route]['acl']) && isset($routes[$route]['acl']['resource'])) {
             $resource = $routes[$route]['acl']['resource'];
             $permission = isset($routes[$route]['acl']['permission']) ? $routes[$route]['acl']['permission'] : null;
             if (!$acl->isAllowed($sess->user->role, $resource, $permission)) {
                 Response::redirect('/');
                 exit;
             }
         }
     }
 }
Ejemplo n.º 7
0
 /**
  * Check for the member session
  *
  * @param  Application $application
  * @return void
  */
 public static function sessionCheck(Application $application)
 {
     if (null !== $application->router()->getController() && $application->router()->getController() instanceof \Phire\Members\Controller\IndexController) {
         $sess = $application->getService('session');
         $action = $application->router()->getRouteMatch()->getAction();
         $route = $application->router()->getRouteMatch()->getRoute();
         $memberUri = $application->router()->getController()->getMemberUri();
         // If logged in, and a member URL, redirect to dashboard
         if (isset($sess->member) && ($action == 'login' || $action == 'register' || $action == 'verify' || $action == 'forgot')) {
             Response::redirect(BASE_PATH . $memberUri);
             exit;
             // Else, if NOT logged in and NOT a system URL, redirect to login
         } else {
             if (!isset($sess->member) && ($action != 'login' && $action != 'register' && $action != 'unsubscribe' && $action != 'verify' && $action != 'forgot' && null !== $action) && substr($route, 0, strlen($memberUri)) == $memberUri) {
                 Response::redirect(BASE_PATH . $memberUri . '/login');
                 exit;
             }
         }
     }
 }
Ejemplo n.º 8
0
 /**
  * Check for the user session
  *
  * @param  Application $application
  * @return void
  */
 public static function check(Application $application)
 {
     $sess = $application->getService('session');
     $action = $application->router()->getRouteMatch()->getAction();
     if (isset($sess->user) && isset($sess->user->sess_id) && !isset(Table\UserSessions::findById($sess->user->sess_id)->id)) {
         $user = new Model\User();
         $user->logout($sess);
         unset($sess->user);
         $sess->setRequestValue('expired', true);
         Response::redirect('/login');
         exit;
     } else {
         if (isset($sess->user) && ($action == 'login' || $action == 'forgot' || $action == 'verify')) {
             Response::redirect('/');
             exit;
         } else {
             if (!isset($sess->user) && $action != 'login' && $action != 'forgot' && $action != 'verify') {
                 Response::redirect('/login');
                 exit;
             }
         }
     }
 }
Ejemplo n.º 9
0
 /**
  * Redirect response
  *
  * @param  string $url
  * @param  string $code
  * @param  string $version
  * @return void
  */
 public function redirect($url, $code = '302', $version = '1.1')
 {
     $this->application->trigger('app.send.pre', ['controller' => $this]);
     $this->application->trigger('app.send.post', ['controller' => $this]);
     Response::redirect($url, $code, $version);
     exit;
 }
Ejemplo n.º 10
0
 /**
  * Process action method
  *
  * @return void
  */
 public function process()
 {
     $module = new Model\Module();
     $module->process($this->request->getPost(), $this->services);
     if (null !== $this->request->getPost('rm_modules')) {
         $this->sess->setRequestValue('removed', true);
     } else {
         $this->sess->setRequestValue('saved', true);
     }
     \Pop\Http\Response::redirect(BASE_PATH . APP_URI . '/modules');
     exit;
 }
Ejemplo n.º 11
0
 /**
  * Site remove method
  *
  * @return void
  */
 public function remove()
 {
     // Loop through and delete the fields
     if ($this->request->isPost()) {
         $site = new Model\Site();
         $site->remove($this->request->getPost());
     }
     Response::redirect($this->request->getBasePath() . '?removed=' . time());
 }
Ejemplo n.º 12
0
 /**
  * Install initial user method
  *
  * @return void
  */
 public function user()
 {
     // If the system is installed
     if (DB_INTERFACE != '' && DB_NAME != '' && !isset($this->sess->config)) {
         Response::redirect(BASE_PATH . APP_URI);
         // Else, if the initial install screen or config isn't complete
     } else {
         if (DB_INTERFACE == '' && DB_NAME == '') {
             if (isset($this->sess->config)) {
                 Response::redirect(BASE_PATH . (isset($this->sess->app_uri) ? $this->sess->app_uri : APP_URI) . '/install/config?lang=' . $_GET['lang']);
             } else {
                 Response::redirect(BASE_PATH . (isset($this->sess->app_uri) ? $this->sess->app_uri : APP_URI) . '/install?lang=' . $_GET['lang']);
             }
             // Else, install the first system user
         } else {
             $user = new Model\User(array('title' => $this->i18n->__('User Setup')));
             $form = new Form\User($this->request->getBasePath() . $this->request->getRequestUri() . '?lang=' . $this->i18n->getLanguage() . '_' . $this->i18n->getLocale(), 'post', 2001, true);
             if ($this->request->isPost()) {
                 $form->setFieldValues($this->request->getPost(), array('strip_tags' => null, 'htmlentities' => array(ENT_QUOTES, 'UTF-8')));
                 if ($form->isValid()) {
                     $user->save($form, $this->project->module('Phire'));
                     $newUser = Table\Users::findById($user->id);
                     if (isset($newUser->id)) {
                         $newUser->site_ids = serialize(array(0));
                         $newUser->created = date('Y-m-d H:i:s');
                         $newUser->update();
                     }
                     $ext = new Model\Extension(array('acl' => $this->project->getService('acl')));
                     $ext->getModules($this->project);
                     if (count($ext->new) > 0) {
                         $ext->installModules();
                     }
                     $user->set('form', '        <p style="text-align: center; margin: 50px 0 0 0; line-height: 1.8em; font-size: 1.2em;">' . $this->i18n->__('Thank you. The system has been successfully installed.') . '<br />' . $this->i18n->__('You can now log in %1here%2 or view the home page %3here%4.', array('<a href="' . BASE_PATH . APP_URI . '/login">', '</a>', '<a href="' . BASE_PATH . '/" target="_blank">', '</a>')) . '</p>' . PHP_EOL);
                     Model\Install::send($form);
                     unset($this->sess->config);
                     unset($this->sess->app_uri);
                     $this->view = View::factory($this->viewPath . '/user.phtml', $user->getData());
                     $this->view->set('i18n', $this->i18n);
                     $this->send();
                 } else {
                     $user->set('form', $form);
                     $this->view = View::factory($this->viewPath . '/user.phtml', $user->getData());
                     $this->view->set('i18n', $this->i18n);
                     $this->send();
                 }
             } else {
                 $user->set('form', $form);
                 $this->view = View::factory($this->viewPath . '/user.phtml', $user->getData());
                 $this->view->set('i18n', $this->i18n);
                 $this->send();
             }
         }
     }
 }
Ejemplo n.º 13
0
 /**
  * Role remove method
  *
  * @return void
  */
 public function remove()
 {
     // Loop through and delete the roles
     if ($this->request->isPost()) {
         $role = new Model\UserRole();
         $role->remove($this->request->getPost());
     }
     Response::redirect($this->request->getBasePath() . '?removed=' . time());
 }
Ejemplo n.º 14
0
 /**
  * Event-based auth check
  *
  * @param  \Pop\Mvc\Router $router
  * @return mixed
  */
 public static function auth($router)
 {
     $sess = Session::getInstance();
     $site = Sites::getSite();
     $basePath = $site->base_path;
     $resource = $router->getControllerClass();
     $permission = $router->getAction();
     $isFrontController = substr_count($resource, '\\') == 2;
     // Check for the resource and permission
     if (!$isFrontController && $resource != 'Phire\\Controller\\Phire\\Install\\IndexController') {
         if (null === $router->project()->getService('acl')->getResource($resource)) {
             if ($resource != 'Phire\\Controller\\Phire\\IndexController') {
                 $router->project()->getService('acl')->addResource($resource);
             } else {
                 $resource = null;
                 $permission = null;
             }
         }
         if (null !== $permission && null !== $resource && !method_exists($resource, $permission)) {
             $permission = 'error';
         }
         if ($router->controller()->getRequest()->getPath(0) == 'index' || $router->controller()->getRequest()->getPath(0) == 'add') {
             $permId = $router->controller()->getRequest()->getPath(1);
             if (null !== $permId && is_numeric($permId)) {
                 $permission .= '_' . $permId;
             }
         }
         // Get the user URI
         $uri = APP_URI == '' || strtolower($router->project()->getService('acl')->getType()->type) == 'user' ? APP_URI : '/' . strtolower($router->project()->getService('acl')->getType()->type);
         // If reset password flag is set
         if (isset($sess->reset_pwd) && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/profile' && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/login' && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/logout') {
             \Pop\Http\Response::redirect($basePath . $uri . '/profile');
             return \Pop\Event\Manager::KILL;
             // If not logged in for unsubscribe and required, redirect to the system login
         } else {
             if ($_SERVER['REQUEST_URI'] == $basePath . $uri . '/unsubscribe' && $router->project()->getService('acl')->getType()->unsubscribe_login && !$router->project()->getService('acl')->isAuth($resource, $permission)) {
                 \Pop\Http\Response::redirect($basePath . $uri . '/login');
                 return \Pop\Event\Manager::KILL;
                 // Else, if not logged in or allowed, redirect to the system login
             } else {
                 if ($_SERVER['REQUEST_URI'] != $basePath . $uri . '/login' && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/register' && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/forgot' && $_SERVER['REQUEST_URI'] != $basePath . $uri . '/unsubscribe' && substr($_SERVER['REQUEST_URI'], 0, strlen($basePath . $uri . '/json')) != $basePath . $uri . '/json' && strpos($_SERVER['REQUEST_URI'], $basePath . $uri . '/verify') === false && !$router->project()->getService('acl')->isAuth($resource, $permission)) {
                     \Pop\Http\Response::redirect($basePath . $uri . '/login');
                     return \Pop\Event\Manager::KILL;
                     // Else, if logged in and allowed, and a system access URI, redirect back to the system
                 } else {
                     if (($_SERVER['REQUEST_URI'] == $basePath . $uri . '/login' || $_SERVER['REQUEST_URI'] == $basePath . $uri . '/register' || $_SERVER['REQUEST_URI'] == $basePath . $uri . '/forgot') && $router->project()->getService('acl')->isAuth($resource, $permission)) {
                         \Pop\Http\Response::redirect($basePath . ($uri == '' ? '/' : $uri));
                         return \Pop\Event\Manager::KILL;
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 15
0
 /**
  * Modules method
  *
  * @return void
  */
 public function modules()
 {
     $this->prepareView('modules.phtml', array('assets' => $this->project->getAssets(), 'acl' => $this->project->getService('acl'), 'phireNav' => $this->project->getService('phireNav')));
     $ext = new Model\Extension(array('acl' => $this->project->getService('acl')));
     $ext->getModules($this->project);
     if (null === $this->request->getPath(1)) {
         $this->view->set('title', $this->view->i18n->__('Extensions') . ' ' . $this->view->separator . ' ' . $this->view->i18n->__('Modules'));
         $this->view->merge($ext->getData());
         $this->send();
     } else {
         if (null !== $this->request->getPath(1) && $this->request->getPath(1) == 'install' && count($ext->new) > 0) {
             $ext->installModules();
             if (null !== $ext->error) {
                 $this->view->set('title', $this->view->i18n->__('Extensions') . ' ' . $this->view->separator . ' ' . $this->view->i18n->__('Modules') . ' ' . $this->view->separator . ' ' . $this->view->i18n->__('Installation Error'));
                 $this->view->merge($ext->getData());
                 $this->send();
             } else {
                 Response::redirect($this->request->getBasePath() . '/modules?saved=' . time());
             }
         } else {
             if ($this->request->isPost() && null !== $this->request->getPath(1) && $this->request->getPath(1) == 'process') {
                 $ext->processModules($this->request->getPost());
                 Response::redirect($this->request->getBasePath() . '/modules?saved=' . time());
             } else {
                 Response::redirect($this->request->getBasePath() . '/modules');
             }
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * Error handler
  *
  * @param  \Exception $exception
  * @return void
  */
 public function error(\Exception $exception)
 {
     if ($exception instanceof \Phire\Exception && $exception->isInstallError()) {
         Response::redirect(BASE_PATH . APP_URI . '/install');
         exit;
     }
     // Load assets, if they haven't been loaded already
     $this->loadAssets($_SERVER['DOCUMENT_ROOT'] . APP_PATH . '/data/themes/default', 'default');
     $this->loadAssets(__DIR__ . '/../data/assets', 'phire');
     sort($this->assets['js']);
     sort($this->assets['css']['link']);
     sort($this->assets['css']['import']);
     // Load any custom/override assets
     $this->loadAssets(CONTENT_ABS_PATH . '/phire/assets', 'phire-custom', true);
     $view = new View(__DIR__ . '/../view/phire/exception.phtml');
     $view->title = 'Application Error';
     $view->systemTitle = 'Phire CMS';
     $view->assets = $this->assets;
     $view->phireUri = BASE_PATH . APP_URI;
     $view->basePath = BASE_PATH;
     $view->base_path = BASE_PATH;
     $view->contentPath = BASE_PATH . CONTENT_PATH;
     $view->content_path = BASE_PATH . CONTENT_PATH;
     $view->message = htmlentities(strip_tags($exception->getMessage()), ENT_QUOTES, 'UTF-8');
     $response = new Response();
     $response->setBody((string) $view);
     $response->send();
 }
Ejemplo n.º 17
0
 /**
  * Verify method
  *
  * @param  string $redirect
  * @return void
  */
 public function verify($redirect = null)
 {
     // If the required user ID and hash is submitted
     if (null !== $this->request->getPath(1) && null !== $this->request->getPath(2)) {
         $this->prepareView('verify.phtml', array('assets' => $this->project->getAssets(), 'acl' => $this->project->getService('acl'), 'phireNav' => $this->project->getService('phireNav'), 'phire' => new Model\Phire(), 'title' => 'Verify'));
         $this->view->set('title', $this->view->i18n->__('Verify'));
         $user = new Model\User();
         $user->getById($this->request->getPath(1));
         // If the user was found, verify and save
         if (isset($user->id) && sha1($user->email) == $this->request->getPath(2)) {
             $user->verify();
             $message = 'Thank you. Your email has been verified.';
             // Else, render failure message
         } else {
             $message = 'Sorry. That email could not be verified.';
         }
         if (null !== $redirect) {
             Response::redirect($redirect);
         } else {
             $this->view->set('message', $this->view->i18n->__($message));
             $this->send();
         }
         // Else, redirect
     } else {
         Response::redirect($this->request->getBasePath());
     }
 }
Ejemplo n.º 18
0
 /**
  * Logout method
  *
  * @param  boolean $redirect
  * @return void
  */
 public function logout($redirect = true)
 {
     // Destroy the session database entry
     if (null !== $this->sess->user->sess_id) {
         $session = Table\UserSessions::findById($this->sess->user->sess_id);
         if (isset($session->id)) {
             $session->delete();
         }
     }
     // Destroy the session object.
     unset($this->sess->user);
     // Delete the phire cookie
     $path = BASE_PATH . APP_URI;
     if ($path == '') {
         $path = '/';
     }
     $cookie = Cookie::getInstance(array('path' => $path));
     $cookie->delete('phire');
     if ($redirect) {
         $uri = $this->basePath == '' ? '/' : $this->basePath;
         \Pop\Http\Response::redirect($uri);
     }
 }
Ejemplo n.º 19
0
 /**
  * Redirect response
  *
  * @param  string $url
  * @param  string $code
  * @param  string $version
  * @return void
  */
 public function redirect($url, $code = '302', $version = '1.1')
 {
     Response::redirect($url, $code, $version);
     exit;
 }
Ejemplo n.º 20
0
 /**
  * Export method
  *
  * @return void
  */
 public function export()
 {
     $user = new Model\User();
     $user->getExport($this->request->getPath(1), $this->request->getQuery('sort'), $this->request->getQuery('page'));
     if (isset($user->userRows[0])) {
         $userRows = $user->userRows;
         foreach ($userRows as $key => $value) {
             foreach ($value as $k => $v) {
                 if (is_array($v)) {
                     $userRows[$key]->{$k} = implode('|', $v);
                 }
             }
         }
         \Pop\Data\Data::factory($userRows)->writeData($_SERVER['HTTP_HOST'] . '_' . $user->userType . '_' . date('Y-m-d') . '.csv', true, true);
     } else {
         Response::redirect($this->request->getBasePath() . '/index/' . $this->request->getPath(1));
     }
 }
Ejemplo n.º 21
0
 /**
  * Group remove method
  *
  * @return void
  */
 public function remove()
 {
     // Loop through and delete the groups
     if ($this->request->isPost()) {
         $group = new Model\FieldGroup();
         $group->remove($this->request->getPost());
     }
     Response::redirect($this->request->getBasePath() . '?removed=' . time());
 }
Ejemplo n.º 22
0
 /**
  * Login and track session
  *
  * @param  AbstractController $controller
  * @param  Application        $application
  * @return void
  */
 public static function login(AbstractController $controller, Application $application)
 {
     $sess = $application->getService('session');
     $userUri = APP_URI;
     $key = 'user';
     if (isset($sess->member) && $application->isRegistered('phire-members')) {
         $key = 'member';
         $memberAdmin = new \Phire\Members\Model\MembersAdmin();
         $memberAdmin->getByRoleId($sess->member->role_id);
         if (isset($memberAdmin->uri)) {
             $userUri = $memberAdmin->uri;
         }
     }
     $path = BASE_PATH . $userUri;
     if ($path == '') {
         $path = '/';
     }
     $cookie = Cookie::getInstance(['path' => $path]);
     $cookie->delete('phire_session_timeout');
     $cookie->delete('phire_session_path');
     // If login, validate and start new session
     if ($controller->request()->isPost() && substr($controller->request()->getRequestUri(), -6) == '/login') {
         // If the user successfully logged in
         if (isset($sess[$key])) {
             $config = Table\UserSessionConfig::findById($sess[$key]->role_id);
             $data = Table\UserSessionData::findById($sess[$key]->id);
             if (isset($config->role_id)) {
                 if (!self::validate($config, $sess[$key], $data)) {
                     if (isset($data->user_id)) {
                         $data->failed_attempts++;
                         $data->save();
                     } else {
                         $data = new Table\UserSessionData(['user_id' => $sess[$key]->id, 'logins' => null, 'failed_attempts' => 1]);
                         $data->save();
                     }
                     if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) {
                         self::log($config, $sess[$key], false);
                     }
                     $sess->kill();
                     Response::redirect(BASE_PATH . $userUri . '/login?failed=' . $data->failed_attempts);
                     exit;
                 } else {
                     if (isset($data->user_id)) {
                         $limit = (int) $application->module('phire-sessions')['login_limit'];
                         $logins = unserialize($data->logins);
                         if ($limit > 0 && count($logins) >= $limit) {
                             reset($logins);
                             unset($logins[key($logins)]);
                         }
                         $logins[time()] = ['ua' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR']];
                         $data->total_logins++;
                         $data->failed_attempts = 0;
                         $data->logins = serialize($logins);
                         $data->save();
                     } else {
                         $data = new Table\UserSessionData(['user_id' => $sess[$key]->id, 'logins' => serialize([time() => ['ua' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR']]]), 'total_logins' => 1, 'failed_attempts' => 0]);
                         $data->save();
                     }
                 }
                 $expire = (int) $config->session_expiration > 0 ? (int) $config->session_expiration : null;
                 $timeout = (int) $config->timeout_warning;
             } else {
                 $expire = null;
                 $timeout = false;
             }
             $lastLogin = null;
             $lastIp = null;
             // Check for the last login
             $data = Table\UserSessionData::findById($sess[$key]->id);
             if (isset($data->user_id)) {
                 $logins = null !== $data->logins ? unserialize($data->logins) : [];
                 if (count($logins) > 1) {
                     $keys = array_keys($logins);
                     $timestamp = isset($keys[count($keys) - 2]) ? $keys[count($keys) - 2] : null;
                     if (null !== $timestamp && isset($logins[$timestamp])) {
                         $lastLogin = $timestamp;
                         $lastIp = $logins[$timestamp]['ip'];
                     }
                 }
             }
             // Clear old sessions
             $clear = (int) $application->module('phire-sessions')['clear_sessions'];
             if ($clear > 0) {
                 $clear = time() - $clear;
                 $sql = Table\UserSessions::sql();
                 $sql->delete()->where(['start <= :start']);
                 Table\UserSessions::execute((string) $sql, ['start' => $clear]);
             }
             $session = new Table\UserSessions(['user_id' => $sess[$key]->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'ua' => $_SERVER['HTTP_USER_AGENT'], 'start' => time()]);
             $session->save();
             $sess[$key]->session = new \ArrayObject(['id' => $session->id, 'start' => $session->start, 'last' => $session->start, 'expire' => $expire, 'timeout' => $timeout, 'last_login' => $lastLogin, 'last_ip' => $lastIp], \ArrayObject::ARRAY_AS_PROPS);
             if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) {
                 self::log($config, $sess[$key], true);
             }
             // Else, if the user login failed
         } else {
             if (null !== $controller->view()->form && $controller->view()->form !== false && null !== $controller->view()->form->username) {
                 $user = \Phire\Table\Users::findBy(['username' => $controller->view()->form->username]);
                 $config = Table\UserSessionConfig::findById($user->role_id);
                 if (isset($user->id)) {
                     $data = Table\UserSessionData::findById($user->id);
                     if (isset($data->user_id)) {
                         $data->failed_attempts++;
                         $data->save();
                     } else {
                         $data = new Table\UserSessionData(['user_id' => $user->id, 'logins' => null, 'failed_attempts' => 1]);
                         $data->save();
                     }
                     if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) {
                         self::log($config, $user, false);
                     }
                 }
             }
         }
         // Check existing session
     } else {
         if (isset($sess[$key]) && isset($sess[$key]->session)) {
             if (!isset(Table\UserSessions::findById((int) $sess[$key]->session->id)->id) || null !== $sess[$key]->session->expire && time() - $sess[$key]->session->last >= $sess[$key]->session->expire) {
                 $session = Table\UserSessions::findById((int) $sess[$key]->session->id);
                 if (isset($session->id)) {
                     $session->delete();
                 }
                 $sess->kill();
                 Response::redirect(BASE_PATH . $userUri . '/login?expired=1');
                 exit;
             } else {
                 if ($sess[$key]->session->timeout && null !== $sess[$key]->session->expire) {
                     $cookie->set('phire_session_timeout', $sess[$key]->session->expire - 30);
                     $cookie->set('phire_session_path', BASE_PATH . $userUri);
                 }
                 $sess[$key]->session->last = time();
             }
         }
     }
 }