<?php

/**
 * This is essential main file.
 * Front-end script must include this script.
 * and Instance class and run method call.
 */

require_once '../../mainfile.php';
require_once XOONIPS_CLASS_PATH.'util.php';
require_once XOONIPS_CLASS_PATH.'basic_auth.php';
require_once XOONIPS_USER_PATH.'/class/bean/UsersBean.class.php';

/**
 * Below digest auth class extend rest
 */
class rest_basic_auth extends basic_auth {

  private $uid;
  
  public function __construct() {
    $this->uid = null;
  }
  
  /**
   * Method inherit 
   * DB serach $user
   * 
   * @param string $user Username from agent
   * @param string $passwd Password from agent
   * @return boolen true:success, false:fail
   */  
  protected function cmppasswd($user, $passwd) {
    $dirname = $trustDirname = 'user';
    $userBean = Xoonips_BeanFactory::getBean('UsersBean', $dirname, $trustDirname);
    // TODO: rewrite here!!! This is very inefficient.
    $alluser = $userBean->getAllUsers();
    $md5pass = md5($passwd);
    foreach ($alluser as $u) {
      if (strcmp($u['uname'], $user) == 0 && strcmp($md5pass, $u['pass']) == 0) {
        $this->uid = $u['uid'];
        return true;
      }
    }
    return false;
  }
  
  public function get_uid(){
    return $this->uid;
  }
}

//////////////////////////////////////////////////////////////
/**
 * Post and file data handling this class.
 * 
 */
class Request {

  protected $postval;
  protected $fileval;

  public function __construct() {
    $this->postval = array();
    $this->fileval = array();
    if(count($_POST) == 1){
      $val = current($_POST);
      if(is_array($val)){
        $this->postval[key($_POST)] = $val;
        return;
      }
    }
    
    foreach ($_POST as $key => $value) {
      $this->postval[$key] = $value;
    }
    
    foreach ($_FILES as $key => $value) {
      if($value['error'] == 0)
        $this->fileval[$key] = $value;
    }
  }
  
  /**
   * Get post data
   * 
   * @param string $key key name
   * @return string any string sucess, null is fail.
   */
  public function get($key = null) {
    $ret = null;
    if (!is_null($key) && array_key_exists($key, $this->postval))
      $ret = $this->postval[$key];
    return $ret;
  }
  
  /**
   * This method get tmp file name.
   * 
   * @param string $fname 
   * 
   */
  public function getfile($fname) {
    foreach ($this->fileval as $key => $value) {
      if(strcmp($value['name'], $fname) == 0)
        return $value['tmp_name'];
    }
    return null;
  }
  
  public function get_file_array() {
    $ret = array();
    foreach ($this->fileval as $key => $value)
      $ret[$value['name']] = $value['tmp_name'];
    return $ret;
  }

  /**
   * Get fileinfo;
   * 
   * @param string $file_id
   * @return array fileid info, array() is nothing found
   */
  public function get_file_info($file_id) {
    if (array_key_exists($file_id, $this->fileval))
      return $this->fileval[$file_id];
    return array();
  }
  
  /**
   * Get name array.*NOT* file name!
   * 
   * @return Exist value array:Success Empyt array:fail
   */
  public function get_file_keys() {
    if (count($this->fileval) > 0)
      return array_keys($this->fileval);
    return array();
  }
}

//////////////////////////////////////////////////////////////

// Base class -- This is dispatcher.
class rest_base {
  private $root;
  private function setrootobj() {
    $this->root = &XCube_Root::getSingleton();
  }

  /**
   * get filename from caller script.
   * 
   * ex) /foo/bar/boo.php => boo
   * 
   * @param string $fname caller script fullpath
   * @return filename 
   */
  private function getfilename($fname) {
    $file = basename($fname);
    $arr_file = explode('.', $file);
    return $arr_file[0];
  }
  
  /**
   * main dispatcher
   * 
   * @param type $mod 
   */
  public function run($mod) {
    // Digest Auth
    $auth = new rest_basic_auth();
    $username = empty($_SERVER['PHP_AUTH_USER'])?"":$_SERVER['PHP_AUTH_USER'];
    $auth->init('Xoonips REST');
    if ($auth->auth() == false) {
      exit();
    }

    $this->setrootobj();

    // Load Control
    $class_name = $this->getfilename($mod);
    $file_name = XOONIPS_CONTROL_PATH.'control_'.$class_name.'.php';
    if (!file_exists($file_name)) {
      res_code(500);
      exit();
    }
    
    $req = new Request();
    require_once $file_name;
    if (!class_exists($class_name)) {
      res_code(500);
      exit();
    }
    $controller = new $class_name;
    $controller->set_uid($auth->get_uid());
    $controller->set_user($username);
    $controller->init();
    $controller->run($req);
  }
}
