/
SshServer.php
237 lines (201 loc) · 5.1 KB
/
SshServer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
<?php
/**
* FTP Deployment
*
* Copyright (c) 2009 David Grudl (https://davidgrudl.com)
*/
namespace Deployment;
/**
* SSH server.
*/
class SshServer implements Server
{
/** @var int */
public $filePermissions;
/** @var int */
public $dirPermissions;
/** @var resource */
private $connection;
/** @var resource */
private $sftp;
/** @var array see parse_url() */
private $url;
/**
* @param string|array URL ftp://...
* @param bool
*/
public function __construct($url)
{
if (!extension_loaded('ssh2')) {
throw new \Exception('PHP extension SSH2 is not loaded.');
}
$this->url = is_array($url) ? $url : parse_url($url);
if (!isset($this->url['scheme'], $this->url['user']) || $this->url['scheme'] !== 'sftp') {
throw new \InvalidArgumentException('Invalid URL or missing username');
}
}
/**
* Connects to FTP server.
* @return void
*/
public function connect()
{
$this->connection = $this->protect('ssh2_connect', [$this->url['host'], empty($this->url['port']) ? 22 : (int) $this->url['port']]);
if (isset($this->url['pass'])) {
$this->protect('ssh2_auth_password', [$this->connection, urldecode($this->url['user']), urldecode($this->url['pass'])]);
} else {
$this->protect('ssh2_auth_agent', [$this->connection, urldecode($this->url['user'])]);
}
$this->sftp = $this->protect('ssh2_sftp', [$this->connection]);
}
/**
* Reads remote file from FTP server.
* @return void
*/
public function readFile($remote, $local)
{
$this->protect('copy', ["ssh2.sftp://$this->sftp$remote", $local]);
}
/**
* Uploads file to FTP server.
* @return void
*/
public function writeFile($local, $remote, callable $progress = null)
{
$this->protect(function () use ($local, $remote, $progress) {
$size = max(filesize($local), 1);
$len = 0;
$i = fopen($local, 'rb');
$o = fopen("ssh2.sftp://$this->sftp$remote", 'wb');
while (!feof($i)) {
$s = fread($i, 10000);
fwrite($o, $s, strlen($s));
$len += strlen($s);
if ($progress) {
$progress($len * 100 / $size);
}
}
});
if ($this->filePermissions) {
$this->protect('ssh2_sftp_chmod', [$this->sftp, $remote, $this->filePermissions]);
}
}
/**
* Removes file from FTP server if exists.
* @return void
*/
public function removeFile($file)
{
if (file_exists($path = "ssh2.sftp://$this->sftp$file")) {
$this->protect('unlink', [$path]);
}
}
/**
* Renames and rewrites file on FTP server.
* @return void
*/
public function renameFile($old, $new)
{
if (file_exists($path = "ssh2.sftp://$this->sftp$new")) {
$perms = fileperms($path);
$this->removeFile($new);
}
$this->protect('ssh2_sftp_rename', [$this->sftp, $old, $new]);
if (!empty($perms)) {
$this->protect('ssh2_sftp_chmod', [$this->sftp, $new, $perms]);
}
}
/**
* Creates directories on FTP server.
* @return void
*/
public function createDir($dir)
{
if (trim($dir, '/') !== '' && !file_exists("ssh2.sftp://$this->sftp$dir")) {
$this->protect('ssh2_sftp_mkdir', [$this->sftp, $dir, $this->dirPermissions ?: 0777, true]);
}
}
/**
* Removes directory from FTP server if exists.
* @return void
*/
public function removeDir($dir)
{
if (file_exists($path = "ssh2.sftp://$this->sftp$dir")) {
$this->protect('rmdir', [$path]);
}
}
/**
* Recursive deletes content of directory or file.
* @param string
* @return void
*/
public function purge($dir, callable $progress = null)
{
$dirs = $entries = [];
$iterator = dir($path = "ssh2.sftp://$this->sftp$dir");
while (($entry = $iterator->read()) !== false) {
if ($entry !== '.' && $entry !== '..') {
$entries[] = $entry;
}
}
foreach ($entries as $entry) {
if (is_dir("$path/$entry")) {
$dirs[] = $tmp = '.delete' . uniqid() . count($dirs);
$this->protect('rename', ["$path/$entry", "$path/$tmp"]);
} else {
$this->protect('unlink', ["$path/$entry"]);
}
if ($progress) {
$progress($entry);
}
}
foreach ($dirs as $subdir) {
$this->purge("$dir/$subdir", $progress);
$this->protect('rmdir', ["$path/$subdir"]);
}
}
/**
* Returns current directory.
* @return string
*/
public function getDir()
{
return isset($this->url['path']) ? rtrim($this->url['path'], '/') : '';
}
/**
* Executes a command on a remote server.
* @return string
*/
public function execute($command)
{
$stream = $this->protect('ssh2_exec', [$this->connection, $command]);
stream_set_blocking($stream, true);
$out = stream_get_contents($stream);
fclose($stream);
return $out;
}
private function protect(callable $func, $args = [])
{
set_error_handler(function ($severity, $message) {
if (ini_get('html_errors')) {
$message = html_entity_decode(strip_tags($message));
}
if (preg_match('#^\w+\(\):\s*(.+)#', $message, $m)) {
$message = $m[1];
}
throw new SshException($message);
});
try {
$res = call_user_func_array($func, $args);
restore_error_handler();
} catch (\Exception $e) {
restore_error_handler();
throw $e;
}
if ($res === false) {
throw new SshException(is_string($func) ? "$func failures." : null);
}
return $res;
}
}