]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/class-wp-filesystem-ssh2.php
Wordpress 4.6
[autoinstalls/wordpress.git] / wp-admin / includes / class-wp-filesystem-ssh2.php
1 <?php
2 /**
3  * WordPress Filesystem Class for implementing SSH2
4  *
5  * To use this class you must follow these steps for PHP 5.2.6+
6  *
7  * @contrib http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ - Installation Notes
8  *
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)
10  *
11  * cd /usr/src
12  * wget http://surfnet.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.14.tar.gz
13  * tar -zxvf libssh2-0.14.tar.gz
14  * cd libssh2-0.14/
15  * ./configure
16  * make all install
17  *
18  * Note: Do not leave the directory yet!
19  *
20  * Enter: pecl install -f ssh2
21  *
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
25  *
26  * Restart Apache!
27  * Check phpinfo() streams to confirm that: ssh2.shell, ssh2.exec, ssh2.tunnel, ssh2.scp, ssh2.sftp  exist.
28  *
29  * Note: as of WordPress 2.8, This utilises the PHP5+ function 'stream_get_contents'
30  *
31  * @since 2.7.0
32  *
33  * @package WordPress
34  * @subpackage Filesystem
35  */
36 class WP_Filesystem_SSH2 extends WP_Filesystem_Base {
37
38         /**
39          * @access public
40          */
41         public $link = false;
42
43         /**
44          * @access public
45          * @var resource
46          */
47         public $sftp_link;
48         public $keys = false;
49
50         /**
51          * @access public
52          *
53          * @param array $opt
54          */
55         public function __construct( $opt = '' ) {
56                 $this->method = 'ssh2';
57                 $this->errors = new WP_Error();
58
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'));
62                         return;
63                 }
64                 if ( !function_exists('stream_get_contents') ) {
65                         $this->errors->add(
66                                 'ssh2_php_requirement',
67                                 sprintf(
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>'
71                                 )
72                         );
73                         return;
74                 }
75
76                 // Set defaults:
77                 if ( empty($opt['port']) )
78                         $this->options['port'] = 22;
79                 else
80                         $this->options['port'] = $opt['port'];
81
82                 if ( empty($opt['hostname']) )
83                         $this->errors->add('empty_hostname', __('SSH2 hostname is required'));
84                 else
85                         $this->options['hostname'] = $opt['hostname'];
86
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'];
91
92                         $this->options['hostkey'] = array('hostkey' => 'ssh-rsa');
93
94                         $this->keys = true;
95                 } elseif ( empty ($opt['username']) ) {
96                         $this->errors->add('empty_username', __('SSH2 username is required'));
97                 }
98
99                 if ( !empty($opt['username']) )
100                         $this->options['username'] = $opt['username'];
101
102                 if ( empty ($opt['password']) ) {
103                         // Password can be blank if we are using keys.
104                         if ( !$this->keys )
105                                 $this->errors->add('empty_password', __('SSH2 password is required'));
106                 } else {
107                         $this->options['password'] = $opt['password'];
108                 }
109         }
110
111         /**
112          * @access public
113          *
114          * @return bool
115          */
116         public function connect() {
117                 if ( ! $this->keys ) {
118                         $this->link = @ssh2_connect($this->options['hostname'], $this->options['port']);
119                 } else {
120                         $this->link = @ssh2_connect($this->options['hostname'], $this->options['port'], $this->options['hostkey']);
121                 }
122
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']
128                                 )
129                         );
130                         return false;
131                 }
132
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']
139                                         )
140                                 );
141                                 return false;
142                         }
143                 } else {
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']
149                                         )
150                                 );
151                                 return false;
152                         }
153                 }
154
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']
161                                 )
162                         );
163                         return false;
164                 }
165
166                 return true;
167         }
168
169         /**
170          * Gets the ssh2.sftp PHP stream wrapper path to open for the given file.
171          *
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.
176          *
177          * @access public
178          *
179          * @since 4.4.0
180          *
181          * @param string $path The File/Directory path on the remote server to return
182          * @return string The ssh2.sftp:// wrapped path to use.
183          */
184         public function sftp_path( $path ) {
185                 if ( '/' === $path ) {
186                         $path = '/./';
187                 }
188                 return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' );
189         }
190
191         /**
192          * @access public
193          * 
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.
198          */
199         public function run_command( $command, $returnbool = false ) {
200                 if ( ! $this->link )
201                         return false;
202
203                 if ( ! ($stream = ssh2_exec($this->link, $command)) ) {
204                         $this->errors->add( 'command',
205                                 /* translators: %s: command */
206                                 sprintf( __( 'Unable to perform command: %s'),
207                                         $command
208                                 )
209                         );
210                 } else {
211                         stream_set_blocking( $stream, true );
212                         stream_set_timeout( $stream, FS_TIMEOUT );
213                         $data = stream_get_contents( $stream );
214                         fclose( $stream );
215
216                         if ( $returnbool )
217                                 return ( $data === false ) ? false : '' != trim($data);
218                         else
219                                 return $data;
220                 }
221                 return false;
222         }
223
224         /**
225          * @access public
226          *
227          * @param string $file
228          * @return string|false
229          */
230         public function get_contents( $file ) {
231                 return file_get_contents( $this->sftp_path( $file ) );
232         }
233
234         /**
235          * @access public
236          *
237          * @param string $file
238          * @return array
239          */
240         public function get_contents_array($file) {
241                 return file( $this->sftp_path( $file ) );
242         }
243
244         /**
245          * @access public
246          *
247          * @param string   $file
248          * @param string   $contents
249          * @param bool|int $mode
250          * @return bool
251          */
252         public function put_contents($file, $contents, $mode = false ) {
253                 $ret = file_put_contents( $this->sftp_path( $file ), $contents );
254
255                 if ( $ret !== strlen( $contents ) )
256                         return false;
257
258                 $this->chmod($file, $mode);
259
260                 return true;
261         }
262
263         /**
264          * @access public
265          *
266          * @return bool
267          */
268         public function cwd() {
269                 $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' );
270                 if ( $cwd ) {
271                         $cwd = trailingslashit( trim( $cwd ) );
272                 }
273                 return $cwd;
274         }
275
276         /**
277          * @access public
278          *
279          * @param string $dir
280          * @return bool|string
281          */
282         public function chdir($dir) {
283                 return $this->run_command('cd ' . $dir, true);
284         }
285
286         /**
287          * @access public
288          *
289          * @param string $file
290          * @param string $group
291          * @param bool   $recursive
292          *
293          * @return bool
294          */
295         public function chgrp($file, $group, $recursive = false ) {
296                 if ( ! $this->exists($file) )
297                         return false;
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);
301         }
302
303         /**
304          * @access public
305          *
306          * @param string $file
307          * @param int    $mode
308          * @param bool   $recursive
309          * @return bool|string
310          */
311         public function chmod($file, $mode = false, $recursive = false) {
312                 if ( ! $this->exists($file) )
313                         return false;
314
315                 if ( ! $mode ) {
316                         if ( $this->is_file($file) )
317                                 $mode = FS_CHMOD_FILE;
318                         elseif ( $this->is_dir($file) )
319                                 $mode = FS_CHMOD_DIR;
320                         else
321                                 return false;
322                 }
323
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);
327         }
328
329         /**
330          * Change the ownership of a file / folder.
331          *
332          * @access public
333          *
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.
338          */
339         public function chown( $file, $owner, $recursive = false ) {
340                 if ( ! $this->exists($file) )
341                         return false;
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);
345         }
346
347         /**
348          * @access public
349          *
350          * @param string $file
351          * @return string|false
352          */
353         public function owner($file) {
354                 $owneruid = @fileowner( $this->sftp_path( $file ) );
355                 if ( ! $owneruid )
356                         return false;
357                 if ( ! function_exists('posix_getpwuid') )
358                         return $owneruid;
359                 $ownerarray = posix_getpwuid($owneruid);
360                 return $ownerarray['name'];
361         }
362
363         /**
364          * @access public
365          *
366          * @param string $file
367          * @return string
368          */
369         public function getchmod($file) {
370                 return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 );
371         }
372
373         /**
374          * @access public
375          *
376          * @param string $file
377          * @return string|false
378          */
379         public function group($file) {
380                 $gid = @filegroup( $this->sftp_path( $file ) );
381                 if ( ! $gid )
382                         return false;
383                 if ( ! function_exists('posix_getgrgid') )
384                         return $gid;
385                 $grouparray = posix_getgrgid($gid);
386                 return $grouparray['name'];
387         }
388
389         /**
390          * @access public
391          *
392          * @param string   $source
393          * @param string   $destination
394          * @param bool     $overwrite
395          * @param int|bool $mode
396          * @return bool
397          */
398         public function copy($source, $destination, $overwrite = false, $mode = false) {
399                 if ( ! $overwrite && $this->exists($destination) )
400                         return false;
401                 $content = $this->get_contents($source);
402                 if ( false === $content)
403                         return false;
404                 return $this->put_contents($destination, $content, $mode);
405         }
406
407         /**
408          * @access public
409          *
410          * @param string $source
411          * @param string $destination
412          * @param bool   $overwrite
413          * @return bool
414          */
415         public function move($source, $destination, $overwrite = false) {
416                 return @ssh2_sftp_rename( $this->sftp_link, $source, $destination );
417         }
418
419         /**
420          * @access public
421          *
422          * @param string      $file
423          * @param bool        $recursive
424          * @param string|bool $type
425          * @return bool
426          */
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);
430                 if ( ! $recursive )
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']);
436                         }
437                 }
438                 return ssh2_sftp_rmdir($this->sftp_link, $file);
439         }
440
441         /**
442          * @access public
443          *
444          * @param string $file
445          * @return bool
446          */
447         public function exists($file) {
448                 return file_exists( $this->sftp_path( $file ) );
449         }
450
451         /**
452          * @access public
453          *
454          * @param string $file
455          * @return bool
456          */
457         public function is_file($file) {
458                 return is_file( $this->sftp_path( $file ) );
459         }
460
461         /**
462          * @access public
463          *
464          * @param string $path
465          * @return bool
466          */
467         public function is_dir($path) {
468                 return is_dir( $this->sftp_path( $path ) );
469         }
470
471         /**
472          * @access public
473          *
474          * @param string $file
475          * @return bool
476          */
477         public function is_readable($file) {
478                 return is_readable( $this->sftp_path( $file ) );
479         }
480
481         /**
482          * @access public
483          *
484          * @param string $file
485          * @return bool
486          */
487         public function is_writable($file) {
488                 // PHP will base it's writable checks on system_user === file_owner, not ssh_user === file_owner
489                 return true;
490         }
491
492         /**
493          * @access public
494          *
495          * @param string $file
496          * @return int
497          */
498         public function atime($file) {
499                 return fileatime( $this->sftp_path( $file ) );
500         }
501
502         /**
503          * @access public
504          *
505          * @param string $file
506          * @return int
507          */
508         public function mtime($file) {
509                 return filemtime( $this->sftp_path( $file ) );
510         }
511
512         /**
513          * @access public
514          *
515          * @param string $file
516          * @return int
517          */
518         public function size($file) {
519                 return filesize( $this->sftp_path( $file ) );
520         }
521
522         /**
523          * @access public
524          *
525          * @param string $file
526          * @param int    $time
527          * @param int    $atime
528          */
529         public function touch($file, $time = 0, $atime = 0) {
530                 //Not implemented.
531         }
532
533         /**
534          * @access public
535          *
536          * @param string $path
537          * @param mixed  $chmod
538          * @param mixed  $chown
539          * @param mixed  $chgrp
540          * @return bool
541          */
542         public function mkdir($path, $chmod = false, $chown = false, $chgrp = false) {
543                 $path = untrailingslashit($path);
544                 if ( empty($path) )
545                         return false;
546
547                 if ( ! $chmod )
548                         $chmod = FS_CHMOD_DIR;
549                 if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) )
550                         return false;
551                 if ( $chown )
552                         $this->chown($path, $chown);
553                 if ( $chgrp )
554                         $this->chgrp($path, $chgrp);
555                 return true;
556         }
557
558         /**
559          * @access public
560          *
561          * @param string $path
562          * @param bool   $recursive
563          * @return bool
564          */
565         public function rmdir($path, $recursive = false) {
566                 return $this->delete($path, $recursive);
567         }
568
569         /**
570          * @access public
571          *
572          * @param string $path
573          * @param bool   $include_hidden
574          * @param bool   $recursive
575          * @return bool|array
576          */
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);
581                 } else {
582                         $limit_file = false;
583                 }
584
585                 if ( ! $this->is_dir($path) )
586                         return false;
587
588                 $ret = array();
589                 $dir = @dir( $this->sftp_path( $path ) );
590
591                 if ( ! $dir )
592                         return false;
593
594                 while (false !== ($entry = $dir->read()) ) {
595                         $struc = array();
596                         $struc['name'] = $entry;
597
598                         if ( '.' == $struc['name'] || '..' == $struc['name'] )
599                                 continue; //Do not care about these folders.
600
601                         if ( ! $include_hidden && '.' == $struc['name'][0] )
602                                 continue;
603
604                         if ( $limit_file && $struc['name'] != $limit_file )
605                                 continue;
606
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';
617
618                         if ( 'd' == $struc['type'] ) {
619                                 if ( $recursive )
620                                         $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
621                                 else
622                                         $struc['files'] = array();
623                         }
624
625                         $ret[ $struc['name'] ] = $struc;
626                 }
627                 $dir->close();
628                 unset($dir);
629                 return $ret;
630         }
631 }