English
Kamil Dudka

Drobné programy (C, C++, C#, ...)

Detail souboru

Jméno:Stáhnoutdb.php [Stáhnout]
Umístění: tiny > IIS > proj > engine
Velikost:6.4 KB
Poslední změna:2022-09-09 13:06

Zdrojový kód

<?php
/**
 * Set of most common classes accessing to MySQL db
 * @package default
 * @author Kamil Dudka <xdudka00@gmail.com>
 */
 
/**
 * Set of base classes used by almost all pages of IS
 */
include_once ("base.php");
/**
 * Sensitive information needed to connect MySQL db.
 */
include_once ("db_passwd.php");
 
/**
 * Persistent connection to MySQL db.
 * Design pattern singleton.
 * @package default
 */
class DbConnection
{
  /**
   * @return Return reference to singleton object.
   */
  public static function singleton() 
  {
    if (!isset(self::$instance)) {
      $c = __CLASS__;
      self::$instance = new $c;
    }
 
    return self::$instance;
  }
  /**
   * Resource ID of opened db.
   */
  public $db;
 
  // Prevent users to clone the instance
  public function __clone()
  {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
  }
  private static $instance;
  private function __construct()
  {
    $this->db= mysql_pconnect (
        AccessToMysql::MYSQL_SERVER,
        AccessToMysql::MYSQL_USER,
        AccessToMysql::MYSQL_PASSWD
        )
      or die ("CRITICAL: Could not connect to db.\n");
      // TODO: well-formed exception handling
 
    mysql_select_db (
        AccessToMysql::MYSQL_DB
        );
  }
  public function __destruct()
  {
    if ($this->db)
      mysql_close ($this->db);
  }
};
 
/**
 * User authorization framework.
 * Design pattern singleton.
 * @package default
 */
class UserAuth {
  /**
   * @return Return reference to singleton object.
   */
  public static function singleton() 
  {
    if (!isset(self::$instance)) {
      $c = __CLASS__;
      self::$instance = new $c;
    }
    return self::$instance;
  }
  /**
   * Inactivity timer constant. [sec]
   * After this time will be user will be automatically logged out.
   */
  const AUTO_LOGOUT=900;      // Inactivity timer for 15 minutes (15*60)
 
  // lougout reason enumeration
  const LOGIN_INCORRECT=1;
  const ACCESS_DENIED=2;
  const INACTIVITY_TIMEOUT=3;
  const USER_LOGOUT=4;
  /**
   * Try login user with given login and passwd.
   * If 'login incorrect' occur, logout method is called automatically.
   * @param szUser User name to login with.
   * @param szPasswd Password to use. Passsword is passed as plain text - be carreful.
   * @return Return logged user role as string, e.g. "manager", ...
   */
  public function login ($szUser, $szPasswd) {
    $nowIs= time();
    $szQuery=
      "SELECT count(user) AS cnt FROM users WHERE ".    // user lookup
      "passwd=password('$szPasswd') AND ".              // check password
      "user='$szUser' AND ".                            // check user name
      "expiration<>-1 AND expiration < '$nowIs';";      // check account expiration
    $res= @mysql_query ($szQuery);
    $resArray= @mysql_fetch_array ($res);
    $iLines= @mysql_num_rows ($res);
    if ($resArray["cnt"] !=1) {                         // login incorrect
      $this->logout(self::LOGIN_INCORRECT);
      return NULL;
    }
    $_SESSION["user"]= $szUser;
    $this->updateLastAccess();
    return $this->getRole();
  }
  /**
   * Logout current user, if such exists.
   * Automatically redirects to /login.php with reason as parameter.
   * This should be called before placing any text to page.
   * @param eReason Reason of logout enumeration. This will be passed to /login.php as parameter.
   */
  public function logout($eReason= self::USER_LOGOUT) {
    unset ($_SESSION["user"]);
    header (
      "Location: ".
      Page::singleton()->linkToWebRoot().
      "/login".Page::phpFileExt()."?reason=".$eReason
      );
    exit();
  }
  public function logged() {
    return !empty($_SESSION["user"]);
  }
  /**
   * This authorizate user to access privileged page of IS.
   * If 'access denied' occur, user is automatically redirected to /login.php
   * with ACCESS_DENIED as reason.
   * @param szRole Role of user needed to access page. (as string)
   * @return Return true if access is granted.
   */
  public function tryAccess ($szRole) {
    if ($this->getRole() != $szRole) {
      $this->logout(self::ACCESS_DENIED);
      return false;
    }
    if (!$this->userAlive ()) {
      $this->logout(self::INACTIVITY_TIMEOUT);
      return false;
    }
    $this->updateLastAccess();
    return true;
  }
  /**
   * @return Return logged-in user name, empty string if nobody is logged in IS.
   */
  public function getUser()
  {
    return @$_SESSION["user"];
  }
  /**
   * @return Return logged-in user role as string.
   */
  public function getRole()
  {
    $szUser= @$_SESSION["user"];
    if (empty ($szUser))
      return NULL;
    $res= @mysql_query ("SELECT ico FROM users WHERE user='$szUser'");
    $iLines= @mysql_num_rows ($res);
    if ($iLines !=1)
      return NULL;
    $resArray= mysql_fetch_array ($res);
    $ico= $resArray["ico"];
    if ($ico== 0)
      return "manager";
    $res= @mysql_query ("SELECT ico FROM dealers WHERE ico='$ico'");
    $iLines= @mysql_num_rows ($res);
    if ($iLines ==1)
      return "dealer";
    $res= @mysql_query ("SELECT ico FROM transporters WHERE ico='$ico'");
    $iLines= @mysql_num_rows ($res);
    if ($iLines ==1)
      return "transporter";
    return NULL;
  }
  private function updateLastAccess () {
    $nowIs= time();
    $szUser= $_SESSION["user"];
    @mysql_query ("UPDATE users SET last_access=$nowIs WHERE user='$szUser'");
  }
  private function userAlive () {
    $szUser= $_SESSION["user"];
    $res =@mysql_query ("SELECT last_access FROM users WHERE user='$szUser'");
    $resArray= @mysql_fetch_array($res);
    return
      (!empty ($resArray["last_access"])) &&
      ($resArray["last_access"]+self::AUTO_LOGOUT > time());
  }
  // Prevent users to clone the instance
  public function __clone()
  {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
  }
  private static $instance;
  private function __construct() 
  {
    session_start();
    DbConnection::singleton();
  }
};
 
class DbQuery {
  public function __construct($szQuery)
  {
    DbConnection::singleton();
    $this->res= mysql_query($szQuery);
  }
  public function getNumRows()
  {
    return @mysql_num_rows ($this->res);
  }
  public function getAffectedRows()
  {
    return @mysql_affected_rows (DbConnection::singleton()->db);
  }
  public function fetchArray ($eType= MYSQL_ASSOC)
  {
    return $this->resArray= @mysql_fetch_array ($this->res, $eType);
  }
  public function getElement ($szElement)
  {
    return @$this->resArray[$szElement];
  }
  public $res;
  public $resArray;
};
?>