Ignore:
Timestamp:
Jan 5, 2014, 4:28:51 PM (11 years ago)
Author:
chronos
Message:
  • Modified: Logged user state remade to use memory table to avoid offten writes to storage. Memory table lose their content if mysql server is restarted. So UserTrace still keep user information but table is only updated on login or logout. Login timeout is managed by UserOnline table.
  • Added: Ability to login permanently. Session will not timeout after short time. List of online users will be not affected as it use own timeout check.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/Modules/User/User.php

    r627 r712  
    1212                parent::__construct($System);
    1313                $this->Name = 'User';
    14                 $this->Version = '1.0';
     14                $this->Version = '1.1';
    1515                $this->Creator = 'Chronos';
    1616                $this->License = 'GNU/GPL';
     
    2626                $this->System->RegisterPage('registrace.php', 'PageUserRegistration');
    2727                $this->System->RegisterPage('user.php', 'PageUserProfile');
     28                $this->System->RegisterPage('login', 'PageUserLogin');
    2829                $this->System->RegisterMenuItem(array(
    2930        'Title' => T('Translators'),
     
    4142        {
    4243                $Output = T('Online translators').':<br />';
    43                 $DbResult = $this->System->Database->query('SELECT `Name`, `GM`, `User`.`ID` AS `ID` FROM `User` '.
    44                                 'LEFT JOIN `UserTrace` ON `UserTrace`.`User` = `User`.`Id` '.
    45                                 'WHERE (`LastLogin` >= NOW() - 300) AND ((`LastLogout` < `LastLogin`) OR (ISNULL(`LastLogout`)))');
     44                $DbResult = $this->System->Database->query('SELECT `User`.`Name`, `User`.`ID` FROM `UserOnline` '.
     45                                'LEFT JOIN `User` ON `User`.`ID` = `UserOnline`.`User` '.
     46                                'WHERE (`ActivityTime` >= NOW() - 300) ');
    4647                while($DbUser = $DbResult->fetch_assoc())
    4748                {
     
    5152                return($Output);
    5253        }       
     54}
     55
     56class PageUserLogin extends Page
     57{
     58        function Show()
     59        {
     60                $Output = '<form action="'.$this->System->Link('/?action=login').'" method="post">'.
     61                        '<fieldset><legend>'.T('Login').'</legend>                     
     62                        <table>
     63                        <tr>
     64                        <td>'.T('Name').':</td><td><input type="text" name="LoginUser" size="13" /></td>
     65                        </tr>
     66                        <tr>
     67                        <td>'.T('Password').':</td><td><input type="password" name="LoginPass" size="13" /></td>
     68                        </tr>
     69                        <tr>
     70                        <td>'.T('Stay logged').':</td><td><input type="checkbox" name="StayLogged" /></td>
     71                        </tr>
     72                        <tr>
     73                        <th><input type="submit" value="'.T('Do login').'" /></th>
     74                        </tr>
     75                        </table>
     76                        </fieldset></form>';
     77                        return($Output);
     78        }
    5379}
    5480
     
    6894  var $Language;
    6995  var $System;
     96  var $Database;
     97  var $OnlineStateTimeout;
    7098 
    7199  function __construct($System)
    72100  {
    73101    $this->System = &$System;
    74     if(isset($_SESSION)) $this->Restore();   
    75       else $this->SetAnonymous();
     102    $this->Database = &$System->Database;
     103    $this->OnlineStateTimeout = 600; // in seconds
     104    if(isset($_SESSION)) $this->Check();   
    76105  }
    77106 
    78107  function __destroy()
    79108  {
    80     if(isset($_SESSION)) $this->Store();
    81   }
    82  
    83   function Login($Name, $Password)
    84   {
    85     $DbResult = $this->System->Database->query('SELECT `ID` FROM `User` WHERE '.
     109  }
     110 
     111  function Login($Name, $Password, $StayLogged = false)
     112  {
     113        $SID = session_id();
     114    $DbResult = $this->Database->query('SELECT `ID` FROM `User` WHERE '.
    86115      'LOWER(`Name`) = LOWER("'.$Name.'") AND `Pass` = '.$this->CryptPasswordSQL('"'.$Password.'"', '`Salt`'));
    87116    if($DbResult->num_rows > 0)
    88117    {
    89118      $User = $DbResult->fetch_assoc();
    90       $this->Id = $User['ID'];     
    91       $this->Load();
    92       $this->System->ModuleManager->Modules['Log']->WriteLog('Login: '.$Name, LOG_TYPE_USER);
    93       $this->UpdateState();
    94     } else $this->Role = LICENCE_ANONYMOUS;
     119      $this->Id = $User['ID'];
     120      $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => $User['ID'], 'StayLogged' => $StayLogged));     
     121      $this->Database->query('UPDATE `UserTrace` SET '.
     122        '`LastLogin` = NOW(), '.
     123        '`LastIP` = "'.$_SERVER['REMOTE_ADDR'].'", '.
     124        '`UserAgent` = "'.$this->System->Database->real_escape_string($_SERVER['HTTP_USER_AGENT']).'" '.
     125        ' WHERE `User` = '.$this->Id);
     126      $this->System->ModuleManager->Modules['Log']->WriteLog('Login', LOG_TYPE_USER);
     127      $this->Check();
     128    };
    95129  }
    96130 
    97131  function Logout()
    98132  {
     133        $SID = session_id();
    99134    if($this->Role != LICENCE_ANONYMOUS)
    100       $this->System->Database->query('UPDATE `UserTrace` SET '.
     135    {
     136      $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('User' => null));
     137      $this->Database->query('UPDATE `UserTrace` SET '.
    101138        '`LastLogout` = NOW() WHERE `User` = '.$this->Id);
    102     $this->SetAnonymous();
     139      $this->System->ModuleManager->Modules['Log']->WriteLog('Logout: '.$this->Name, LOG_TYPE_USER);
     140      $this->Check();
     141    }
    103142  }
    104143 
    105144  function Load()
    106145  {
    107     $DbResult = $this->System->Database->query('SELECT * FROM `User` WHERE `ID` = '.$this->Id);
     146    $DbResult = $this->Database->query('SELECT * FROM `User` WHERE `ID` = '.$this->Id);
    108147    if($DbResult->num_rows > 0)
    109148    {
     
    122161  }
    123162 
    124   function Restore()
    125   {
    126     if(array_key_exists('UserId', $_SESSION))
    127     {
    128       $this->Id = $_SESSION['UserId'];
    129       if($this->Id != 0)
    130       {
    131         $this->Load();
    132         $this->UpdateState();
    133       } else $this->SetAnonymous();
    134     } else $this->SetAnonymous();
    135   }
    136  
    137   function Store()
    138   {
    139     $_SESSION['UserId'] = $this->Id;
    140   }
    141  
    142163  function SetAnonymous()
    143164  {
     
    159180  function CheckToken($Licence, $Token)
    160181  {
    161     $DbResult = $this->System->Database->select('APIToken', 'User', '`Token`="'.$Token.'"');
     182    $DbResult = $this->Database->select('APIToken', 'User', '`Token`="'.$Token.'"');
    162183    if($DbResult->num_rows > 0)
    163184    {
    164185      $DbRow = $DbResult->fetch_assoc();
    165       $DbResult2 = $this->System->Database->select('User', 'GM', '`ID`="'.$DbRow['User'].'"');
     186      $DbResult2 = $this->Database->select('User', 'GM', '`ID`="'.$DbRow['User'].'"');
    166187      $DbRow2 = $DbResult2->fetch_assoc();
    167188      return($DbRow2['GM'] >= $Licence);
     
    179200  }
    180201 
    181   function UpdateState()
    182   {
    183     if(array_key_exists('REMOTE_ADDR', $_SERVER) and ($this->Role != LICENCE_ANONYMOUS))
    184       $this->System->Database->query('UPDATE `UserTrace` SET '.
    185         '`LastIP` = "'.$_SERVER['REMOTE_ADDR'].'", '.
    186         '`LastLogin` = NOW(), '.
    187         '`UserAgent` = "'.$this->System->Database->real_escape_string($_SERVER['HTTP_USER_AGENT']).'" '.
    188         'WHERE `User` = '.$this->Id);
     202  function Check()
     203  {
     204    $SID = session_id();
     205    // Lookup user record
     206    $Query = $this->Database->select('UserOnline', '*', 'SessionId="'.$SID.'"');
     207    if($Query->num_rows > 0)
     208    {
     209      // Refresh time of last access
     210      $this->Database->update('UserOnline', 'SessionId="'.$SID.'"', array('ActivityTime' => 'NOW()'));
     211    } else $this->Database->insert('UserOnline', array('SessionId' => $SID,
     212      'User' => null, 'LoginTime' => 'NOW()', 'ActivityTime' => 'NOW()',
     213      'IpAddress' => GetRemoteAddress(), 'HostName' => gethostbyaddr(GetRemoteAddress()),
     214      'ScriptName' => $_SERVER['PHP_SELF']));
     215     
     216    // Check login
     217    $Query = $this->Database->select('UserOnline', '*', '`SessionId`="'.$SID.'"');
     218    $Row = $Query->fetch_assoc();
     219    if($Row['User'] != '')
     220    {
     221        $this->Id = $Row['User'];
     222      $this->Load();
     223    } else
     224    {
     225      $this->SetAnonymous();
     226    }
     227   
     228    // Remove nonactive users
     229    $DbResult = $this->Database->select('UserOnline', '`Id`, `User`', '(`ActivityTime` < DATE_SUB(NOW(), INTERVAL '.$this->OnlineStateTimeout.' SECOND)) AND (`StayLogged` = 0)');
     230    while($DbRow = $DbResult->fetch_array())
     231    {
     232      $this->Database->delete('UserOnline', 'Id='.$DbRow['Id']);
     233    }
    189234  }
    190235 
     
    192237  {
    193238    $Salt = $this->GetPasswordSalt();
    194     $this->System->Database->query('INSERT INTO `User` '.
     239    $this->Database->query('INSERT INTO `User` '.
    195240      '(`Name` , `Pass` , `Salt`, `Email` , `Language` , `Team` , `NeedUpdate`, `RegistrationTime`, `PreferredVersion` ) '.
    196241      'VALUES ("'.$UserName.'", '.$this->CryptPasswordSQL('"'.$Password.'"', '"'.$Salt.'"').
    197242      ', "'.$Salt.'", "'.$Email.'", '.$Language.', '.$Team.', 1, NOW(), '.$PreferredVersion.')');
    198     $UserId = $this->System->Database->insert_id;
    199     $this->System->Database->query('INSERT INTO `UserTrace` (`User`, `LastIP`, `UserAgent`) '.
     243    $UserId = $this->Database->insert_id;
     244    $this->Database->query('INSERT INTO `UserTrace` (`User`, `LastIP`, `UserAgent`) '.
    200245        'VALUES ('.$UserId.', "'.$_SERVER['REMOTE_ADDR'].'", '.
    201         '"'.$this->System->Database->real_escape_string($_SERVER['HTTP_USER_AGENT']).'")');
     246        '"'.$this->Database->real_escape_string($_SERVER['HTTP_USER_AGENT']).'")');
    202247  }
    203248}
Note: See TracChangeset for help on using the changeset viewer.