host = $host; $this->user = $user; $this->pass = $pass; $this->port = $port ?: 21; $this->timeout = $timeout ?: 90; $this->use_ssl = function_exists( 'ftp_ssl_connect' ) && $use_ssl; $this->passive = (bool) $passive; $this->resource = null; } /** * @inheritdoc */ public function connect() { // Don't execute the connection twice. if ( $this->resource ) { return $this; } if ( ! function_exists( 'ftp_connect' ) ) { throw new \BackWPup_Destination_Connect_Exception( 'Function ftp_connect does not exists. No way to connect to the server.' ); } // Default connection type. $resource = ftp_connect( $this->host, $this->port, $this->timeout ); // Can be connected over ssl? if ( $this->use_ssl ) { $resource = ftp_ssl_connect( $this->host, $this->port, $this->timeout ); } if ( ! $resource ) { throw new \BackWPup_Destination_Connect_Exception( 'Something went wrong during FTP connection. Seems not possible to connect to the service.' ); } $this->resource = $resource; if ( ! $this->login() ) { throw new BackWPup_Destination_Connect_Exception( 'Something went wrong during FTP connection. Seems not possible to connect to the service.' ); } ftp_pasv( $this->resource, $this->passive ); return $this; } /** * @inheritdoc */ public function resource() { return $this->resource; } /** * Get the FTP URL * * @param string $path The path to the FTP file * * @return string The URL to the FTP server. */ public function getURL( $path = null ) { if ( $path !== null && substr( $path, 0, 1 ) != '/' ) { $path = '/' . $path; } return ( $this->use_ssl ? 'ftps://' : 'ftp://' ) . rawurlencode( $this->user ) . ':' . rawurlencode( $this->pass ) . '@' . rawurlencode( $this->host ) . ':' . intval( $this->port ) . $path; } /** * Login * * Perform a login to the service. * * @throws BackWPup_Destination_Connect_Exception In case isn't possible to login. * * @since 3.5.0 * * @return bool True if was able to login, false otherwise. */ private function login() { $response = false; if ( ftp_login( $this->resource, $this->user, $this->pass ) ) { $response = true; } if ( ! $response ) { ftp_raw( $this->resource, 'USER ' . $this->user ); $response = ftp_raw( $this->resource, 'PASS ' . $this->pass ); } // Since the ftp_raw returns an array, we check for false value. if ( is_array( $response ) && substr( trim( $response[0] ), 0, 3 ) > 400 ) { $response = false; } return $response; } }