| 1 |
<?php |
| 2 |
|
| 3 |
namespace LIBRARY; |
| 4 |
|
| 5 |
class Downloader { |
| 6 |
private $download_directory_path = ''; |
| 7 |
|
| 8 |
public function __construct( $download_directory_path = '' ) { |
| 9 |
$this->set_download_directory_path( $download_directory_path ); |
| 10 |
} |
| 11 |
|
| 12 |
|
| 13 |
public function download_file( $url, $filename ) { |
| 14 |
$content = $this->get_content_from_url( $url ); |
| 15 |
|
| 16 |
if ( is_wp_error( $content ) ) { |
| 17 |
return $content; |
| 18 |
} |
| 19 |
|
| 20 |
return Helpers::write_to_file( $content, $this->download_directory_path . $filename ); |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
private function get_content_from_url( $url ) { |
| 25 |
if ( empty( $url ) ) { |
| 26 |
return new \WP_Error( |
| 27 |
'missing_url', |
| 28 |
__( 'Missing URL for downloading a file!', 'borderless' ) |
| 29 |
); |
| 30 |
} |
| 31 |
|
| 32 |
$response = wp_remote_get( |
| 33 |
$url, |
| 34 |
array( 'timeout' => Helpers::apply_filters( 'library/timeout_for_downloading_import_file', 20 ) ) |
| 35 |
); |
| 36 |
|
| 37 |
if ( is_wp_error( $response ) || 200 !== $response['response']['code'] ) { |
| 38 |
$response_error = $this->get_error_from_response( $response ); |
| 39 |
|
| 40 |
return new \WP_Error( |
| 41 |
'download_error', |
| 42 |
sprintf( |
| 43 |
__( 'An error occurred while fetching file from: %1$s%2$s%3$s!%4$sReason: %5$s - %6$s.', 'borderless' ), |
| 44 |
'<strong>', |
| 45 |
$url, |
| 46 |
'</strong>', |
| 47 |
'<br>', |
| 48 |
$response_error['error_code'], |
| 49 |
$response_error['error_message'] |
| 50 |
) . '<br>' . |
| 51 |
Helpers::apply_filters( 'library/message_after_file_fetching_error', '' ) |
| 52 |
); |
| 53 |
} |
| 54 |
|
| 55 |
return wp_remote_retrieve_body( $response ); |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
private function get_error_from_response( $response ) { |
| 60 |
$response_error = array(); |
| 61 |
|
| 62 |
if ( is_array( $response ) ) { |
| 63 |
$response_error['error_code'] = $response['response']['code']; |
| 64 |
$response_error['error_message'] = $response['response']['message']; |
| 65 |
} |
| 66 |
else { |
| 67 |
$response_error['error_code'] = $response->get_error_code(); |
| 68 |
$response_error['error_message'] = $response->get_error_message(); |
| 69 |
} |
| 70 |
|
| 71 |
return $response_error; |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
public function get_download_directory_path() { |
| 76 |
return $this->download_directory_path; |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
public function set_download_directory_path( $download_directory_path ) { |
| 81 |
if ( file_exists( $download_directory_path ) ) { |
| 82 |
$this->download_directory_path = $download_directory_path; |
| 83 |
} |
| 84 |
else { |
| 85 |
$upload_dir = wp_upload_dir(); |
| 86 |
$this->download_directory_path = Helpers::apply_filters( 'library/upload_file_path', trailingslashit( $upload_dir['path'] ) ); |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
|