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') ) {
65 $this->errors->add('ssh2_php_requirement', __('The ssh2 PHP extension is available, however, we require the PHP5 function <code>stream_get_contents()</code>'));
70 if ( empty($opt['port']) )
71 $this->options['port'] = 22;
73 $this->options['port'] = $opt['port'];
75 if ( empty($opt['hostname']) )
76 $this->errors->add('empty_hostname', __('SSH2 hostname is required'));
78 $this->options['hostname'] = $opt['hostname'];
80 // Check if the options provided are OK.
81 if ( !empty ($opt['public_key']) && !empty ($opt['private_key']) ) {
82 $this->options['public_key'] = $opt['public_key'];
83 $this->options['private_key'] = $opt['private_key'];
85 $this->options['hostkey'] = array('hostkey' => 'ssh-rsa');
88 } elseif ( empty ($opt['username']) ) {
89 $this->errors->add('empty_username', __('SSH2 username is required'));
92 if ( !empty($opt['username']) )
93 $this->options['username'] = $opt['username'];
95 if ( empty ($opt['password']) ) {
96 // Password can be blank if we are using keys.
98 $this->errors->add('empty_password', __('SSH2 password is required'));
100 $this->options['password'] = $opt['password'];
109 public function connect() {
110 if ( ! $this->keys ) {
111 $this->link = @ssh2_connect($this->options['hostname'], $this->options['port']);
113 $this->link = @ssh2_connect($this->options['hostname'], $this->options['port'], $this->options['hostkey']);
116 if ( ! $this->link ) {
117 $this->errors->add( 'connect',
118 /* translators: %s: hostname:port */
119 sprintf( __( 'Failed to connect to SSH2 Server %s' ),
120 $this->options['hostname'] . ':' . $this->options['port']
126 if ( !$this->keys ) {
127 if ( ! @ssh2_auth_password($this->link, $this->options['username'], $this->options['password']) ) {
128 $this->errors->add( 'auth',
129 /* translators: %s: username */
130 sprintf( __( 'Username/Password incorrect for %s' ),
131 $this->options['username']
137 if ( ! @ssh2_auth_pubkey_file($this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) {
138 $this->errors->add( 'auth',
139 /* translators: %s: username */
140 sprintf( __( 'Public and Private keys incorrect for %s' ),
141 $this->options['username']
148 $this->sftp_link = ssh2_sftp( $this->link );
149 if ( ! $this->sftp_link ) {
150 $this->errors->add( 'connect',
151 /* translators: %s: hostname:port */
152 sprintf( __( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ),
153 $this->options['hostname'] . ':' . $this->options['port']
163 * Gets the ssh2.sftp PHP stream wrapper path to open for the given file.
165 * This method also works around a PHP bug where the root directory (/) cannot
166 * be opened by PHP functions, causing a false failure. In order to work around
167 * this, the path is converted to /./ which is semantically the same as /
168 * See https://bugs.php.net/bug.php?id=64169 for more details.
174 * @param string $path The File/Directory path on the remote server to return
175 * @return string The ssh2.sftp:// wrapped path to use.
177 public function sftp_path( $path ) {
178 if ( '/' === $path ) {
181 return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' );
187 * @param string $command
188 * @param bool $returnbool
189 * @return bool|string
191 public function run_command( $command, $returnbool = false ) {
195 if ( ! ($stream = ssh2_exec($this->link, $command)) ) {
196 $this->errors->add( 'command',
197 /* translators: %s: command */
198 sprintf( __( 'Unable to perform command: %s'),
203 stream_set_blocking( $stream, true );
204 stream_set_timeout( $stream, FS_TIMEOUT );
205 $data = stream_get_contents( $stream );
209 return ( $data === false ) ? false : '' != trim($data);
219 * @param string $file
220 * @return string|false
222 public function get_contents( $file ) {
223 return file_get_contents( $this->sftp_path( $file ) );
229 * @param string $file
232 public function get_contents_array($file) {
233 return file( $this->sftp_path( $file ) );
239 * @param string $file
240 * @param string $contents
241 * @param bool|int $mode
244 public function put_contents($file, $contents, $mode = false ) {
245 $ret = file_put_contents( $this->sftp_path( $file ), $contents );
247 if ( $ret !== strlen( $contents ) )
250 $this->chmod($file, $mode);
260 public function cwd() {
261 $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' );
263 $cwd = trailingslashit( trim( $cwd ) );
272 * @return bool|string
274 public function chdir($dir) {
275 return $this->run_command('cd ' . $dir, true);
281 * @param string $file
282 * @param string $group
283 * @param bool $recursive
287 public function chgrp($file, $group, $recursive = false ) {
288 if ( ! $this->exists($file) )
290 if ( ! $recursive || ! $this->is_dir($file) )
291 return $this->run_command(sprintf('chgrp %s %s', escapeshellarg($group), escapeshellarg($file)), true);
292 return $this->run_command(sprintf('chgrp -R %s %s', escapeshellarg($group), escapeshellarg($file)), true);
298 * @param string $file
300 * @param bool $recursive
301 * @return bool|string
303 public function chmod($file, $mode = false, $recursive = false) {
304 if ( ! $this->exists($file) )
308 if ( $this->is_file($file) )
309 $mode = FS_CHMOD_FILE;
310 elseif ( $this->is_dir($file) )
311 $mode = FS_CHMOD_DIR;
316 if ( ! $recursive || ! $this->is_dir($file) )
317 return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true);
318 return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true);
322 * Change the ownership of a file / folder.
326 * @param string $file Path to the file.
327 * @param string|int $owner A user name or number.
328 * @param bool $recursive Optional. If set True changes file owner recursivly. Defaults to False.
329 * @return bool|string Returns true on success or false on failure.
331 public function chown( $file, $owner, $recursive = false ) {
332 if ( ! $this->exists($file) )
334 if ( ! $recursive || ! $this->is_dir($file) )
335 return $this->run_command(sprintf('chown %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
336 return $this->run_command(sprintf('chown -R %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
342 * @param string $file
343 * @return string|false
345 public function owner($file) {
346 $owneruid = @fileowner( $this->sftp_path( $file ) );
349 if ( ! function_exists('posix_getpwuid') )
351 $ownerarray = posix_getpwuid($owneruid);
352 return $ownerarray['name'];
358 * @param string $file
361 public function getchmod($file) {
362 return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 );
368 * @param string $file
369 * @return string|false
371 public function group($file) {
372 $gid = @filegroup( $this->sftp_path( $file ) );
375 if ( ! function_exists('posix_getgrgid') )
377 $grouparray = posix_getgrgid($gid);
378 return $grouparray['name'];
384 * @param string $source
385 * @param string $destination
386 * @param bool $overwrite
387 * @param int|bool $mode
390 public function copy($source, $destination, $overwrite = false, $mode = false) {
391 if ( ! $overwrite && $this->exists($destination) )
393 $content = $this->get_contents($source);
394 if ( false === $content)
396 return $this->put_contents($destination, $content, $mode);
402 * @param string $source
403 * @param string $destination
404 * @param bool $overwrite
407 public function move($source, $destination, $overwrite = false) {
408 return @ssh2_sftp_rename( $this->sftp_link, $source, $destination );
414 * @param string $file
415 * @param bool $recursive
416 * @param string|bool $type
419 public function delete($file, $recursive = false, $type = false) {
420 if ( 'f' == $type || $this->is_file($file) )
421 return ssh2_sftp_unlink($this->sftp_link, $file);
423 return ssh2_sftp_rmdir($this->sftp_link, $file);
424 $filelist = $this->dirlist($file);
425 if ( is_array($filelist) ) {
426 foreach ( $filelist as $filename => $fileinfo) {
427 $this->delete($file . '/' . $filename, $recursive, $fileinfo['type']);
430 return ssh2_sftp_rmdir($this->sftp_link, $file);
436 * @param string $file
439 public function exists($file) {
440 return file_exists( $this->sftp_path( $file ) );
446 * @param string $file
449 public function is_file($file) {
450 return is_file( $this->sftp_path( $file ) );
456 * @param string $path
459 public function is_dir($path) {
460 return is_dir( $this->sftp_path( $path ) );
466 * @param string $file
469 public function is_readable($file) {
470 return is_readable( $this->sftp_path( $file ) );
476 * @param string $file
479 public function is_writable($file) {
480 // PHP will base it's writable checks on system_user === file_owner, not ssh_user === file_owner
487 * @param string $file
490 public function atime($file) {
491 return fileatime( $this->sftp_path( $file ) );
497 * @param string $file
500 public function mtime($file) {
501 return filemtime( $this->sftp_path( $file ) );
507 * @param string $file
510 public function size($file) {
511 return filesize( $this->sftp_path( $file ) );
517 * @param string $file
521 public function touch($file, $time = 0, $atime = 0) {
528 * @param string $path
529 * @param mixed $chmod
530 * @param mixed $chown
531 * @param mixed $chgrp
534 public function mkdir($path, $chmod = false, $chown = false, $chgrp = false) {
535 $path = untrailingslashit($path);
540 $chmod = FS_CHMOD_DIR;
541 if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
544 $this->chown($path, $chown);
546 $this->chgrp($path, $chgrp);
553 * @param string $path
554 * @param bool $recursive
557 public function rmdir($path, $recursive = false) {
558 return $this->delete($path, $recursive);
564 * @param string $path
565 * @param bool $include_hidden
566 * @param bool $recursive
569 public function dirlist($path, $include_hidden = true, $recursive = false) {
570 if ( $this->is_file($path) ) {
571 $limit_file = basename($path);
572 $path = dirname($path);
577 if ( ! $this->is_dir($path) )
581 $dir = @dir( $this->sftp_path( $path ) );
586 while (false !== ($entry = $dir->read()) ) {
588 $struc['name'] = $entry;
590 if ( '.' == $struc['name'] || '..' == $struc['name'] )
591 continue; //Do not care about these folders.
593 if ( ! $include_hidden && '.' == $struc['name'][0] )
596 if ( $limit_file && $struc['name'] != $limit_file )
599 $struc['perms'] = $this->gethchmod($path.'/'.$entry);
600 $struc['permsn'] = $this->getnumchmodfromh($struc['perms']);
601 $struc['number'] = false;
602 $struc['owner'] = $this->owner($path.'/'.$entry);
603 $struc['group'] = $this->group($path.'/'.$entry);
604 $struc['size'] = $this->size($path.'/'.$entry);
605 $struc['lastmodunix']= $this->mtime($path.'/'.$entry);
606 $struc['lastmod'] = date('M j',$struc['lastmodunix']);
607 $struc['time'] = date('h:i:s',$struc['lastmodunix']);
608 $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f';
610 if ( 'd' == $struc['type'] ) {
612 $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
614 $struc['files'] = array();
617 $ret[ $struc['name'] ] = $struc;