3 * WordPress Filesystem Class for implementing SSH2
5 * To use this class you must follow these steps for PHP 5.2.6+
7 * @contrib http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ - Installation Notes
9 * Complie libssh2 (Note: Only 0.14 is officaly working with PHP 5.2.6+ right now, But many users have found the latest versions work)
12 * wget http://surfnet.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.14.tar.gz
13 * tar -zxvf libssh2-0.14.tar.gz
18 * Note: Do not leave the directory yet!
20 * Enter: pecl install -f ssh2
22 * Copy the ssh.so file it creates to your PHP Module Directory.
23 * Open up your PHP.INI file and look for where extensions are placed.
24 * Add in your PHP.ini file: extension=ssh2.so
27 * Check phpinfo() streams to confirm that: ssh2.shell, ssh2.exec, ssh2.tunnel, ssh2.scp, ssh2.sftp exist.
29 * Note: as of WordPress 2.8, This utilises the PHP5+ function 'stream_get_contents'
34 * @subpackage Filesystem
36 class WP_Filesystem_SSH2 extends WP_Filesystem_Base {
55 public function __construct( $opt = '' ) {
56 $this->method = 'ssh2';
57 $this->errors = new WP_Error();
59 //Check if possible to use ssh2 functions.
60 if ( ! extension_loaded('ssh2') ) {
61 $this->errors->add('no_ssh2_ext', __('The ssh2 PHP extension is not available'));
64 if ( !function_exists('stream_get_contents') ) {
66 'ssh2_php_requirement',
68 /* translators: %s: stream_get_contents() */
69 __( 'The ssh2 PHP extension is available, however, we require the PHP5 function %s' ),
70 '<code>stream_get_contents()</code>'
77 if ( empty($opt['port']) )
78 $this->options['port'] = 22;
80 $this->options['port'] = $opt['port'];
82 if ( empty($opt['hostname']) )
83 $this->errors->add('empty_hostname', __('SSH2 hostname is required'));
85 $this->options['hostname'] = $opt['hostname'];
87 // Check if the options provided are OK.
88 if ( !empty ($opt['public_key']) && !empty ($opt['private_key']) ) {
89 $this->options['public_key'] = $opt['public_key'];
90 $this->options['private_key'] = $opt['private_key'];
92 $this->options['hostkey'] = array('hostkey' => 'ssh-rsa');
95 } elseif ( empty ($opt['username']) ) {
96 $this->errors->add('empty_username', __('SSH2 username is required'));
99 if ( !empty($opt['username']) )
100 $this->options['username'] = $opt['username'];
102 if ( empty ($opt['password']) ) {
103 // Password can be blank if we are using keys.
105 $this->errors->add('empty_password', __('SSH2 password is required'));
107 $this->options['password'] = $opt['password'];
116 public function connect() {
117 if ( ! $this->keys ) {
118 $this->link = @ssh2_connect($this->options['hostname'], $this->options['port']);
120 $this->link = @ssh2_connect($this->options['hostname'], $this->options['port'], $this->options['hostkey']);
123 if ( ! $this->link ) {
124 $this->errors->add( 'connect',
125 /* translators: %s: hostname:port */
126 sprintf( __( 'Failed to connect to SSH2 Server %s' ),
127 $this->options['hostname'] . ':' . $this->options['port']
133 if ( !$this->keys ) {
134 if ( ! @ssh2_auth_password($this->link, $this->options['username'], $this->options['password']) ) {
135 $this->errors->add( 'auth',
136 /* translators: %s: username */
137 sprintf( __( 'Username/Password incorrect for %s' ),
138 $this->options['username']
144 if ( ! @ssh2_auth_pubkey_file($this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) {
145 $this->errors->add( 'auth',
146 /* translators: %s: username */
147 sprintf( __( 'Public and Private keys incorrect for %s' ),
148 $this->options['username']
155 $this->sftp_link = ssh2_sftp( $this->link );
156 if ( ! $this->sftp_link ) {
157 $this->errors->add( 'connect',
158 /* translators: %s: hostname:port */
159 sprintf( __( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ),
160 $this->options['hostname'] . ':' . $this->options['port']
170 * Gets the ssh2.sftp PHP stream wrapper path to open for the given file.
172 * This method also works around a PHP bug where the root directory (/) cannot
173 * be opened by PHP functions, causing a false failure. In order to work around
174 * this, the path is converted to /./ which is semantically the same as /
175 * See https://bugs.php.net/bug.php?id=64169 for more details.
181 * @param string $path The File/Directory path on the remote server to return
182 * @return string The ssh2.sftp:// wrapped path to use.
184 public function sftp_path( $path ) {
185 if ( '/' === $path ) {
188 return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' );
194 * @param string $command
195 * @param bool $returnbool
196 * @return bool|string True on success, false on failure. String if the command was executed, `$returnbool`
197 * is false (default), and data from the resulting stream was retrieved.
199 public function run_command( $command, $returnbool = false ) {
203 if ( ! ($stream = ssh2_exec($this->link, $command)) ) {
204 $this->errors->add( 'command',
205 /* translators: %s: command */
206 sprintf( __( 'Unable to perform command: %s'),
211 stream_set_blocking( $stream, true );
212 stream_set_timeout( $stream, FS_TIMEOUT );
213 $data = stream_get_contents( $stream );
217 return ( $data === false ) ? false : '' != trim($data);
227 * @param string $file
228 * @return string|false
230 public function get_contents( $file ) {
231 return file_get_contents( $this->sftp_path( $file ) );
237 * @param string $file
240 public function get_contents_array($file) {
241 return file( $this->sftp_path( $file ) );
247 * @param string $file
248 * @param string $contents
249 * @param bool|int $mode
252 public function put_contents($file, $contents, $mode = false ) {
253 $ret = file_put_contents( $this->sftp_path( $file ), $contents );
255 if ( $ret !== strlen( $contents ) )
258 $this->chmod($file, $mode);
268 public function cwd() {
269 $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' );
271 $cwd = trailingslashit( trim( $cwd ) );
280 * @return bool|string
282 public function chdir($dir) {
283 return $this->run_command('cd ' . $dir, true);
289 * @param string $file
290 * @param string $group
291 * @param bool $recursive
295 public function chgrp($file, $group, $recursive = false ) {
296 if ( ! $this->exists($file) )
298 if ( ! $recursive || ! $this->is_dir($file) )
299 return $this->run_command(sprintf('chgrp %s %s', escapeshellarg($group), escapeshellarg($file)), true);
300 return $this->run_command(sprintf('chgrp -R %s %s', escapeshellarg($group), escapeshellarg($file)), true);
306 * @param string $file
308 * @param bool $recursive
309 * @return bool|string
311 public function chmod($file, $mode = false, $recursive = false) {
312 if ( ! $this->exists($file) )
316 if ( $this->is_file($file) )
317 $mode = FS_CHMOD_FILE;
318 elseif ( $this->is_dir($file) )
319 $mode = FS_CHMOD_DIR;
324 if ( ! $recursive || ! $this->is_dir($file) )
325 return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true);
326 return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true);
330 * Change the ownership of a file / folder.
334 * @param string $file Path to the file.
335 * @param string|int $owner A user name or number.
336 * @param bool $recursive Optional. If set True changes file owner recursivly. Default False.
337 * @return bool True on success or false on failure.
339 public function chown( $file, $owner, $recursive = false ) {
340 if ( ! $this->exists($file) )
342 if ( ! $recursive || ! $this->is_dir($file) )
343 return $this->run_command(sprintf('chown %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
344 return $this->run_command(sprintf('chown -R %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
350 * @param string $file
351 * @return string|false
353 public function owner($file) {
354 $owneruid = @fileowner( $this->sftp_path( $file ) );
357 if ( ! function_exists('posix_getpwuid') )
359 $ownerarray = posix_getpwuid($owneruid);
360 return $ownerarray['name'];
366 * @param string $file
369 public function getchmod($file) {
370 return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 );
376 * @param string $file
377 * @return string|false
379 public function group($file) {
380 $gid = @filegroup( $this->sftp_path( $file ) );
383 if ( ! function_exists('posix_getgrgid') )
385 $grouparray = posix_getgrgid($gid);
386 return $grouparray['name'];
392 * @param string $source
393 * @param string $destination
394 * @param bool $overwrite
395 * @param int|bool $mode
398 public function copy($source, $destination, $overwrite = false, $mode = false) {
399 if ( ! $overwrite && $this->exists($destination) )
401 $content = $this->get_contents($source);
402 if ( false === $content)
404 return $this->put_contents($destination, $content, $mode);
410 * @param string $source
411 * @param string $destination
412 * @param bool $overwrite
415 public function move($source, $destination, $overwrite = false) {
416 return @ssh2_sftp_rename( $this->sftp_link, $source, $destination );
422 * @param string $file
423 * @param bool $recursive
424 * @param string|bool $type
427 public function delete($file, $recursive = false, $type = false) {
428 if ( 'f' == $type || $this->is_file($file) )
429 return ssh2_sftp_unlink($this->sftp_link, $file);
431 return ssh2_sftp_rmdir($this->sftp_link, $file);
432 $filelist = $this->dirlist($file);
433 if ( is_array($filelist) ) {
434 foreach ( $filelist as $filename => $fileinfo) {
435 $this->delete($file . '/' . $filename, $recursive, $fileinfo['type']);
438 return ssh2_sftp_rmdir($this->sftp_link, $file);
444 * @param string $file
447 public function exists($file) {
448 return file_exists( $this->sftp_path( $file ) );
454 * @param string $file
457 public function is_file($file) {
458 return is_file( $this->sftp_path( $file ) );
464 * @param string $path
467 public function is_dir($path) {
468 return is_dir( $this->sftp_path( $path ) );
474 * @param string $file
477 public function is_readable($file) {
478 return is_readable( $this->sftp_path( $file ) );
484 * @param string $file
487 public function is_writable($file) {
488 // PHP will base it's writable checks on system_user === file_owner, not ssh_user === file_owner
495 * @param string $file
498 public function atime($file) {
499 return fileatime( $this->sftp_path( $file ) );
505 * @param string $file
508 public function mtime($file) {
509 return filemtime( $this->sftp_path( $file ) );
515 * @param string $file
518 public function size($file) {
519 return filesize( $this->sftp_path( $file ) );
525 * @param string $file
529 public function touch($file, $time = 0, $atime = 0) {
536 * @param string $path
537 * @param mixed $chmod
538 * @param mixed $chown
539 * @param mixed $chgrp
542 public function mkdir($path, $chmod = false, $chown = false, $chgrp = false) {
543 $path = untrailingslashit($path);
548 $chmod = FS_CHMOD_DIR;
549 if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
552 $this->chown($path, $chown);
554 $this->chgrp($path, $chgrp);
561 * @param string $path
562 * @param bool $recursive
565 public function rmdir($path, $recursive = false) {
566 return $this->delete($path, $recursive);
572 * @param string $path
573 * @param bool $include_hidden
574 * @param bool $recursive
577 public function dirlist($path, $include_hidden = true, $recursive = false) {
578 if ( $this->is_file($path) ) {
579 $limit_file = basename($path);
580 $path = dirname($path);
585 if ( ! $this->is_dir($path) )
589 $dir = @dir( $this->sftp_path( $path ) );
594 while (false !== ($entry = $dir->read()) ) {
596 $struc['name'] = $entry;
598 if ( '.' == $struc['name'] || '..' == $struc['name'] )
599 continue; //Do not care about these folders.
601 if ( ! $include_hidden && '.' == $struc['name'][0] )
604 if ( $limit_file && $struc['name'] != $limit_file )
607 $struc['perms'] = $this->gethchmod($path.'/'.$entry);
608 $struc['permsn'] = $this->getnumchmodfromh($struc['perms']);
609 $struc['number'] = false;
610 $struc['owner'] = $this->owner($path.'/'.$entry);
611 $struc['group'] = $this->group($path.'/'.$entry);
612 $struc['size'] = $this->size($path.'/'.$entry);
613 $struc['lastmodunix']= $this->mtime($path.'/'.$entry);
614 $struc['lastmod'] = date('M j',$struc['lastmodunix']);
615 $struc['time'] = date('h:i:s',$struc['lastmodunix']);
616 $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f';
618 if ( 'd' == $struc['type'] ) {
620 $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
622 $struc['files'] = array();
625 $ret[ $struc['name'] ] = $struc;