<?php
/**
- * WordPress SSH2 Filesystem.
- *
- * @package WordPress
- * @subpackage Filesystem
- */
-
-/**
- * WordPress Filesystem Class for implementing SSH2.
+ * WordPress Filesystem Class for implementing SSH2
*
* To use this class you must follow these steps for PHP 5.2.6+
*
* @contrib http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ - Installation Notes
*
- * Complie libssh2 (Note: Only 0.14 is officaly working with PHP 5.2.6+ right now.)
+ * 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)
*
* cd /usr/src
* wget http://surfnet.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.14.tar.gz
* ./configure
* make all install
*
- * Note: No not leave the directory yet!
+ * Note: Do not leave the directory yet!
*
* Enter: pecl install -f ssh2
*
* Restart Apache!
* Check phpinfo() streams to confirm that: ssh2.shell, ssh2.exec, ssh2.tunnel, ssh2.scp, ssh2.sftp exist.
*
+ * Note: as of WordPress 2.8, This utilises the PHP5+ function 'stream_get_contents'
+ *
+ * @since 2.7.0
*
- * @since 2.7
* @package WordPress
* @subpackage Filesystem
- * @uses WP_Filesystem_Base Extends class
*/
class WP_Filesystem_SSH2 extends WP_Filesystem_Base {
- var $debugtest = false; // set this to true only if your a debuging your connection
+ public $link = false;
+ public $sftp_link = false;
+ public $keys = false;
+ public $errors = array();
+ public $options = array();
- var $link = null;
- var $sftp_link = null;
- var $keys = false;
- /*
- * This is the timeout value for ssh results to comeback.
- * Slower servers might need this incressed, but this number otherwise should not change.
- *
- * @parm $timeout int
- *
- */
- var $timeout = 15;
- var $errors = array();
- var $options = array();
-
- var $permission = 0644;
-
- function WP_Filesystem_SSH2($opt='') {
+ public function __construct($opt='') {
$this->method = 'ssh2';
$this->errors = new WP_Error();
$this->errors->add('no_ssh2_ext', __('The ssh2 PHP extension is not available'));
return false;
}
+ if ( !function_exists('stream_get_contents') ) {
+ $this->errors->add('ssh2_php_requirement', __('The ssh2 PHP extension is available, however, we require the PHP5 function <code>stream_get_contents()</code>'));
+ return false;
+ }
// Set defaults:
if ( empty($opt['port']) )
else
$this->options['hostname'] = $opt['hostname'];
- if ( isset($opt['base']) && ! empty($opt['base']) )
+ if ( ! empty($opt['base']) )
$this->wp_base = $opt['base'];
// Check if the options provided are OK.
- if ( empty ($opt['username']) )
- $this->errors->add('empty_username', __('SSH2 username is required'));
- else
- $this->options['username'] = $opt['username'];
-
- if ( ( !empty ($opt['public_key']) ) && ( !empty ($opt['private_key']) ) ) {
+ if ( !empty ($opt['public_key']) && !empty ($opt['private_key']) ) {
$this->options['public_key'] = $opt['public_key'];
$this->options['private_key'] = $opt['private_key'];
- $this->options['hostkey'] = array("hostkey" => "ssh-rsa");
+ $this->options['hostkey'] = array('hostkey' => 'ssh-rsa');
$this->keys = true;
+ } elseif ( empty ($opt['username']) ) {
+ $this->errors->add('empty_username', __('SSH2 username is required'));
}
+ if ( !empty($opt['username']) )
+ $this->options['username'] = $opt['username'];
if ( empty ($opt['password']) ) {
- if ( !$this->keys ) // password can be blank if we are using keys
+ // Password can be blank if we are using keys.
+ if ( !$this->keys )
$this->errors->add('empty_password', __('SSH2 password is required'));
} else {
$this->options['password'] = $opt['password'];
}
- function connect() {
- $this->debug("connect();");
-
+ public function connect() {
if ( ! $this->keys ) {
$this->link = @ssh2_connect($this->options['hostname'], $this->options['port']);
} else {
}
} else {
if ( ! @ssh2_auth_pubkey_file($this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) {
- $this->errors->add('auth', sprintf(__('Public and Private keys incorrent for %s'), $this->options['username']));
+ $this->errors->add('auth', sprintf(__('Public and Private keys incorrect for %s'), $this->options['username']));
return false;
}
}
return true;
}
- function run_command($link, $command, $returnbool = false) {
- $this->debug("run_command();");
- if(!($stream = @ssh2_exec( $link, $command . "; echo \"__COMMAND_FINISHED__\";"))) {
+ public function run_command( $command, $returnbool = false) {
+
+ if ( ! $this->link )
+ return false;
+
+ if ( ! ($stream = ssh2_exec($this->link, $command)) ) {
$this->errors->add('command', sprintf(__('Unable to perform command: %s'), $command));
} else {
stream_set_blocking( $stream, true );
- $time_start = time();
- $data = null;
- while( true ) {
- if (strpos($data,"__COMMAND_FINISHED__") !== false){
- break; // the command has finshed!
- }
- if( (time()-$time_start) > $this->timeout ){
- $this->errors->add('command', sprintf(__('Connection to the server has timeout after %s seconds.'), $this->timeout));
- unset($this->link);
- unset($this->sftp_link); // close connections
- return false;
- }
- while( $buf = fread( $stream, strlen($stream) ) )
- $data .= $buf;
- }
- fclose($stream);
- $data = trim(str_replace("__COMMAND_FINISHED__", "", $data));
- if (($returnbool) && ( (int) $data )) {
- return true;
- } elseif (($returnbool) && (! (int) $data )) {
- return false;
- } else {
+ stream_set_timeout( $stream, FS_TIMEOUT );
+ $data = stream_get_contents( $stream );
+ fclose( $stream );
+
+ if ( $returnbool )
+ return ( $data === false ) ? false : '' != trim($data);
+ else
return $data;
- }
}
return false;
}
- function debug($text)
- {
- if ($this->debugtest)
- {
- echo "<br/>" . $text . "<br/>";
- }
+ public function get_contents( $file ) {
+ $file = ltrim($file, '/');
+ return file_get_contents('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function setDefaultPermissions($perm) {
- $this->debug("setDefaultPermissions();");
- if ( $perm )
- $this->permission = $perm;
+ public function get_contents_array($file) {
+ $file = ltrim($file, '/');
+ return file('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function get_contents($file, $type = '', $resumepos = 0 ) {
- $this->debug("get_contents();");
- $tempfile = wp_tempnam( $file );
- if ( ! $tempfile )
- return false;
- if( ! ssh2_scp_recv($this->link, $file, $tempfile) )
+ public function put_contents($file, $contents, $mode = false ) {
+ $ret = file_put_contents( 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $file, '/' ), $contents );
+
+ if ( $ret !== strlen( $contents ) )
return false;
- $contents = file_get_contents($tempfile);
- unlink($tempfile);
- return $contents;
- }
- function get_contents_array($file) {
- $this->debug("get_contents_array();");
- return explode("\n", $this->get_contents($file));
- }
+ $this->chmod($file, $mode);
- function put_contents($file, $contents, $type = '' ) {
- $this->debug("put_contents($file);");
- $tempfile = wp_tempnam( $file );
- $temp = fopen($tempfile, 'w');
- if ( ! $temp )
- return false;
- fwrite($temp, $contents);
- fclose($temp);
- $ret = ssh2_scp_send($this->link, $tempfile, $file, $this->permission);
- unlink($tempfile);
- return $ret;
+ return true;
}
- function cwd() {
- $this->debug("cwd();");
- $cwd = $this->run_command($this->link, 'pwd');
- if( $cwd )
+ public function cwd() {
+ $cwd = $this->run_command('pwd');
+ if ( $cwd )
$cwd = trailingslashit($cwd);
return $cwd;
}
- function chdir($dir) {
- $this->debug("chdir();");
- return $this->run_command($this->link, 'cd ' . $dir, true);
+ public function chdir($dir) {
+ return $this->run_command('cd ' . $dir, true);
}
- function chgrp($file, $group, $recursive = false ) {
- $this->debug("chgrp();");
+ public function chgrp($file, $group, $recursive = false ) {
if ( ! $this->exists($file) )
return false;
if ( ! $recursive || ! $this->is_dir($file) )
- return $this->run_command($this->link, sprintf('chgrp %o %s', $mode, $file), true);
- return $this->run_command($this->link, sprintf('chgrp -R %o %s', $mode, $file), true);
+ return $this->run_command(sprintf('chgrp %s %s', escapeshellarg($group), escapeshellarg($file)), true);
+ return $this->run_command(sprintf('chgrp -R %s %s', escapeshellarg($group), escapeshellarg($file)), true);
}
- function chmod($file, $mode = false, $recursive = false) {
- $this->debug("chmod();");
- if( ! $mode )
- $mode = $this->permission;
- if( ! $mode )
- return false;
+ public function chmod($file, $mode = false, $recursive = false) {
if ( ! $this->exists($file) )
return false;
+
+ if ( ! $mode ) {
+ if ( $this->is_file($file) )
+ $mode = FS_CHMOD_FILE;
+ elseif ( $this->is_dir($file) )
+ $mode = FS_CHMOD_DIR;
+ else
+ return false;
+ }
+
if ( ! $recursive || ! $this->is_dir($file) )
- return $this->run_command($this->link, sprintf('chmod %o %s', $mode, $file), true);
- return $this->run_command($this->link, sprintf('chmod -R %o %s', $mode, $file), true);
+ return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true);
+ return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true);
}
- function chown($file, $owner, $recursive = false ) {
- $this->debug("chown();");
+ /**
+ * Change the ownership of a file / folder.
+ *
+ * @since Unknown
+ *
+ * @param string $file Path to the file.
+ * @param mixed $owner A user name or number.
+ * @param bool $recursive Optional. If set True changes file owner recursivly. Defaults to False.
+ * @return bool Returns true on success or false on failure.
+ */
+ public function chown( $file, $owner, $recursive = false ) {
if ( ! $this->exists($file) )
return false;
if ( ! $recursive || ! $this->is_dir($file) )
- return $this->run_command($this->link, sprintf('chown %o %s', $mode, $file), true);
- return $this->run_command($this->link, sprintf('chown -R %o %s', $mode, $file), true);
+ return $this->run_command(sprintf('chown %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
+ return $this->run_command(sprintf('chown -R %s %s', escapeshellarg($owner), escapeshellarg($file)), true);
}
- function owner($file) {
- $this->debug("owner();");
- $dir = $this->dirlist($file);
- return $dir[$file]['owner'];
+ public function owner($file) {
+ $owneruid = @fileowner('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/'));
+ if ( ! $owneruid )
+ return false;
+ if ( ! function_exists('posix_getpwuid') )
+ return $owneruid;
+ $ownerarray = posix_getpwuid($owneruid);
+ return $ownerarray['name'];
}
- function getchmod($file) {
- $this->debug("getchmod();");
- $dir = $this->dirlist($file);
- return $dir[$file]['permsn'];
+ public function getchmod($file) {
+ return substr( decoct( @fileperms( 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $file, '/' ) ) ), -3 );
}
- function group($file) {
- $this->debug("group();");
- $dir = $this->dirlist($file);
- return $dir[$file]['group'];
+ public function group($file) {
+ $gid = @filegroup('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/'));
+ if ( ! $gid )
+ return false;
+ if ( ! function_exists('posix_getgrgid') )
+ return $gid;
+ $grouparray = posix_getgrgid($gid);
+ return $grouparray['name'];
}
- function copy($source, $destination, $overwrite = false ) {
- $this->debug("copy();");
- if( ! $overwrite && $this->exists($destination) )
+ public function copy($source, $destination, $overwrite = false, $mode = false) {
+ if ( ! $overwrite && $this->exists($destination) )
return false;
$content = $this->get_contents($source);
- if( false === $content)
+ if ( false === $content)
return false;
- return $this->put_contents($destination, $content);
+ return $this->put_contents($destination, $content, $mode);
}
- function move($source, $destination, $overwrite = false) {
- $this->debug("move();");
+ public function move($source, $destination, $overwrite = false) {
return @ssh2_sftp_rename($this->link, $source, $destination);
}
- function delete($file, $recursive = false) {
- $this->debug("delete();");
- if ( $this->is_file($file) )
+ public function delete($file, $recursive = false, $type = false) {
+ if ( 'f' == $type || $this->is_file($file) )
return ssh2_sftp_unlink($this->sftp_link, $file);
if ( ! $recursive )
return ssh2_sftp_rmdir($this->sftp_link, $file);
$filelist = $this->dirlist($file);
if ( is_array($filelist) ) {
foreach ( $filelist as $filename => $fileinfo) {
- $this->delete($file . '/' . $filename, $recursive);
+ $this->delete($file . '/' . $filename, $recursive, $fileinfo['type']);
}
}
return ssh2_sftp_rmdir($this->sftp_link, $file);
}
- function exists($file) {
- $this->debug("exists();");
- return $this->run_command($this->link, sprintf('ls -lad %s', $file), true);
+ public function exists($file) {
+ $file = ltrim($file, '/');
+ return file_exists('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function is_file($file) {
- $this->debug("is_file();");
- //DO NOT RELY ON dirlist()!
- $list = $this->run_command($this->link, sprintf('ls -lad %s', $file));
- $list = $this->parselisting($list);
- if ( ! $list )
- return false;
- else
- return ( !$list['isdir'] && !$list['islink'] ); //ie. not a file or link, yet exists, must be file.
+ public function is_file($file) {
+ $file = ltrim($file, '/');
+ return is_file('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function is_dir($path) {
- $this->debug("is_dir();");
- //DO NOT RELY ON dirlist()!
- $list = $this->parselisting($this->run_command($this->link, sprintf('ls -lad %s', untrailingslashit($path))));
- if ( ! $list )
- return false;
- else
- return $list['isdir'];
+ public function is_dir($path) {
+ $path = ltrim($path, '/');
+ return is_dir('ssh2.sftp://' . $this->sftp_link . '/' . $path);
}
- function is_readable($file) {
- //Not implmented.
+ public function is_readable($file) {
+ $file = ltrim($file, '/');
+ return is_readable('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function is_writable($file) {
- //Not implmented.
+ public function is_writable($file) {
+ $file = ltrim($file, '/');
+ return is_writable('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function atime($file) {
- //Not implmented.
+ public function atime($file) {
+ $file = ltrim($file, '/');
+ return fileatime('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function mtime($file) {
- //Not implmented.
+ public function mtime($file) {
+ $file = ltrim($file, '/');
+ return filemtime('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function size($file) {
- //Not implmented.
+ public function size($file) {
+ $file = ltrim($file, '/');
+ return filesize('ssh2.sftp://' . $this->sftp_link . '/' . $file);
}
- function touch($file, $time = 0, $atime = 0) {
- //Not implmented.
+ public function touch($file, $time = 0, $atime = 0) {
+ //Not implemented.
}
- function mkdir($path, $chmod = null, $chown = false, $chgrp = false) {
- $this->debug("mkdir();");
+ public function mkdir($path, $chmod = false, $chown = false, $chgrp = false) {
$path = untrailingslashit($path);
- if( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
+ if ( empty($path) )
return false;
- if( $chown )
+
+ if ( ! $chmod )
+ $chmod = FS_CHMOD_DIR;
+ if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
+ return false;
+ if ( $chown )
$this->chown($path, $chown);
- if( $chgrp )
+ if ( $chgrp )
$this->chgrp($path, $chgrp);
return true;
}
- function rmdir($path, $recursive = false) {
- $this->debug("rmdir();");
+ public function rmdir($path, $recursive = false) {
return $this->delete($path, $recursive);
}
- function parselisting($line) {
- $this->debug("parselisting();");
- $is_windows = ($this->OS_remote == FTP_OS_Windows);
- if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/", $line, $lucifer)) {
- $b = array();
- if ($lucifer[3]<70) { $lucifer[3] +=2000; } else { $lucifer[3]+=1900; } // 4digit year fix
- $b['isdir'] = ($lucifer[7]=="<DIR>");
- if ( $b['isdir'] )
- $b['type'] = 'd';
- else
- $b['type'] = 'f';
- $b['size'] = $lucifer[7];
- $b['month'] = $lucifer[1];
- $b['day'] = $lucifer[2];
- $b['year'] = $lucifer[3];
- $b['hour'] = $lucifer[4];
- $b['minute'] = $lucifer[5];
- $b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]);
- $b['am/pm'] = $lucifer[6];
- $b['name'] = $lucifer[8];
- } else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) {
- //echo $line."\n";
- $lcount=count($lucifer);
- if ($lcount<8) return '';
- $b = array();
- $b['isdir'] = $lucifer[0]{0} === "d";
- $b['islink'] = $lucifer[0]{0} === "l";
- if ( $b['isdir'] )
- $b['type'] = 'd';
- elseif ( $b['islink'] )
- $b['type'] = 'l';
- else
- $b['type'] = 'f';
- $b['perms'] = $lucifer[0];
- $b['number'] = $lucifer[1];
- $b['owner'] = $lucifer[2];
- $b['group'] = $lucifer[3];
- $b['size'] = $lucifer[4];
- if ($lcount==8) {
- sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']);
- sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']);
- $b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']);
- $b['name'] = $lucifer[7];
- } else {
- $b['month'] = $lucifer[5];
- $b['day'] = $lucifer[6];
- if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) {
- $b['year'] = date("Y");
- $b['hour'] = $l2[1];
- $b['minute'] = $l2[2];
- } else {
- $b['year'] = $lucifer[7];
- $b['hour'] = 0;
- $b['minute'] = 0;
- }
- $b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute']));
- $b['name'] = $lucifer[8];
- }
- }
-
- return $b;
- }
-
- function dirlist($path = '.', $incdot = false, $recursive = false) {
- $this->debug("dirlist();");
- if( $this->is_file($path) ) {
- $limitFile = basename($path);
- $path = trailingslashit(dirname($path));
+ public function dirlist($path, $include_hidden = true, $recursive = false) {
+ if ( $this->is_file($path) ) {
+ $limit_file = basename($path);
+ $path = dirname($path);
} else {
- $limitFile = false;
+ $limit_file = false;
}
- $list = $this->run_command($this->link, sprintf('ls -la %s', $path));
-
- if ( $list === false )
+ if ( ! $this->is_dir($path) )
return false;
- $list = explode("\n", $list);
+ $ret = array();
+ $dir = @dir('ssh2.sftp://' . $this->sftp_link .'/' . ltrim($path, '/') );
- $dirlist = array();
- foreach ( (array)$list as $k => $v ) {
- $entry = $this->parselisting($v);
- if ( empty($entry) )
- continue;
+ if ( ! $dir )
+ return false;
- if ( '.' == $entry['name'] || '..' == $entry['name'] )
- continue;
+ while (false !== ($entry = $dir->read()) ) {
+ $struc = array();
+ $struc['name'] = $entry;
- $dirlist[ $entry['name'] ] = $entry;
- }
+ if ( '.' == $struc['name'] || '..' == $struc['name'] )
+ continue; //Do not care about these folders.
- if ( ! $dirlist )
- return false;
+ if ( ! $include_hidden && '.' == $struc['name'][0] )
+ continue;
- if ( empty($dirlist) )
- return array();
+ if ( $limit_file && $struc['name'] != $limit_file )
+ continue;
- $ret = array();
- foreach ( $dirlist as $struc ) {
+ $struc['perms'] = $this->gethchmod($path.'/'.$entry);
+ $struc['permsn'] = $this->getnumchmodfromh($struc['perms']);
+ $struc['number'] = false;
+ $struc['owner'] = $this->owner($path.'/'.$entry);
+ $struc['group'] = $this->group($path.'/'.$entry);
+ $struc['size'] = $this->size($path.'/'.$entry);
+ $struc['lastmodunix']= $this->mtime($path.'/'.$entry);
+ $struc['lastmod'] = date('M j',$struc['lastmodunix']);
+ $struc['time'] = date('h:i:s',$struc['lastmodunix']);
+ $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f';
if ( 'd' == $struc['type'] ) {
- $struc['files'] = array();
-
- if ( $incdot ){
- //We're including the doted starts
- if( '.' != $struc['name'] && '..' != $struc['name'] ){ //Ok, It isnt a special folder
- if ($recursive)
- $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive);
- }
- } else { //No dots
- if ( $recursive )
- $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive);
- }
+ if ( $recursive )
+ $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
+ else
+ $struc['files'] = array();
}
- //File
- $ret[$struc['name']] = $struc;
+
+ $ret[ $struc['name'] ] = $struc;
}
+ $dir->close();
+ unset($dir);
return $ret;
}
- function __destruct() {
- $this->debug("__destruct();");
- if ( $this->link )
- unset($this->link);
- if ( $this->sftp_link )
- unset($this->sftp_link);
- }
}
-
-?>