WP_Filesystem_SSH2::connectpublicWP 2.7.0

Connects filesystem.

Method of the class: WP_Filesystem_SSH2{}

No Hooks.

Returns

true|false. True on success, false on failure.

Usage

$WP_Filesystem_SSH2 = new WP_Filesystem_SSH2();
$WP_Filesystem_SSH2->connect();

Changelog

Since 2.7.0 Introduced.

WP_Filesystem_SSH2::connect() code WP 7.1

public function connect() {
	/*
	 * Bail if the constructor recorded a configuration error. Connection and
	 * authentication errors are excluded so that a failed connection attempt
	 * can be retried on the same instance.
	 */
	if ( $this->errors->has_errors() && ! array_intersect( array( 'connect', 'auth' ), $this->errors->get_error_codes() ) ) {
		return false;
	}

	if ( ! isset( $this->options['hostkey'] ) ) {
		$this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'] );
	} else {
		$this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'], $this->options['hostkey'] );
	}

	if ( ! $this->link ) {
		$this->errors->add(
			'connect',
			sprintf(
				/* translators: %s: hostname:port */
				__( 'Failed to connect to SSH2 Server %s' ),
				$this->options['hostname'] . ':' . $this->options['port']
			)
		);

		return false;
	}

	if ( ! $this->keys ) {
		if ( ! @ssh2_auth_password( $this->link, $this->options['username'], $this->options['password'] ?? '' ) ) {
			$this->errors->add(
				'auth',
				sprintf(
					/* translators: %s: Username. */
					__( 'Username/Password incorrect for %s' ),
					$this->options['username']
				)
			);

			return false;
		}
	} 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(
					/* translators: %s: Username. */
					__( 'Public and Private keys incorrect for %s' ),
					$this->options['username']
				)
			);

			return false;
		}
	}

	$this->sftp_link = ssh2_sftp( $this->link );

	if ( ! $this->sftp_link ) {
		$this->errors->add(
			'connect',
			sprintf(
				/* translators: %s: hostname:port */
				__( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ),
				$this->options['hostname'] . ':' . $this->options['port']
			)
		);

		return false;
	}

	return true;
}