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
198 public function run_command( $command, $returnbool = false ) {
202 if ( ! ($stream = ssh2_exec($this->link, $command)) ) {
203 $this->errors->add( 'command',
204 /* translators: %s: command */
205 sprintf( __( 'Unable to perform command: %s'),
210 stream_set_blocking( $stream, true );
211 stream_set_timeout( $stream, FS_TIMEOUT );
212 $data = stream_get_contents( $stream );
216 return ( $data === false ) ? false : '' != trim($data);
226 * @param string $file
227 * @return string|false
229 public function get_contents( $file ) {
230 return file_get_contents( $this->sftp_path( $file ) );
236 * @param string $file
239 public function get_contents_array($file) {
240 return file( $this->sftp_path( $file ) );
246 * @param string $file
247 * @param string $contents
248 * @param bool|int $mode
251 public function put_contents($file, $contents, $mode = false ) {
252 $ret = file_put_contents( $this->sftp_path( $file ), $contents );
254 if ( $ret !== strlen( $contents ) )
257 $this->chmod($file, $mode);
267 public function cwd() {
268 $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' );
270 $cwd = trailingslashit( trim( $cwd ) );
279 * @return bool|string
281 public function chdir($dir) {
282 return $this->run_command('cd ' . $dir, true);
288 * @param string $file
289 * @param string $group
290 * @param bool $recursive
294 public function chgrp($file, $group, $recursive = false ) {
295 if ( ! $this->exists($file) )
297 if ( ! $recursive || ! $this->is_dir($file) )
298 return $this->run_command(sprintf('chgrp %s %s', escapeshellarg($group), escapeshellarg($file)), true);
299 return $this->run_command(sprintf('chgrp -R %s %s', escapeshellarg($group), escapeshellarg($file)), true);
305 * @param string $file
307 * @param bool $recursive
308 * @return bool|string
310 public function chmod($file, $mode = false, $recursive = false) {
311 if ( ! $this->exists($file) )
315 if ( $this->is_file($file) )
316 $mode = FS_CHMOD_FILE;
317 elseif ( $this->is_dir($file) )
318 $mode = FS_CHMOD_DIR;
323 if ( ! $recursive || ! $this->is_dir($file) )
324 return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true);
325 return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true);
329 * Change the ownership of a file / folder.
333 * @param string $file Path to the file.
334 * @param string|int $owner A user name or number.
335 * @param bool $recursive Optional. If set True changes file owner recursivly. Defaults to False.
336 * @return bool|string Returns true on success or false on failure.
338 public function chown( $file, $owner, $recursive = false ) {
339 if ( ! $this->exists($file) )
341 if ( ! $recursive || ! $this->is_dir($file) )
342 return $this->run_command(sprintf('chown %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
343 return $this->run_command(sprintf('chown -R %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
349 * @param string $file
350 * @return string|false
352 public function owner($file) {
353 $owneruid = @fileowner( $this->sftp_path( $file ) );
356 if ( ! function_exists('posix_getpwuid') )
358 $ownerarray = posix_getpwuid($owneruid);
359 return $ownerarray['name'];
365 * @param string $file
368 public function getchmod($file) {
369 return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 );
375 * @param string $file
376 * @return string|false
378 public function group($file) {
379 $gid = @filegroup( $this->sftp_path( $file ) );
382 if ( ! function_exists('posix_getgrgid') )
384 $grouparray = posix_getgrgid($gid);
385 return $grouparray['name'];
391 * @param string $source
392 * @param string $destination
393 * @param bool $overwrite
394 * @param int|bool $mode
397 public function copy($source, $destination, $overwrite = false, $mode = false) {
398 if ( ! $overwrite && $this->exists($destination) )
400 $content = $this->get_contents($source);
401 if ( false === $content)
403 return $this->put_contents($destination, $content, $mode);
409 * @param string $source
410 * @param string $destination
411 * @param bool $overwrite
414 public function move($source, $destination, $overwrite = false) {
415 return @ssh2_sftp_rename( $this->sftp_link, $source, $destination );
421 * @param string $file
422 * @param bool $recursive
423 * @param string|bool $type
426 public function delete($file, $recursive = false, $type = false) {
427 if ( 'f' == $type || $this->is_file($file) )
428 return ssh2_sftp_unlink($this->sftp_link, $file);
430 return ssh2_sftp_rmdir($this->sftp_link, $file);
431 $filelist = $this->dirlist($file);
432 if ( is_array($filelist) ) {
433 foreach ( $filelist as $filename => $fileinfo) {
434 $this->delete($file . '/' . $filename, $recursive, $fileinfo['type']);
437 return ssh2_sftp_rmdir($this->sftp_link, $file);
443 * @param string $file
446 public function exists($file) {
447 return file_exists( $this->sftp_path( $file ) );
453 * @param string $file
456 public function is_file($file) {
457 return is_file( $this->sftp_path( $file ) );
463 * @param string $path
466 public function is_dir($path) {
467 return is_dir( $this->sftp_path( $path ) );
473 * @param string $file
476 public function is_readable($file) {
477 return is_readable( $this->sftp_path( $file ) );
483 * @param string $file
486 public function is_writable($file) {
487 // PHP will base it's writable checks on system_user === file_owner, not ssh_user === file_owner
494 * @param string $file
497 public function atime($file) {
498 return fileatime( $this->sftp_path( $file ) );
504 * @param string $file
507 public function mtime($file) {
508 return filemtime( $this->sftp_path( $file ) );
514 * @param string $file
517 public function size($file) {
518 return filesize( $this->sftp_path( $file ) );
524 * @param string $file
528 public function touch($file, $time = 0, $atime = 0) {
535 * @param string $path
536 * @param mixed $chmod
537 * @param mixed $chown
538 * @param mixed $chgrp
541 public function mkdir($path, $chmod = false, $chown = false, $chgrp = false) {
542 $path = untrailingslashit($path);
547 $chmod = FS_CHMOD_DIR;
548 if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
551 $this->chown($path, $chown);
553 $this->chgrp($path, $chgrp);
560 * @param string $path
561 * @param bool $recursive
564 public function rmdir($path, $recursive = false) {
565 return $this->delete($path, $recursive);
571 * @param string $path
572 * @param bool $include_hidden
573 * @param bool $recursive
576 public function dirlist($path, $include_hidden = true, $recursive = false) {
577 if ( $this->is_file($path) ) {
578 $limit_file = basename($path);
579 $path = dirname($path);
584 if ( ! $this->is_dir($path) )
588 $dir = @dir( $this->sftp_path( $path ) );
593 while (false !== ($entry = $dir->read()) ) {
595 $struc['name'] = $entry;
597 if ( '.' == $struc['name'] || '..' == $struc['name'] )
598 continue; //Do not care about these folders.
600 if ( ! $include_hidden && '.' == $struc['name'][0] )
603 if ( $limit_file && $struc['name'] != $limit_file )
606 $struc['perms'] = $this->gethchmod($path.'/'.$entry);
607 $struc['permsn'] = $this->getnumchmodfromh($struc['perms']);
608 $struc['number'] = false;
609 $struc['owner'] = $this->owner($path.'/'.$entry);
610 $struc['group'] = $this->group($path.'/'.$entry);
611 $struc['size'] = $this->size($path.'/'.$entry);
612 $struc['lastmodunix']= $this->mtime($path.'/'.$entry);
613 $struc['lastmod'] = date('M j',$struc['lastmodunix']);
614 $struc['time'] = date('h:i:s',$struc['lastmodunix']);
615 $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f';
617 if ( 'd' == $struc['type'] ) {
619 $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
621 $struc['files'] = array();
624 $ret[ $struc['name'] ] = $struc;