Merge commit 'origin/fusionax' into account
[platal.git] / classes / xorgsession.php
index baeb28b..f757337 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2008 Polytechnique.org                              *
+ *  Copyright (C) 2003-2009 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
 
 class XorgSession extends PlSession
 {
+    const INVALID_USER = -2;
+    const NO_COOKIE = -1;
+    const COOKIE_SUCCESS = 0;
+    const INVALID_COOKIE = 1;
+
     public function __construct()
     {
         parent::__construct();
@@ -29,15 +34,20 @@ class XorgSession extends PlSession
     public function startAvailableAuth()
     {
         if (!S::logged()) {
-            $cookie = $this->tryCookie();
-            if ($cookie == 0) {
-                return $this->start(AUTH_COOKIE);
-            } else if ($cookie == 1 || $cookie == -2) {
+            switch ($this->tryCookie()) {
+              case self::COOKIE_SUCCESS:
+                if (!$this->start(AUTH_COOKIE)) {
+                    return false;
+                }
+                break;
+
+              case self::INVALID_USER:
+              case self::INVALID_COOKIE:
                 return false;
             }
         }
         if ((check_ip('dangerous') && S::has('uid')) || check_account()) {
-            $_SESSION['log']->log("view_page", $_SERVER['REQUEST_URI']);
+            S::logger()->log("view_page", $_SERVER['REQUEST_URI']);
         }
         return true;
     }
@@ -47,25 +57,24 @@ class XorgSession extends PlSession
     private function tryCookie()
     {
         S::kill('auth_by_cookie');
-        if (Cookie::v('ORGaccess') == '' || !Cookie::has('ORGuid')) {
-            return -1;
+        if (Cookie::v('access') == '' || !Cookie::has('uid')) {
+            return self::NO_COOKIE;
         }
 
         $res = XDB::query('SELECT  uid, password
                              FROM  accounts
                             WHERE  uid = {?} AND state = \'active\'',
-                         Cookie::i('ORGuid'));
+                         Cookie::i('uid'));
         if ($res->numRows() != 0) {
             list($uid, $password) = $res->fetchOneRow();
-            $expected_value = sha1($password);
-            if ($expected_value == Cookie::v('ORGaccess')) {
+            if (sha1($password) == Cookie::v('access')) {
                 S::set('auth_by_cookie', $uid);
-                return 0;
+                return self::COOKIE_SUCCESS;
             } else {
-                return 1;
+                return self::INVALID_COOKIE;
             }
         }
-        return -2;
+        return self::INVALID_USER;
     }
 
     private function checkPassword($uname, $login, $response, $login_type)
@@ -79,11 +88,17 @@ class XorgSession extends PlSession
             $expected_response = sha1("$uname:$password:" . S::v('challenge'));
             /* XXX: Deprecates len(password) > 10 conversion */
             if ($response != $expected_response) {
+                if (!S::logged()) {
+                    Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
+                } else {
+                    Platal::page()->trigError('Mot de passe invalide');
+                }
                 S::logger($uid)->log('auth_fail', 'bad password');
                 return null;
             }
             return $uid;
         }
+        Platal::page()->trigError('Mot de passe ou nom d\'utilisateur invalide');
         return null;
     }
 
@@ -103,7 +118,7 @@ class XorgSession extends PlSession
             if (!S::logged()) {
                 S::set('auth', AUTH_COOKIE);
             }
-            return S::i('auth_by_cookie');
+            return User::getSilentWithValues(null, array('user_id' => S::i('auth_by_cookie')));
         }
 
 
@@ -115,9 +130,8 @@ class XorgSession extends PlSession
 
         /** We come from an authentication form.
          */
-        if (S::has('suid')) {
-            $suid  = S::v('suid');
-            $login = $uname = $suid['uid'];
+        if (S::suid()) {
+            $login = $uname = S::suid('uid');
             $redirect = false;
         } else {
             $uname = Env::v('username');
@@ -140,9 +154,8 @@ class XorgSession extends PlSession
         }
 
         $uid = $this->checkPassword($uname, $login, Post::v('response'), (!$redirect && is_numeric($uname)) ? 'id' : 'alias');
-        if (!is_null($uid) && S::has('suid')) {
-            $suid = S::v('suid');
-            if ($suid['uid'] == $uid) {
+        if (!is_null($uid) && S::suid()) {
+            if (S::suid('uid') == $uid) {
                 $uid = S::i('uid');
             } else {
                 $uid = null;
@@ -150,26 +163,25 @@ class XorgSession extends PlSession
         }
         if (!is_null($uid)) {
             S::set('auth', AUTH_MDP);
-            if (!S::has('suid')) {
+            if (!S::suid()) {
                 if (Post::has('domain')) {
                     if (($domain = Post::v('domain', 'login')) == 'alias') {
-                        setcookie('ORGdomain', "alias", (time() + 25920000), '/', '', 0);
+                        Cookie::set('domain', 'alias', 300);
                     } else {
-                        setcookie('ORGdomain', '', (time() - 3600), '/', '', 0);
+                        Cookie::kill('domain');
                     }
-                    // pour que la modification soit effective dans le reste de la page
-                    $_COOKIE['ORGdomain'] = $domain;
                 }
             }
             S::kill('challenge');
             S::logger($uid)->log('auth_ok');
         }
-        return $uid;
+        return User::getSilentWithValues(null, array('user_id' => $uid));
     }
 
-    protected function startSessionAs($uid, $level)
+    protected function startSessionAs($user, $level)
     {
-        if ((!is_null(S::v('user')) && S::i('user') != $uid) || (S::has('uid') && S::i('uid') != $uid)) {
+        if ((!is_null(S::v('user')) && S::v('user')->id() != $user->id())
+            || (S::has('uid') && S::i('uid') != $user->id())) {
             return false;
         } else if (S::has('uid')) {
             return true;
@@ -177,21 +189,26 @@ class XorgSession extends PlSession
         if ($level == AUTH_SUID) {
             S::set('auth', AUTH_MDP);
         }
-        unset($_SESSION['log']);
 
         // Retrieves main user properties.
-        /** XXX Move needed informations to account tables */
-        $res  = XDB::query("SELECT  u.user_id AS uid, u.hruid, prenom, prenom_ini, nom, nom_ini, nom_usage, perms, promo, promo_sortie,
-                                    matricule, password, FIND_IN_SET('femme', u.flags) AS femme,
-                                    q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash,
-                                    FIND_IN_SET('watch', u.flags) AS watch_account, q.last_version, g.g_account_name IS NOT NULL AS googleapps,
-                                    UNIX_TIMESTAMP(s.start) AS lastlogin, s.host
-                              FROM  auth_user_md5   AS u
-                        INNER JOIN  auth_user_quick AS q  USING(user_id)
-                         LEFT JOIN  gapps_accounts  AS g  ON (u.user_id = g.l_userid AND g.g_status = 'active')
-                         LEFT JOIN  logger.last_sessions AS ls ON (ls.uid = u.user_id)
+        /** TODO: Move needed informations to account tables */
+        /** TODO: Currently suppressed data are matricule, promo */
+        /** TODO: Use the User object to fetch all this */
+        $res  = XDB::query("SELECT  a.uid, a.hruid, a.display_name, a.full_name,
+                                    a.sex = 'female' AS femme, a.email_format,
+                                    a.token, FIND_IN_SET('watch', a.flags) AS watch_account,
+                                    UNIX_TIMESTAMP(fp.last_seen) AS banana_last, UNIX_TIMESTAMP(w.last) AS watch_last,
+                                    a.last_version, g.g_account_name IS NOT NULL AS googleapps,
+                                    UNIX_TIMESTAMP(s.start) AS lastlogin, s.host,
+                                    a.is_admin, at.perms
+                              FROM  accounts        AS a
+                        INNER JOIN  account_types   AS at ON(a.type = at.type)
+                        INNER JOIN  watch           AS w  ON(w.uid = a.uid)
+                         LEFT JOIN  forum_profiles  AS fp ON(fp.uid = a.uid)
+                         LEFT JOIN  gapps_accounts  AS g  ON(a.uid = g.l_userid AND g.g_status = 'active')
+                         LEFT JOIN  logger.last_sessions AS ls ON (ls.uid = a.uid)
                          LEFT JOIN  logger.sessions AS s  ON(s.id = ls.id)
-                             WHERE  u.user_id = {?} AND u.perms IN('admin', 'user')", $uid);
+                             WHERE  a.uid = {?} AND a.state = 'active'", $user->id());
         $sess = $res->fetchOneAssoc();
         $perms = $sess['perms'];
         unset($sess['perms']);
@@ -200,31 +217,21 @@ class XorgSession extends PlSession
         $_SESSION = array_merge($_SESSION, $sess);
 
         // Starts the session's logger, and sets up the permanent cookie.
-        if (S::has('suid')) {
-            $suid = S::v('suid');
-            $logger = S::logger($uid);
-            $logger->log("suid_start", S::v('hruid') . " by " . $suid['hruid']);
+        if (S::suid()) {
+            S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
         } else {
-            $logger = S::logger($uid);
-            $logger->saveLastSession();
-            setcookie('ORGuid', $uid, (time() + 25920000), '/', '', 0);
-
-            if (S::i('auth_by_cookie') == $uid || Post::v('remember', 'false') == 'true') {
-                $cookie = sha1($sess['password']);
-                setcookie('ORGaccess', $cookie, (time() + 25920000), '/', '', 0);
-                if ($logger && S::i('auth_by_cookie') != $uid) {
-                    $logger->log("cookie_on");
-                }
+            S::logger()->saveLastSession();
+            Cookie::set('uid', $user->id(), 300);
+
+            if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
+                $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
             } else {
-                setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
-                if ($logger) {
-                    $logger->log("cookie_off");
-                }
+                $this->killAccessCookie();
             }
         }
 
         // Finalizes the session setup.
-        S::set('perms', User::makePerms($perms));
+        $this->makePerms($perms, S::b('is_admin'));
         $this->securityChecks();
         $this->setSkin();
         $this->updateNbNotifs();
@@ -235,6 +242,21 @@ class XorgSession extends PlSession
         return true;
     }
 
+    /** Start a session without authentication data for the given user.
+     * This is used to identify the user after his registration, to be
+     * removed after rewriting registration procedure.
+     * XXX: Temporary
+     */
+    public function startWeakSession($user)
+    {
+        if (!$this->startSessionAs($user, AUTH_MDP)) {
+            $this->destroy();
+            return false;
+        }
+        S::set('auth', AUTH_MDP);
+        return true;
+    }
+
     private function securityChecks()
     {
         $mail_subject = array();
@@ -259,36 +281,25 @@ class XorgSession extends PlSession
 
     public function tokenAuth($login, $token)
     {
-        $res = XDB::query('SELECT  a.hruid
+        $res = XDB::query('SELECT  a.uid AS user_id, a.hruid
                              FROM  aliases  AS l
                        INNER JOIN  accounts AS a ON (l.id = a.uid AND a.state = \'active\')
                             WHERE  a.token = {?} AND l.alias = {?} AND l.type != \'homonyme\'',
                            $token, $login);
         if ($res->numRows() == 1) {
-            $data = $res->fetchOneAssoc();
-            return new User($data['hruid'], $data);
+            return new User(null, $res->fetchOneAssoc());
         }
         return null;
     }
 
-    public function makePerms($perm)
+    protected function makePerms($perm, $is_admin)
     {
-        $flags = new PlFlagSet();
-        if ($perm == 'disabled' || $perm == 'ext') {
-            S::set('perms', $flags);
-            return;
-        }
-        $flags->addFlag(PERMS_USER);
-        if ($perm == 'admin') {
-            $flags->addFlag(PERMS_ADMIN);
-        }
-        S::set('perms', $flags);
+        S::set('perms', User::makePerms($perm, $is_admin));
     }
 
     public function setSkin()
     {
-        if (S::logged() && (!S::has('skin') || S::has('suid'))) {
-            $uid = S::v('uid');
+        if (S::logged() && (!S::has('skin') || S::suid())) {
             $res = XDB::query('SELECT  skin_tpl
                                  FROM  accounts AS a
                            INNER JOIN  skins    AS s on (a.skin = s.id)
@@ -311,8 +322,31 @@ class XorgSession extends PlSession
     public function updateNbNotifs()
     {
         require_once 'notifs.inc.php';
-        $n = select_notifs(false, S::i('uid'), S::v('watch_last'), false);
-        S::set('notifs', $n->numRows());
+        $user = S::user();
+        $n = Watch::getCount($user);
+        S::set('notifs', $n);
+    }
+
+    public function setAccessCookie($replace = false, $log = true) {
+        if (S::suid() || ($replace && !Cookie::blank('access'))) {
+            return;
+        }
+        Cookie::set('access', sha1(S::user()->password()), 300, true);
+        if ($log) {
+            S::logger()->log('cookie_on');
+        }
+    }
+
+    public function killAccessCookie($log = true) {
+        Cookie::kill('access');
+        if ($log) {
+            S::logger()->log('cookie_off');
+        }
+    }
+
+    public function killLoginFormCookies() {
+        Cookie::kill('uid');
+        Cookie::kill('domain');
     }
 }