<?php

class FtpClient
{
  public $handle;

  /**
   *
   * @param string $host
   */
  public function __construct($host)
  {
    $this->handle = ftp_connect($host);
  }

  /**
   *
   * @return boolean
   */
  public function login($username, $password)
  {
    if($this->isOpen())
      return ftp_login($this->handle, $username, $password) !== false;
    return false;
  }

  /**
   *
   * @return boolean
   */
  public function isOpen()
  {
    return $this->handle !== false;
  }

  /**
   *
   * @return boolean
   */
  public function close()
  {
    if($this->isOpen())
    {
      ftp_close($this->handle);
      $this->handle = false;
      return true;
    }
    return false;
  }

  /**
   *
   */
  function __destruct()
  {
    $this->close();
  }

  /**
   *
   * @param string $path  default '.'
   * @return string[]|false
   */
  public function nlist($path='.')
  {
    if($this->isOpen())
      return ftp_nlist($this->handle, $path);
    return false;
  }

  /**
   *
   * @param string $path
   * @return number|boolean
   */
  public function getFileSize($path)
  {
    if($this->isOpen())
    {
      $size = ftp_size($this->handle, $path);
      //if($size !== -1)
      return $size;
    }
    return false;
  }

  /**
   *
   * @param string $path
   * @return DateTimeEx|boolean
   */
  public function getFileTime($path)
  {
    if($this->isOpen())
    {
      $time = ftp_mdtm($this->handle, $path);
      //if($time !== -1)
      return new DateTimeEx($time);
    }
    return false;
  }

  /**
   * 
   * @param string $remotePath
   * @param string $localPath
   * @param number $resumePos default 0
   * @return boolean
   */
  public function download($remotePath, $localPath, $resumePos=0)
  {
    if($this->isOpen())
    {
      return ftp_get($this->handle, $localPath, $remotePath, FTP_BINARY);
    }
    return false;
  }
}