<?php

include("constants.php");
      
class MySQLDB
{
   var $connection;         //The MySQL database connection
   var $num_members;        //Number of signed-up users
   /* Note: call getNumMembers() to access $num_members! */
   
   # Tables and their column fields
   var $_tableFields = [];
   
   /* Class constructor */
   function __construct(){
      /* Make connection to database */
//      $this->connection = mysql_old_ mysql_old_connect(DB_SERVER, DB_USER, DB_PASS) or die($db->ErrorMsg());
//      mysql_old_select_db(DB_NAME, $this->connection) or die($db->ErrorMsg());
      
      /**
       * Only query database to find out number of members
       * when getNumMembers() is called for the first time,
       * until then, default value set.
       */
      $this->num_members = -1;
   }

   /**
    * confirmUserPass - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given password is the same password in the database
    * for that user. If the user doesn't exist or if the
    * passwords don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
   function confirmUserPass($username, $password){
   	 
   	 global $db, $debug;
   	 
      /* Add slashes if necessary (for query) */
       $username = addslashes($username);


      /* Verify that user is in database */
      $q = "SELECT password, active FROM ".TBL_USERS." WHERE username = ?";
      $result = $db->Execute($q, array($username)) or die("Error locating user: " . $db->ErrorMsg());
      if(!$result || ($result->RecordCount() < 1)){
         return 1; //Indicates username failure
      }

      /* Retrieve password from result, strip slashes */
      $dbarray = $result->FetchRow();
      $dbarray['password'] = stripslashes($dbarray['password']);
            
      $password = stripslashes($password);

      //if (@$debug) { echo "<br>PW string entered:$password<br>PW string in base:".$dbarray['password']; } 
      
      

      /* Validate that password is correct */
      if($dbarray['active'] == 0){
          return 3;
      }
      elseif($password == $dbarray['password']){
         return 0; //Success! Username and password confirmed
      }
      else{
         return 2; //Indicates password failure
      }
   }
   
   
   /**
   * @desc verifyUserDatabase
   * This can be called to make sure there's a valid database connection.
   * (This function was moved to version_check.php)
   */

   /**
    * confirmUserID - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given userid is the same userid in the database
    * for that user. If the user doesn't exist or if the
    * userids don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
   function confirmUserSessionID($username, $usersessionid){
	 		global $db;   	 
      /* Add slashes if necessary (for query) */
      $username = addslashes($username);


      /* Verify that user is in database */
      $q = "SELECT usersessionid FROM ".TBL_USERS." WHERE username = ?";
      $result = $db->Execute($q, array($username));

      if(!$result || ($result->RecordCount() < 1)){
        logDebugMessage ("No user in table matching $username.");
        return 1; //Indicates username failure
      }
      /* Retrieve usersessionid from result, strip slashes */
      $dbarray = $result->FetchRow();
      $result->close;
      $dbarray['usersessionid'] = stripslashes($dbarray['usersessionid']);
      $usersessionid = stripslashes($usersessionid);

      /* Validate that usersessionid is correct */
      if($usersessionid == $dbarray['usersessionid']){
         return 0; # Success! Username and usersessionid confirmed
      }
      else{
        logDebugMessage ("Query: " . $q);
        logDebugMessage ("Session ID mismatch, session:".$usersessionid.", database: ".$dbarray['usersessionid']);
        return 2; # Indicates usersessionid invalid
      }
   }

   /**
    * GetSubscription - returns the requested subscription
   */
   function GetSubscription($subid){
      global $db; 

      $sub = [];

      $query = $db->Execute("SELECT * FROM ". TBL_SUBSCRIPTIONS ." WHERE id = ?", array($subid));
      $row = $query->fetchRow();
      $row = json_decode($row['value'],true);
      foreach ($row as $k => $v) {
        if(isset($v["value"])){
          $sub[$k] = $v["value"];
        }
      }
      $sub['reports'] = $row['reports'];

      if(!empty($sub['reports'])){
        $q = $db->Execute("SELECT * FROM ".TBL_REPORTS." WHERE id in (". implode(",",$sub['reports']) .")");
        $sub['reports'] = [];
        while($row = $q->fetchRow()){
          $r = json_decode($row['value'],true);
          $sub['reports'][] = $r['Label'];
        }
      }

      return $sub;
   }

   
   /**
    * usernameTaken - Returns true if the username has
    * been taken by another user, false otherwise.
    */
   function usernameTaken($username){
	 		global $db;
	 		$username = addslashes($username);

      $q = "SELECT username FROM ".TBL_USERS." WHERE username = ?";
      $result = $db->Execute($q, array($username));
      return ($result->RecordCount() > 0);
   }
   
   /**
    * usernameBanned - Returns true if the username has
    * been banned by the administrator.
    */
   function usernameBanned($username){
	 		global $db;   	 

         $username = addslashes($username);

      $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = ?";
	  $result = $db->Execute($q, array($username));
      return ($result->RecordCount() > 0);
   }
   
  
   /**
    * updateUserField - Updates a field, specified by the field
    * parameter, in the user's row of the database.
    */
   function updateUserField($username, $field, $value){
		global $db;   	 
		/**
		* find valid fields;
		*  - can't use Quote() as it adds quote and that doesn't jive for a column field
		*  - can't use escape() as it only escapes quote marks
		*/
		$db_fields = $this->getTableFields(TBL_USERS);
		if (array_key_exists($field,$db_fields)) {
			$q = "UPDATE ".TBL_USERS." SET ".$field." = ? WHERE username = ?";
			return $db->Execute($q, array($value, $username));
		}
		return;
   }
   
   function getTableFields($table){
		global $db;
		if (!array_key_exists($table, $this->_tableFields)) {
			$db_fields = $db->Execute('DESC ' . $table);
			# we'd need to build array if MySQL DESC output ever changes (unlikely)
			$fields = $db_fields->getAssoc();
			$this->_tableFields[$table] = (is_array($fields)) ? $fields : [];
		}
		return $this->_tableFields[$table];
    }
   
   /**
    * getUserInfo - Returns the result array from a mysql
    * query asking for all information stored regarding
    * the given username. If query fails, NULL is returned.
    */
   function getUserInfo($username){
		global $db;   	 
		$q = "SELECT * FROM ".TBL_USERS." WHERE username = ?";
		$result = $db->Execute($q, array($username));
		
		/* Error occurred, return given name by default */
		if(!$result || ($result->RecordCount() < 1)){
			return NULL;
		}
		/* Return result array */
		$dbarray = $result->FetchRow();
		return $dbarray;
   }
   
   /**
    * getNumMembers - Returns the number of signed-up users
    * of the website, banned members not included. The first
    * time the function is called on page load, the database
    * is queried, on subsequent calls, the stored result
    * is returned. This is to improve efficiency, effectively
    * not querying the database when no call is made.
    */
   function getNumMembers(){
	 		global $db;   	 
      if($this->num_members < 0){
         $q = "SELECT * FROM ".TBL_USERS;
         $result = $db->Execute($q);
         $this->num_members = $result->RecordCount();
      }
      return $this->num_members;
   }
   
}

/* Create database connection */
$database = new MySQLDB;

?>
