| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImportWP\Common\Ftp; |
| 4 |
|
| 5 |
use ImportWP\Common\Filesystem\Filesystem; |
| 6 |
|
| 7 |
class Ftp |
| 8 |
{ |
| 9 |
/** |
| 10 |
* @var resource $_conn |
| 11 |
*/ |
| 12 |
private $_conn; |
| 13 |
/** |
| 14 |
* @var string $conn_hash |
| 15 |
*/ |
| 16 |
private $conn_hash; |
| 17 |
/** |
| 18 |
* @var Filesystem $filesystem |
| 19 |
*/ |
| 20 |
private $filesystem; |
| 21 |
|
| 22 |
public function __construct(Filesystem $filesystem) |
| 23 |
{ |
| 24 |
$this->filesystem = $filesystem; |
| 25 |
} |
| 26 |
|
| 27 |
public function __destruct() |
| 28 |
{ |
| 29 |
$this->disconnect(); |
| 30 |
} |
| 31 |
|
| 32 |
public function download_file($url, $host, $user, $pass, $override_filename) |
| 33 |
{ |
| 34 |
if ($this->_conn && $this->conn_hash !== md5($host . $user . $pass)) { |
| 35 |
$this->disconnect(); |
| 36 |
} |
| 37 |
|
| 38 |
if (!$this->_conn) { |
| 39 |
$this->login($host, $user, $pass); |
| 40 |
} |
| 41 |
|
| 42 |
$size = ftp_size($this->_conn, $url); |
| 43 |
if ($size === -1) { |
| 44 |
return new \WP_Error('IWP_FTP_1', 'Could not get ftp file size.'); |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
if ($size === 0) { |
| 49 |
return false; |
| 50 |
} |
| 51 |
|
| 52 |
$wp_upload_dir = wp_upload_dir(); |
| 53 |
|
| 54 |
$dest = wp_unique_filename($wp_upload_dir['path'], basename($url)); |
| 55 |
$wp_dest = $wp_upload_dir['path'] . '/' . $dest; |
| 56 |
|
| 57 |
$result = ftp_get($this->_conn, $wp_dest, $url, FTP_BINARY); |
| 58 |
if (false === $result) { |
| 59 |
return new \WP_Error('IWP_FTP_2', 'Unable to download: ' . $url . ' file via ftp.'); |
| 60 |
} |
| 61 |
|
| 62 |
return array( |
| 63 |
'dest' => $wp_dest, |
| 64 |
'type' => $this->filesystem->get_filetype($wp_dest), |
| 65 |
'mime' => $this->filesystem->get_file_mime($wp_dest) |
| 66 |
); |
| 67 |
} |
| 68 |
|
| 69 |
public function connect($host) |
| 70 |
{ |
| 71 |
$this->_conn = ftp_connect($host); |
| 72 |
} |
| 73 |
|
| 74 |
public function disconnect() |
| 75 |
{ |
| 76 |
if ($this->_conn) { |
| 77 |
ftp_close($this->_conn); |
| 78 |
$this->_conn = false; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
public function login($host, $user, $pass) |
| 83 |
{ |
| 84 |
if (!$this->_conn) { |
| 85 |
$this->connect($host); |
| 86 |
} |
| 87 |
|
| 88 |
if ($this->_conn) { |
| 89 |
if (true === ftp_login($this->_conn, $user, $pass)) { |
| 90 |
$this->conn_hash = md5($host . $user . $pass); |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
|