<?php

/**
 * User related tables migrate functions.
 * 
 */

require_once $MAIN_FILE;
require_once XOOPS_TRUST_PATH.'/modules/xdbmigrate/cmd/inc/migrate_db.inc.php';

define('ACTIVATE','2');

class users {
  
  private $db;
  private $last_autoinc = null;
  private $users_index_array = array(
      'activate'      => 'activate',
      'address'       => 'address',
      'division'      => 'division',
      'tel'           => 'tel',
      'company_name'  => 'company',
      'country'       => 'country',
      'zipcode'       => 'zipcode',
      'fax'           => 'fax',
      'base_url'      => 'url',
      'private_index_id' => 'index_id',
      'private_item_number_limit'  => 'item_number_limit',
      'private_index_number_limit' => 'index_number_limit',
      'private_item_storage_limit' => 'item_storage_limit',
      'user_order'    => 'uorder',
      'posi'          => 'position',
      'appeal'        => 'decription'
    );
  
  private $users_col_array = array(
    'name','bio','url','uname','email','user_avatar','user_regdate','pass',
    'user_icq','user_from','user_sig','user_viewemail','actkey' ,'user_aim',
    'user_yim','user_msnm','posts','attachsig','rank','theme','timezone_offset',
    'last_login','umode','notify_method','user_occ','user_intrest','user_mailok'
  );
    const ADMIN     = 7;
    const MODERATOR = 6;

  function __construct() {
    
  }

  /**
   * xoonips_groups_users_link add groups_users_link 
   * 
   * @return Success:TRUE,Fail:FALSE 
   */
  private function migrate_xoonips_groups_users_link(){
    $tbl = get_tbl('groups_users_link');
    $wk_tbl = get_WK_tbl('xoonips_groups_users_link');
      
    $sql = "insert into {$tbl} (activate,groupid,uid,is_admin) ".
    "select 0,gid+{$this->last_autoinc}-1,uid ,is_admin from {$wk_tbl} ";
    return $this->db->exec($sql);
  }
  
  /**
   * user_field_group and user_field_detail
   * 
   * @param string $xml user_field_group.xml
   * @return boolean Success:TRUE,Fail:FALSE
   */
  private function get_users_field_group($xml) {
    $detail_tbl = get_tbl('user_field_detail');
    $group_tbl = get_tbl('user_field_group');
    $sql = "select detail.group_id,table_name,column_name ".
          "from {$detail_tbl} as detail,{$group_tbl} as group1 ".
          "where detail.group_id = group1.group_id and group1.xml = '{$xml}'";
    $array = $this->db->query($sql);
    if($array === FALSE)return false;
    return $array;
  }
  
  /**
   * val insert user_extend... table
   *
   * @param array $tbl_column_array array(table,column,group_id)
   * @param int   $uid
   * @param mixed $val
   * @param int   $occurence
   * @return boolean Success:TRUE,Fail:FALSE
   */
  protected function insert_user_extend(&$tbl_column_array,$uid,$lval,$occurence=0){
    $tbl = XOOPS_DB_PREFIX.'_'.$tbl_column_array['table_name'];
    $col = $tbl_column_array['column_name'];
    $group_id = $tbl_column_array['group_id'];
    $val = $this->db->quote($lval);
    if($occurence == 0){
      $sql1 = "insert into {$tbl} (uid,group_id,{$col})".
              " values({$uid},{$group_id},{$val})";
    }else{
      $sql1 = "insert into {$tbl} (uid,group_id,{$col},occurrence_number)".
              " values({$uid},{$group_id},{$val},{$occurence})";
    }
    $tbl_column_array = $this->db->exec($sql1);
    if($tbl_column_array === FALSE){
      return false;
    }
    return true;
  }
  
  /**
   * exist_extend ?
   * 
   * @param array $tbl_column_array array(table,column,group_id)
   * @param int $uid
   * @return boolean Success:TRUE,Fail:FALSE
   */
  protected function exist_extend(&$tbl_column_array,$uid){
    $tbl = XOOPS_DB_PREFIX.'_'.$tbl_column_array['table_name'];
    $group_id = $tbl_column_array['group_id'];
    $sql = "select count(*) as cnt from {$tbl} where uid={$uid} and group_id={$group_id}";
    $array = $this->db->query($sql);
    if($array === FALSE)return false;
    if($array[0]['cnt'] == 0)return false;
    return true;
  }

  /**
   *
   * @param array $tbl_column_array
   * @param int   $uid
   * @param mixed $val
   * @return boolean Success:TRUE,Fail:FALSE
   */
  protected function update_table($tbl_column_array,$uid,$val){
    $tbl = XOOPS_DB_PREFIX.'_'.$tbl_column_array['table_name'];
    $col = $tbl_column_array['column_name'];
    $sql = "update {$tbl} set {$col} = '{$val}' where uid={$uid}";
    $tbl_column_array = $this->db->exec($sql);
    if($tbl_column_array === FALSE){
      return false;
    }
    return true;
  }
  
  /**
   *
   * users tables on level column.
   * NG Xoops User module change handling.
   * 
   * Old Xoops User module 0:Pending,1:Active,5:Roor
   * 
   * But NG Xoops User module handling users.level.
   * 0:Inactive,1:Pending,2:Active,5:Roor
   * 
   * @return boolean Sucess:true,Fail:false
   */
  private function update_user_activate()
  {
    $tbl = get_tbl("users");
    $conv_level_array = array(
        #old XooNIps => NG XooNIps
        0 => 1,
        1 => 2
    );
    
    foreach ($conv_level_array as $old => $ng) {
      $sql = "update {$tbl} set level={$ng} where level={$old}";
      if($this->db->exec($sql) == false)return FALSE;
    }
    return TRUE;
  }

  /**
   * exist uid?
   * 
   * @param int $uid Userid
   * @return boolean 
   */
  private function exist_uid($uid) {
    $tbl = get_tbl("users");
    $sql = "select count(*) as cnt from {$tbl} where uid={$uid}";
    $array = $this->db->query($sql);
    if($array === FALSE)return false;
    if($array[0]['cnt'] == 0)return false;
    return true;
  }
  
  /**
   * Insert User Table
   * 
   * @param int $uid USerId
   * @return boolean 
   */
  private function insert_user($uid) {
    $tbl = get_tbl("users");
    $sql = "insert into {$tbl} (uid) values({$uid})";
    $tbl_column_array = $this->db->exec($sql);
    if($tbl_column_array === FALSE){
      return false;
    }
    return true;
  }


  /**
   *loop xoops_users table,then migrate users_field_detail
   * 
   * @return boolean 
   */
  private function migrate_users() {
    global $RUN_LOG;
    $tbl = get_WK_tbl("xoonips_users");
    $utbl = get_WK_tbl("users");
    $sql = "select * from {$tbl} as xu,{$utbl} as u where xu.uid = u.uid";
    $users_array = $this->db->query($sql);
    if($users_array === FALSE){
      return -errmsg(APP_MIGRATE, 'E2501');
    }

    #Migrate groups_users_link

    $rc = $this->migrate_xoonips_groups_users_link();
    if($rc === FALSE){
      return -errmsg(APP_MIGRATE,'E2502');
    }

    foreach ($users_array as $users_row) {
      #If row in table users doesn't exist,then create record.
      $uid = $users_row['uid'];
      if($this->exist_uid($uid) == false){
        $this->insert_user($uid);
      }
      
      #users migrate as key migrate new usesrs table.
      foreach($users_row as $key => $value){
        if(array_search($key,$this->users_col_array) == TRUE){
          $rc = $this->update_table(array('table_name'=>'users','column_name'=>$key), $uid, $value);
          continue;
        }
        if(array_key_exists($key,$this->users_index_array) == FALSE)continue;
        $xml = $this->users_index_array[$key];
        
        #Conversion Values.
        if(strcmp($xml,'activate') == 0){
          $value = $value==1?2:0;
        }else if(strcmp($xml,'item_storage_limit')==0){
          #Unit convert into 1000 * 1000 to 1024 * 1024.
          $value = intval(1.048576 * $value); # 1.048576 = (1024 * 1024)/(1000 * 1000)
        }
        
        $tbl_column_array = $this->get_users_field_group($xml);
        if($tbl_column_array === FALSE){
          return -errmsg(APP_MIGRATE, 'E2503');
        }
        foreach ($tbl_column_array as $tbl_column){
          if(strstr($tbl_column['table_name'],'user_extend') === FALSE){
            $rc = $this->update_table($tbl_column, $uid, $value);
            if($rc === FALSE){
              return -errmsg(APP_MIGRATE, 'E2504',$tbl_column['table_name']);
            }
          }else{
            if($this->exist_extend($tbl_column,$uid) == false){
              $rc = $this->insert_user_extend($tbl_column, $uid, $value);
              if($rc === FALSE){
                return -errmsg(APP_MIGRATE, 'E2505',$tbl_column['table_name']);
              }
            }else{
              $rc = $this->update_table($tbl_column, $uid, $value);
              if($rc === FALSE){
                return -errmsg(APP_MIGRATE, 'E2504',$tbl_column['table_name']);
              }
            }
          }
        }
      }
      $logmsg = sprintf("USER:uid=%d\n",$users_row['uid']);
      fprintf(STDERR,$logmsg);
      if(!is_null($RUN_LOG)){
        error_log(date('Y/m/d H:i:s').' '.$logmsg,3,$RUN_LOG);
      }
    }
    $this->update_user_activate();
    return 0;
  }
  
  /**
   * Set groups object
   * 
   * @param object $groups 
   */
  public function set_groups_obj(&$groups)
  {
      #$this->last_autoinc = $groups->get_last_autoinc();
      $this->last_autoinc = $groups->get_default_groupid();
  }

  /**
   * Do migration.
   * 
   * @return int Sucess:0,Fail:0>
   */
  public function migrate($db) {
    $this->db = $db;
    
    $rc = $this->migrate_users();
    if($rc < 0){
      return $rc;
    }
    return 0;
  }

}
