data = $data; $this->base_url = $base_url; $this->s3_client(); } /** * Clean stuffs */ public function __destruct() { fclose( $this->local_file_handler ); } /** * @inheritdoc */ public function download_chunk( $start_byte, $end_byte ) { $file = $this->s3_client->getObject( array( 'Bucket' => BackWPup_Option::get( $this->data->job_id(), self::OPTION_BUCKET ), 'Key' => $this->data->source_file_path(), 'Range' => 'bytes=' . $start_byte . '-' . $end_byte, ) ); if ( empty( $file['ContentType'] ) || $file['ContentLength'] === 0 ) { throw new \RuntimeException( __( 'Could not write data to file. Empty source file.', 'backwpup' ) ); } $this->local_file_handler( $start_byte ); $bytes = (int) fwrite( $this->local_file_handler, (string) $file['Body'] ); if ( $bytes === 0 ) { throw new \RuntimeException( __( 'Could not write data to file.', 'backwpup' ) ); } } /** * @inheritdoc */ public function calculate_size() { $file = $this->s3_client->getObject( array( 'Bucket' => BackWPup_Option::get( $this->data->job_id(), self::OPTION_BUCKET ), 'Key' => $this->data->source_file_path(), ) ); return (int) ( ! empty( $file['ContentType'] ) ? $file['ContentLength'] : 0 ); } /** * @param int $start_byte */ private function local_file_handler( $start_byte ) { if ( is_resource( $this->local_file_handler ) ) { return; } $this->local_file_handler = fopen( $this->data->local_file_path(), $start_byte == 0 ? 'wb' : 'ab' ); if ( ! is_resource( $this->local_file_handler ) ) { throw new \RuntimeException( __( 'File could not be opened for writing.', 'backwpup' ) ); } } /** * Build S3 Client */ private function s3_client() { if ( $this->s3_client ) { return; } $region = $this->base_url; if (!$region) { $region = BackWPup_Option::get($this->data->job_id(), self::OPTION_REGION); } $aws_destination = BackWPup_S3_Destination::fromOption($region); $this->s3_client = $aws_destination->client( BackWPup_Option::get($this->data->job_id(), self::OPTION_ACCESS_KEY), BackWPup_Option::get($this->data->job_id(), self::OPTION_SECRET_KEY) ); } }