<?php

/**
 *
 * INDEXU
 * Copyright(C), Nicecoder, 2000-2006, All Rights Reserved.
 *
 * INDEXU(tm) is protected by Indonesia and International copyright laws.
 * Unauthorized use or distribution of INDEXU(tm) is strictly prohibited,
 * violators will be prosecuted. To obtain a license for using INDEXU(tm),
 * please register at Nicecoder home page at http://www.nicecoder.com
 *
 * Author:
 *    Dody Rachmat Wicaksono (dody@nicecoder.com)
 *    M. Zuber (zubby@nicecoder.com)
 *
 */

  class clsUsers {

    var $table_name = "members";
    var $query = "";
    var $date_format = "d-M-Y";
    var $max_rows = "";
    var $header = "";
    var $paging = false;
    var $show_number = true;
    var $pg_size = "10";
    var $href  = "";
    var $more_param = "";
    var $enable_user_validation = true;
    var $email_register_subject;
    var $email_register_from;
    var $email_register_template_file;
    var $template_file = "";

    // output only
    var $pagination;
    var $num_rows;

    // internal use only


    // method to get fields name
    // return :   array of field name
    // ------------------------------

    function GetFields() {
      global $dbConn;

      // get link fields information

      $query      = "select * from $this->table_name where username = ''";
      $result     = $dbConn->Execute($query);
      $num_fields = $result->FieldCount();

      if ($result) {
        $i = 0;

        while ($i < $num_fields) {
          $fld      = $result->FetchField($i);
          $fields[] = $fld->name;
          $i++;
        }
      }
      
      // return array
      return $fields;
    }


    // method to add new user
    // return :   0: success
    //            1: user already exist
    //            2: sql error
    // --------------------------------

    function Register($username, $email, $password, $plain_password = '') {
      global $dbConn;

      $tpl      = new Template();

      $username = strtolower($username);

      // check for existing user
      $query    = "select username from $this->table_name where username = '$username'";
      $result   = $dbConn->Execute($query);

      if ($result->RecordCount() == 0)
        $return_value = 0;
      else
        $return_value = 1;

      if ($return_value == 0) {

        // insert into datababase

        mt_srand ((double)microtime() * 1000000);
        $vcode = mt_rand();
        $vcode = substr($vcode, -4, 4);

        if ($this->enable_user_validation) {
          $query = "insert into $this->table_name (username, email, password, date, status, vcode, group_id)
          values ('$username', '$email', '$password', now(), 0, $vcode, 2)";
        }
        else {
          $query = "insert into $this->table_name (username, email, password, date, status, vcode, group_id)
          values ('$username', '$email', '$password', now(), 1, $vcode, 2)";
        }

        $result = $dbConn->Execute($query);

        if (!$result)
          $return_value = 2;

        // create my favorites
        $query  = "insert into idx_favorites (username,date,title)
                   values ('$username', now(), 'My Favorites')";
        $result = $dbConn->Execute($query);

        if (!empty($this->email_register_template_file)) {

          // send email

          $fields = $this->GetFields();

          $j = 0;
          $count_fields = @count($fields);
          while ($j < $count_fields) {
            if ($fields[$j] == 'password') {
              $tpl->assign($fields[$j], $plain_password);
            }
            else {
              $tpl->assign($fields[$j], $$fields[$j]);
            }
            $j++;
          }

          $line = $tpl->fetch($this->email_register_template_file);

          @mail($email, $this->email_register_subject, $line,
                "From: $this->email_register_from\nX-Mailer: INDEXU_X-Mailer/1.0");
        }
      }

      return $return_value;
    }


    // method to confirm new user
    // return :   0: success
    //            1: sql error
    // --------------------------------

    function ConfirmRegister($username, $v) {
      global $dbConn;

      // get vcode

      $query  = "select vcode from $this->table_name where username = '$username' and status = 0";
      $result = $dbConn->Execute($query);
      $vcode  = $result->Fields("vcode");

      if ($v == $vcode) {
        $query  = "update $this->table_name set status = 1 where username = '$username'";
        $result = $dbConn->Execute($query);

        return 0;
      }
      else
        return 1;
    }


    // method to handle user login
    // return :   0: success
    //            1: sql error
    // --------------------------------

    function Login($username, $password, $expire) {
      global $dbConn;

      // get password

      $query  = "select password from $this->table_name where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);
      $pwd    = $result->Fields("password");

      if ($password == $pwd) {
        setcookie("COOKIE_USER_AUTHENTICATED", //string name
                  "1",                         //string value
                  $expire,                     //int expire
                  "",                          //string path
                  "",                          //string domain
                  0                            //int secure
        );

        $username = strtolower($username);
        setcookie("COOKIE_USERNAME", //string name
                  "$username",       //string value
                  $expire,           //int expire
                  "",                //string path
                  "",                //string domain
                  0                  //int secure
        );

        setcookie("COOKIE_PASSWORD", //string name
                  "$pwd",            //string value
                  $expire,           //int expire
                  "",                //string path
                  "",                //string domain
                  0                  //int secure
        );

        $_SESSION['indexu_session_username'] = $username;
        session_write_close();

        return 0;
      }
      else
        return 1;
    }


    // method to handle user logout
    // return :   nothing
    // ----------------------------

    function Logout() {

      // delete all cookies

      setcookie("COOKIE_USER_AUTHENTICATED", //string name
                "",                          //string value
                0,                           //int expire
                "",                          //string path
                "",                          //string domain
                0                            //int secure
      );

      setcookie("COOKIE_USERNAME",           //string name
                "",                          //string value
                0,                           //int expire
                "",                          //string path
                "",                          //string domain
                0                            //int secure
      );

      setcookie("COOKIE_PASSWORD",           //string name
                "",                          //string value
                0,                           //int expire
                "",                          //string path
                "",                          //string domain
                0                            //int secure
      );

      //delete its session data
      session_start();
      session_unset();
      session_destroy();
    }


    // method to get group_id
    // return :   group_id
    // ----------------------

    function GetGroupId($username) {
      global $dbConn;
      $query  = "select group_id from $this->table_name where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);

      if ($result)
        return $result->Fields("group_id");
      else
        return "";
    }


    // method to get email address
    // return :email
    // ---------------------------

    function GetEmailAddress($username, $with_username = FALSE, $query_filter = "") {
      global $dbConn;

      if ($with_username) {
        $query = "select email, username from $this->table_name 
                  where status = 1 
                        and username != 'admin'
                        $query_filter";
        $result   = $dbConn->Execute($query);
        while ($row = $result->FetchRow()) {
          $email[] = $row["email"] . "|" . $row["username"];
        }
        return $email;
      }
      else {
        return $dbConn->Lookup("email", $this->table_name, "username = '$username' and status = 1");
      }
    }


    // method to get user authentication
    // return :   0 : success
    //            1 : failed
    // ----------------------------------

    function GetUserAuthentication($group_id = 100) {
      global $dbConn;

      if (empty($_COOKIE['COOKIE_USER_AUTHENTICATED']) or empty($_COOKIE['COOKIE_USERNAME']) or empty($_COOKIE['COOKIE_PASSWORD']))
        return 1;
      else {
        $query  = "select password, group_id from $this->table_name where username = '$_COOKIE[COOKIE_USERNAME]' and status = 1";
        $result = $dbConn->Execute($query);

        if ($result) {
          $pwd = $result->Fields("password");
          $gid = $result->Fields("group_id");

          if ($group_id == 100) {
            if ($_COOKIE['COOKIE_USER_AUTHENTICATED'] && $_COOKIE['COOKIE_PASSWORD'] == $pwd)
              return 0;
            else
              return 1;
          }
          else {
            if ($_COOKIE['COOKIE_USER_AUTHENTICATED'] && $_COOKIE['COOKIE_PASSWORD'] == $pwd && $group_id == $gid)
              return 0;
            else
              return 1;
          }
        }
        else
          return 1;
      }
    }


    // method to change user profile
    // input :    $status = "display_form"
    //                      "process_form"
    //            $username
    // ------------------------------------------

    function ChangeProfile($status, $username, $admin = false) {
      global $dbConn, $error_msg, $name, $email, $homepage, $icq, $yahoo, $aol, $biography, $interest, $location, $occupation,
               $pflag, $password;

      $tpl = new Template();

      if ($status == 'display_form') {
        if ($pflag != "change") {
          $query  = "select * from $this->table_name where username = '$username' and status = 1";
          $result = $dbConn->Execute($query);

          if ($result) {
            $name       = $result->Fields("name");
            $email      = $result->Fields("email");
            $homepage   = $result->Fields("homepage");
            $icq        = $result->Fields("icq");
            $yahoo      = $result->Fields("yahoo");
            $aol        = $result->Fields("aol");
            $biography  = $result->Fields("biography");
            $interest   = htmlspecialchars($result->Fields("interest"));
            $location   = htmlspecialchars($result->Fields("location"));
            $occupation = htmlspecialchars($result->Fields("occupation"));

            $biography  = htmlspecialchars($biography);

            if ($admin) {
              if (USER_AUTH_TYPE == 'plain') {
                $password = $result->Fields("password");
              }
            }
          }
        }

        // replace strings

        $tpl->assign('error_msg', $error_msg);
        $tpl->assign('name', $name);
        $tpl->assign('email', $email);
        $tpl->assign('homepage', $homepage);
        $tpl->assign('icq', $icq);
        $tpl->assign('yahoo', $yahoo);
        $tpl->assign('aol', $aol);
        $tpl->assign('biography', $biography);
        $tpl->assign('interest', $interest);
        $tpl->assign('location', $location);
        $tpl->assign('occupation', $occupation);

        if ($admin) {
          $tpl->assign('username', $username);
          $tpl->assign('password', $password);
        }

        $line = $tpl->fetch($this->template_file);

        print $line;
      }
      elseif ($status == 'process_form') {
        $biography = addslashes($biography);
        $biography = str_replace("\r", "", $biography);

        $query     = "update $this->table_name set
                      name = '$name',
                      email = '$email',
                      homepage = '$homepage',
                      icq = '$icq',
                      yahoo = '$yahoo',
                      aol = '$aol',
                      biography = '$biography',
                      interest = '$interest',
                      location = '$location',
                      occupation = '$occupation'";

        if ($admin) {
          if ($password) {
            $auth = new auth();
            $query .= ", password = '".$auth->Convert($password)."' ";
          }
        }

        $query .= "where username = '$username' and status = 1";
        $result = $dbConn->Execute($query);

        if (!empty($this->template_file)) {
          global $message;
          $tpl->assign('message', $message);

          $line = $tpl->fetch($this->template_file);

          print $line;
        }
      }
    }


    // method to change password
    // input :    $username
    //            $present_pwd
    //            $new_pwd
    //
    // return :   0: success
    //            1: incorect password
    // ------------------------------------------

    function ChangePassword($username, $present_pwd, $new_pwd) {
      global $dbConn;

      // get present pwd
      $query  = "select password from $this->table_name where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);
      $pwd    = $result->Fields("password");

      if ($present_pwd == $pwd) {
        $query  = "update $this->table_name set password = '$new_pwd' where username = '$username' and status = 1";
        $result = $dbConn->Execute($query);

        return 0;
      }
      else
        return 1;
    }


    // method to set password
    // input :    $username
    //            $new_pwd
    //
    // return :   0: success
    // ------------------------------------------

    function SetPassword($username, $new_pwd) {
      global $dbConn;

      $query  = "update $this->table_name set password = '$new_pwd' where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);

      return 0;
    }


    // method to display userlist
    // ------------------------------------------

    function DisplayUsers() {
      global $dbConn, $admin_template_path, $pg_which;

      $people_icon = "../admin_tpl/images/people.gif";
      $people_icon = "<img src=$people_icon border=0> ";

      $tpl         = new Template();

      $fields      = $this->GetFields();

      // prepare pagination

      if ($this->paging) {
        if (empty($pg_which)) {
          $pg_which = 1;
        }
        $result           = $dbConn->PageExecute($this->query, $pg_which, $this->pg_size);
        $num_rows         = $result->RecordCount();
        $nav              = new navigator;
        $nav->pg_size     = $this->pg_size;
        $nav->href        = $this->href;
        $nav->more_param  = $this->more_param;
        $nav->pg_which    = $pg_which;
        $nav->rec_count   = $num_rows;
        $nav->init();
        $this->pagination = $nav->print_all();
        $i                = $nav->rec_start;
      }
      else {
        $result           = $dbConn->Execute($this->query);
        $num_rows         = $result->RecordCount();
        $i                = 0;
      }

      $number         = 1;
      $this->num_rows = 0;

      while (!$result->EOF) {

        // get field's value
        $j = 0;
        $count_fields = @count($fields);
        while ($j < $count_fields) {
          $$fields[$j] = $result->Fields("$fields[$j]");
          $j++;
        }

        $result->MoveNext();

        if ($homepage == 'http://')
          $homepage = '';

        $date = date($this->date_format, @strtotime($date));

        // write template

        // -- template function

        if (empty($this->template_file))
          $line = $this->template;
        else
          $line = implode(file($this->template_file), "");

        $j = 0;
        $count_fields = @count($fields);
        while ($j < $count_fields) {
          $tpl->assign($fields[$j], $$fields[$j]);
          $j++;
        }

        $chk_box = "<input type=checkbox name=chkbox_$number value=$username>";

        $tpl->assign('chk_box', $chk_box);

        if ($number % 2)
          $tbl_class = "tbl_light";
        else
          $tbl_class = "tbl_light2";

        $tpl->assign('tbl_class', $tbl_class);
        $tpl->assign('people_icon', $people_icon);

        $user .= $tpl->fetch('var:' . $line);

        $number++;
        $this->num_rows++;
        $i++;
      }

      return $user;
    }


    // method to delete user
    // ------------------------------------------

    function Delete($username) {
      global $dbConn;
      $query  = "delete from $this->table_name where username = '$username'";
      $result = $dbConn->Execute($query);
      return 0;
    }


    // method to check if username is exist
    // return :   0 : exist
    //            1 : does not exist
    // ------------------------------------

    function CheckUsername($username) {
      global $dbConn;
      $query    = "select username from $this->table_name where username = '$username' and status = 1";
      $result   = $dbConn->Execute($query);

      $username = $result->Fields("username");

      if (empty($username))
        return 1;
      else
        return 0;
    }


    // method to change email address
    // return :   0 : success
    //            1 : sql error
    // ------------------------------------

    function ChangeEmailAddress($username, $email) {
      global $dbConn;
      $query  = "update $this->table_name set email = '$email' where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);

      if ($result)
        return 0;
      else
        return 1;
    }


    // method to get user detail
    // return :   0 : does not exist
    //            associative array of user detail
    // -------------------------------------------

    function GetUserDetail($username) {
      global $dbConn;
      $query  = "select * from $this->table_name where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);

      if ($result) {
        $detail["username"]   = $result->Fields("username");
        $detail["name"]       = $result->Fields("name");
        $detail["email"]      = $result->Fields("email");
        $detail["homepage"]   = $result->Fields("homepage");
        $detail["icq"]        = $result->Fields("icq");
        $detail["aol"]        = $result->Fields("aol");
        $detail["yahoo"]      = $result->Fields("yahoo");
        $detail["biography"]  = $result->Fields("biography");
        $detail["location"]   = $result->Fields("location");
        $detail["interest"]   = $result->Fields("interest");
        $detail["occupation"] = $result->Fields("occupation");
        $detail["date"]       = $result->Fields("date");

        $detail["date"]       = date($this->date_format, @strtotime($detail["date"]));

        return $detail;
      }
      else
        return 0;
    }
		
		
    // method to test authentication
    // return :   0 : success
    //            1 : failed
    // -------------------------------

    function TestAuthentication($username, $password) {
			global $dbConn;
				
      $query  = "select password 
								 from $this->table_name 
								 where username = '$username' and status = 1";
      $result = $dbConn->Execute($query);

      if ($result) {
        $pwd = $result->Fields("password");

        if ($password == $pwd) 
          return 0;
        else
          return 1;
      }
    }	
			
  }
?>
