暂无描述

class-wc-download-handler.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. <?php
  2. /**
  3. * Download handler
  4. *
  5. * Handle digital downloads.
  6. *
  7. * @package WooCommerce\Classes
  8. * @version 2.2.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Download handler class.
  13. */
  14. class WC_Download_Handler {
  15. /**
  16. * Hook in methods.
  17. */
  18. public static function init() {
  19. if ( isset( $_GET['download_file'], $_GET['order'] ) && ( isset( $_GET['email'] ) || isset( $_GET['uid'] ) ) ) { // WPCS: input var ok, CSRF ok.
  20. add_action( 'init', array( __CLASS__, 'download_product' ) );
  21. }
  22. add_action( 'woocommerce_download_file_redirect', array( __CLASS__, 'download_file_redirect' ), 10, 2 );
  23. add_action( 'woocommerce_download_file_xsendfile', array( __CLASS__, 'download_file_xsendfile' ), 10, 2 );
  24. add_action( 'woocommerce_download_file_force', array( __CLASS__, 'download_file_force' ), 10, 2 );
  25. }
  26. /**
  27. * Check if we need to download a file and check validity.
  28. */
  29. public static function download_product() {
  30. $product_id = absint( $_GET['download_file'] ); // phpcs:ignore WordPress.VIP.SuperGlobalInputUsage.AccessDetected, WordPress.VIP.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
  31. $product = wc_get_product( $product_id );
  32. $data_store = WC_Data_Store::load( 'customer-download' );
  33. if ( ! $product || empty( $_GET['key'] ) || empty( $_GET['order'] ) ) { // WPCS: input var ok, CSRF ok.
  34. self::download_error( __( 'Invalid download link.', 'woocommerce' ) );
  35. }
  36. // Fallback, accept email address if it's passed.
  37. if ( empty( $_GET['email'] ) && empty( $_GET['uid'] ) ) { // WPCS: input var ok, CSRF ok.
  38. self::download_error( __( 'Invalid download link.', 'woocommerce' ) );
  39. }
  40. $order_id = wc_get_order_id_by_order_key( wc_clean( wp_unslash( $_GET['order'] ) ) ); // WPCS: input var ok, CSRF ok.
  41. $order = wc_get_order( $order_id );
  42. if ( isset( $_GET['email'] ) ) { // WPCS: input var ok, CSRF ok.
  43. $email_address = wp_unslash( $_GET['email'] ); // WPCS: input var ok, CSRF ok, sanitization ok.
  44. } else {
  45. // Get email address from order to verify hash.
  46. $email_address = is_a( $order, 'WC_Order' ) ? $order->get_billing_email() : null;
  47. // Prepare email address hash.
  48. $email_hash = function_exists( 'hash' ) ? hash( 'sha256', $email_address ) : sha1( $email_address );
  49. if ( is_null( $email_address ) || ! hash_equals( wp_unslash( $_GET['uid'] ), $email_hash ) ) { // WPCS: input var ok, CSRF ok, sanitization ok.
  50. self::download_error( __( 'Invalid download link.', 'woocommerce' ) );
  51. }
  52. }
  53. $download_ids = $data_store->get_downloads(
  54. array(
  55. 'user_email' => sanitize_email( str_replace( ' ', '+', $email_address ) ),
  56. 'order_key' => wc_clean( wp_unslash( $_GET['order'] ) ), // WPCS: input var ok, CSRF ok.
  57. 'product_id' => $product_id,
  58. 'download_id' => wc_clean( preg_replace( '/\s+/', ' ', wp_unslash( $_GET['key'] ) ) ), // WPCS: input var ok, CSRF ok, sanitization ok.
  59. 'orderby' => 'downloads_remaining',
  60. 'order' => 'DESC',
  61. 'limit' => 1,
  62. 'return' => 'ids',
  63. )
  64. );
  65. if ( empty( $download_ids ) ) {
  66. self::download_error( __( 'Invalid download link.', 'woocommerce' ) );
  67. }
  68. $download = new WC_Customer_Download( current( $download_ids ) );
  69. /**
  70. * Filter download filepath.
  71. *
  72. * @since 4.0.0
  73. * @param string $file_path File path.
  74. * @param string $email_address Email address.
  75. * @param WC_Order|bool $order Order object or false.
  76. * @param WC_Product $product Product object.
  77. * @param WC_Customer_Download $download Download data.
  78. */
  79. $file_path = apply_filters(
  80. 'woocommerce_download_product_filepath',
  81. $product->get_file_download_path( $download->get_download_id() ),
  82. $email_address,
  83. $order,
  84. $product,
  85. $download
  86. );
  87. $parsed_file_path = self::parse_file_path( $file_path );
  88. $download_range = self::get_download_range( @filesize( $parsed_file_path['file_path'] ) ); // @codingStandardsIgnoreLine.
  89. self::check_order_is_valid( $download );
  90. if ( ! $download_range['is_range_request'] ) {
  91. // If the remaining download count goes to 0, allow range requests to be able to finish streaming from iOS devices.
  92. self::check_downloads_remaining( $download );
  93. }
  94. self::check_download_expiry( $download );
  95. self::check_download_login_required( $download );
  96. do_action(
  97. 'woocommerce_download_product',
  98. $download->get_user_email(),
  99. $download->get_order_key(),
  100. $download->get_product_id(),
  101. $download->get_user_id(),
  102. $download->get_download_id(),
  103. $download->get_order_id()
  104. );
  105. $download->save();
  106. // Track the download in logs and change remaining/counts.
  107. $current_user_id = get_current_user_id();
  108. $ip_address = WC_Geolocation::get_ip_address();
  109. if ( ! $download_range['is_range_request'] ) {
  110. $download->track_download( $current_user_id > 0 ? $current_user_id : null, ! empty( $ip_address ) ? $ip_address : null );
  111. }
  112. self::download( $file_path, $download->get_product_id() );
  113. }
  114. /**
  115. * Check if an order is valid for downloading from.
  116. *
  117. * @param WC_Customer_Download $download Download instance.
  118. */
  119. private static function check_order_is_valid( $download ) {
  120. if ( $download->get_order_id() ) {
  121. $order = wc_get_order( $download->get_order_id() );
  122. if ( $order && ! $order->is_download_permitted() ) {
  123. self::download_error( __( 'Invalid order.', 'woocommerce' ), '', 403 );
  124. }
  125. }
  126. }
  127. /**
  128. * Check if there are downloads remaining.
  129. *
  130. * @param WC_Customer_Download $download Download instance.
  131. */
  132. private static function check_downloads_remaining( $download ) {
  133. if ( '' !== $download->get_downloads_remaining() && 0 >= $download->get_downloads_remaining() ) {
  134. self::download_error( __( 'Sorry, you have reached your download limit for this file', 'woocommerce' ), '', 403 );
  135. }
  136. }
  137. /**
  138. * Check if the download has expired.
  139. *
  140. * @param WC_Customer_Download $download Download instance.
  141. */
  142. private static function check_download_expiry( $download ) {
  143. if ( ! is_null( $download->get_access_expires() ) && $download->get_access_expires()->getTimestamp() < strtotime( 'midnight', time() ) ) {
  144. self::download_error( __( 'Sorry, this download has expired', 'woocommerce' ), '', 403 );
  145. }
  146. }
  147. /**
  148. * Check if a download requires the user to login first.
  149. *
  150. * @param WC_Customer_Download $download Download instance.
  151. */
  152. private static function check_download_login_required( $download ) {
  153. if ( $download->get_user_id() && 'yes' === get_option( 'woocommerce_downloads_require_login' ) ) {
  154. if ( ! is_user_logged_in() ) {
  155. if ( wc_get_page_id( 'myaccount' ) ) {
  156. wp_safe_redirect( add_query_arg( 'wc_error', rawurlencode( __( 'You must be logged in to download files.', 'woocommerce' ) ), wc_get_page_permalink( 'myaccount' ) ) );
  157. exit;
  158. } else {
  159. self::download_error( __( 'You must be logged in to download files.', 'woocommerce' ) . ' <a href="' . esc_url( wp_login_url( wc_get_page_permalink( 'myaccount' ) ) ) . '" class="wc-forward">' . __( 'Login', 'woocommerce' ) . '</a>', __( 'Log in to Download Files', 'woocommerce' ), 403 );
  160. }
  161. } elseif ( ! current_user_can( 'download_file', $download ) ) {
  162. self::download_error( __( 'This is not your download link.', 'woocommerce' ), '', 403 );
  163. }
  164. }
  165. }
  166. /**
  167. * Count download.
  168. *
  169. * @deprecated 4.4.0
  170. * @param array $download_data Download data.
  171. */
  172. public static function count_download( $download_data ) {
  173. wc_deprecated_function( 'WC_Download_Handler::count_download', '4.4.0', '' );
  174. }
  175. /**
  176. * Download a file - hook into init function.
  177. *
  178. * @param string $file_path URL to file.
  179. * @param integer $product_id Product ID of the product being downloaded.
  180. */
  181. public static function download( $file_path, $product_id ) {
  182. if ( ! $file_path ) {
  183. self::download_error( __( 'No file defined', 'woocommerce' ) );
  184. }
  185. $filename = basename( $file_path );
  186. if ( strstr( $filename, '?' ) ) {
  187. $filename = current( explode( '?', $filename ) );
  188. }
  189. $filename = apply_filters( 'woocommerce_file_download_filename', $filename, $product_id );
  190. /**
  191. * Filter download method.
  192. *
  193. * @since 4.5.0
  194. * @param string $method Download method.
  195. * @param int $product_id Product ID.
  196. * @param string $file_path URL to file.
  197. */
  198. $file_download_method = apply_filters( 'woocommerce_file_download_method', get_option( 'woocommerce_file_download_method', 'force' ), $product_id, $file_path );
  199. // Add action to prevent issues in IE.
  200. add_action( 'nocache_headers', array( __CLASS__, 'ie_nocache_headers_fix' ) );
  201. // Trigger download via one of the methods.
  202. do_action( 'woocommerce_download_file_' . $file_download_method, $file_path, $filename );
  203. }
  204. /**
  205. * Redirect to a file to start the download.
  206. *
  207. * @param string $file_path File path.
  208. * @param string $filename File name.
  209. */
  210. public static function download_file_redirect( $file_path, $filename = '' ) {
  211. header( 'Location: ' . $file_path );
  212. exit;
  213. }
  214. /**
  215. * Parse file path and see if its remote or local.
  216. *
  217. * @param string $file_path File path.
  218. * @return array
  219. */
  220. public static function parse_file_path( $file_path ) {
  221. $wp_uploads = wp_upload_dir();
  222. $wp_uploads_dir = $wp_uploads['basedir'];
  223. $wp_uploads_url = $wp_uploads['baseurl'];
  224. /**
  225. * Replace uploads dir, site url etc with absolute counterparts if we can.
  226. * Note the str_replace on site_url is on purpose, so if https is forced
  227. * via filters we can still do the string replacement on a HTTP file.
  228. */
  229. $replacements = array(
  230. $wp_uploads_url => $wp_uploads_dir,
  231. network_site_url( '/', 'https' ) => ABSPATH,
  232. str_replace( 'https:', 'http:', network_site_url( '/', 'http' ) ) => ABSPATH,
  233. site_url( '/', 'https' ) => ABSPATH,
  234. str_replace( 'https:', 'http:', site_url( '/', 'http' ) ) => ABSPATH,
  235. );
  236. $file_path = str_replace( array_keys( $replacements ), array_values( $replacements ), $file_path );
  237. $parsed_file_path = wp_parse_url( $file_path );
  238. $remote_file = true;
  239. // Paths that begin with '//' are always remote URLs.
  240. if ( '//' === substr( $file_path, 0, 2 ) ) {
  241. return array(
  242. 'remote_file' => true,
  243. 'file_path' => is_ssl() ? 'https:' . $file_path : 'http:' . $file_path,
  244. );
  245. }
  246. // See if path needs an abspath prepended to work.
  247. if ( file_exists( ABSPATH . $file_path ) ) {
  248. $remote_file = false;
  249. $file_path = ABSPATH . $file_path;
  250. } elseif ( '/wp-content' === substr( $file_path, 0, 11 ) ) {
  251. $remote_file = false;
  252. $file_path = realpath( WP_CONTENT_DIR . substr( $file_path, 11 ) );
  253. // Check if we have an absolute path.
  254. } elseif ( ( ! isset( $parsed_file_path['scheme'] ) || ! in_array( $parsed_file_path['scheme'], array( 'http', 'https', 'ftp' ), true ) ) && isset( $parsed_file_path['path'] ) && file_exists( $parsed_file_path['path'] ) ) {
  255. $remote_file = false;
  256. $file_path = $parsed_file_path['path'];
  257. }
  258. return array(
  259. 'remote_file' => $remote_file,
  260. 'file_path' => $file_path,
  261. );
  262. }
  263. /**
  264. * Download a file using X-Sendfile, X-Lighttpd-Sendfile, or X-Accel-Redirect if available.
  265. *
  266. * @param string $file_path File path.
  267. * @param string $filename File name.
  268. */
  269. public static function download_file_xsendfile( $file_path, $filename ) {
  270. $parsed_file_path = self::parse_file_path( $file_path );
  271. /**
  272. * Fallback on force download method for remote files. This is because:
  273. * 1. xsendfile needs proxy configuration to work for remote files, which cannot be assumed to be available on most hosts.
  274. * 2. Force download method is more secure than redirect method if `allow_url_fopen` is enabled in `php.ini`.
  275. */
  276. if ( $parsed_file_path['remote_file'] && ! apply_filters( 'woocommerce_use_xsendfile_for_remote', false ) ) {
  277. do_action( 'woocommerce_download_file_force', $file_path, $filename );
  278. return;
  279. }
  280. if ( function_exists( 'apache_get_modules' ) && in_array( 'mod_xsendfile', apache_get_modules(), true ) ) {
  281. self::download_headers( $parsed_file_path['file_path'], $filename );
  282. $filepath = apply_filters( 'woocommerce_download_file_xsendfile_file_path', $parsed_file_path['file_path'], $file_path, $filename, $parsed_file_path );
  283. header( 'X-Sendfile: ' . $filepath );
  284. exit;
  285. } elseif ( stristr( getenv( 'SERVER_SOFTWARE' ), 'lighttpd' ) ) {
  286. self::download_headers( $parsed_file_path['file_path'], $filename );
  287. $filepath = apply_filters( 'woocommerce_download_file_xsendfile_lighttpd_file_path', $parsed_file_path['file_path'], $file_path, $filename, $parsed_file_path );
  288. header( 'X-Lighttpd-Sendfile: ' . $filepath );
  289. exit;
  290. } elseif ( stristr( getenv( 'SERVER_SOFTWARE' ), 'nginx' ) || stristr( getenv( 'SERVER_SOFTWARE' ), 'cherokee' ) ) {
  291. self::download_headers( $parsed_file_path['file_path'], $filename );
  292. $xsendfile_path = trim( preg_replace( '`^' . str_replace( '\\', '/', getcwd() ) . '`', '', $parsed_file_path['file_path'] ), '/' );
  293. $xsendfile_path = apply_filters( 'woocommerce_download_file_xsendfile_x_accel_redirect_file_path', $xsendfile_path, $file_path, $filename, $parsed_file_path );
  294. header( "X-Accel-Redirect: /$xsendfile_path" );
  295. exit;
  296. }
  297. // Fallback.
  298. wc_get_logger()->warning(
  299. sprintf(
  300. /* translators: %1$s contains the filepath of the digital asset. */
  301. __( '%1$s could not be served using the X-Accel-Redirect/X-Sendfile method. A Force Download will be used instead.', 'woocommerce' ),
  302. $file_path
  303. )
  304. );
  305. self::download_file_force( $file_path, $filename );
  306. }
  307. /**
  308. * Parse the HTTP_RANGE request from iOS devices.
  309. * Does not support multi-range requests.
  310. *
  311. * @param int $file_size Size of file in bytes.
  312. * @return array {
  313. * Information about range download request: beginning and length of
  314. * file chunk, whether the range is valid/supported and whether the request is a range request.
  315. *
  316. * @type int $start Byte offset of the beginning of the range. Default 0.
  317. * @type int $length Length of the requested file chunk in bytes. Optional.
  318. * @type bool $is_range_valid Whether the requested range is a valid and supported range.
  319. * @type bool $is_range_request Whether the request is a range request.
  320. * }
  321. */
  322. protected static function get_download_range( $file_size ) {
  323. $start = 0;
  324. $download_range = array(
  325. 'start' => $start,
  326. 'is_range_valid' => false,
  327. 'is_range_request' => false,
  328. );
  329. if ( ! $file_size ) {
  330. return $download_range;
  331. }
  332. $end = $file_size - 1;
  333. $download_range['length'] = $file_size;
  334. if ( isset( $_SERVER['HTTP_RANGE'] ) ) { // @codingStandardsIgnoreLine.
  335. $http_range = sanitize_text_field( wp_unslash( $_SERVER['HTTP_RANGE'] ) ); // WPCS: input var ok.
  336. $download_range['is_range_request'] = true;
  337. $c_start = $start;
  338. $c_end = $end;
  339. // Extract the range string.
  340. list( , $range ) = explode( '=', $http_range, 2 );
  341. // Make sure the client hasn't sent us a multibyte range.
  342. if ( strpos( $range, ',' ) !== false ) {
  343. return $download_range;
  344. }
  345. /*
  346. * If the range starts with an '-' we start from the beginning.
  347. * If not, we forward the file pointer
  348. * and make sure to get the end byte if specified.
  349. */
  350. if ( '-' === $range[0] ) {
  351. // The n-number of the last bytes is requested.
  352. $c_start = $file_size - substr( $range, 1 );
  353. } else {
  354. $range = explode( '-', $range );
  355. $c_start = ( isset( $range[0] ) && is_numeric( $range[0] ) ) ? (int) $range[0] : 0;
  356. $c_end = ( isset( $range[1] ) && is_numeric( $range[1] ) ) ? (int) $range[1] : $file_size;
  357. }
  358. /*
  359. * Check the range and make sure it's treated according to the specs: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.
  360. * End bytes can not be larger than $end.
  361. */
  362. $c_end = ( $c_end > $end ) ? $end : $c_end;
  363. // Validate the requested range and return an error if it's not correct.
  364. if ( $c_start > $c_end || $c_start > $file_size - 1 || $c_end >= $file_size ) {
  365. return $download_range;
  366. }
  367. $start = $c_start;
  368. $end = $c_end;
  369. $length = $end - $start + 1;
  370. $download_range['start'] = $start;
  371. $download_range['length'] = $length;
  372. $download_range['is_range_valid'] = true;
  373. }
  374. return $download_range;
  375. }
  376. /**
  377. * Force download - this is the default method.
  378. *
  379. * @param string $file_path File path.
  380. * @param string $filename File name.
  381. */
  382. public static function download_file_force( $file_path, $filename ) {
  383. $parsed_file_path = self::parse_file_path( $file_path );
  384. $download_range = self::get_download_range( @filesize( $parsed_file_path['file_path'] ) ); // @codingStandardsIgnoreLine.
  385. self::download_headers( $parsed_file_path['file_path'], $filename, $download_range );
  386. $start = isset( $download_range['start'] ) ? $download_range['start'] : 0;
  387. $length = isset( $download_range['length'] ) ? $download_range['length'] : 0;
  388. if ( ! self::readfile_chunked( $parsed_file_path['file_path'], $start, $length ) ) {
  389. if ( $parsed_file_path['remote_file'] && 'yes' === get_option( 'woocommerce_downloads_redirect_fallback_allowed' ) ) {
  390. wc_get_logger()->warning(
  391. sprintf(
  392. /* translators: %1$s contains the filepath of the digital asset. */
  393. __( '%1$s could not be served using the Force Download method. A redirect will be used instead.', 'woocommerce' ),
  394. $file_path
  395. )
  396. );
  397. self::download_file_redirect( $file_path );
  398. } else {
  399. self::download_error( __( 'File not found', 'woocommerce' ) );
  400. }
  401. }
  402. exit;
  403. }
  404. /**
  405. * Get content type of a download.
  406. *
  407. * @param string $file_path File path.
  408. * @return string
  409. */
  410. private static function get_download_content_type( $file_path ) {
  411. $file_extension = strtolower( substr( strrchr( $file_path, '.' ), 1 ) );
  412. $ctype = 'application/force-download';
  413. foreach ( get_allowed_mime_types() as $mime => $type ) {
  414. $mimes = explode( '|', $mime );
  415. if ( in_array( $file_extension, $mimes, true ) ) {
  416. $ctype = $type;
  417. break;
  418. }
  419. }
  420. return $ctype;
  421. }
  422. /**
  423. * Set headers for the download.
  424. *
  425. * @param string $file_path File path.
  426. * @param string $filename File name.
  427. * @param array $download_range Array containing info about range download request (see {@see get_download_range} for structure).
  428. */
  429. private static function download_headers( $file_path, $filename, $download_range = array() ) {
  430. self::check_server_config();
  431. self::clean_buffers();
  432. wc_nocache_headers();
  433. header( 'X-Robots-Tag: noindex, nofollow', true );
  434. header( 'Content-Type: ' . self::get_download_content_type( $file_path ) );
  435. header( 'Content-Description: File Transfer' );
  436. header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
  437. header( 'Content-Transfer-Encoding: binary' );
  438. $file_size = @filesize( $file_path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  439. if ( ! $file_size ) {
  440. return;
  441. }
  442. if ( isset( $download_range['is_range_request'] ) && true === $download_range['is_range_request'] ) {
  443. if ( false === $download_range['is_range_valid'] ) {
  444. header( 'HTTP/1.1 416 Requested Range Not Satisfiable' );
  445. header( 'Content-Range: bytes 0-' . ( $file_size - 1 ) . '/' . $file_size );
  446. exit;
  447. }
  448. $start = $download_range['start'];
  449. $end = $download_range['start'] + $download_range['length'] - 1;
  450. $length = $download_range['length'];
  451. header( 'HTTP/1.1 206 Partial Content' );
  452. header( "Accept-Ranges: 0-$file_size" );
  453. header( "Content-Range: bytes $start-$end/$file_size" );
  454. header( "Content-Length: $length" );
  455. } else {
  456. header( 'Content-Length: ' . $file_size );
  457. }
  458. }
  459. /**
  460. * Check and set certain server config variables to ensure downloads work as intended.
  461. */
  462. private static function check_server_config() {
  463. wc_set_time_limit( 0 );
  464. if ( function_exists( 'apache_setenv' ) ) {
  465. @apache_setenv( 'no-gzip', 1 ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_apache_setenv
  466. }
  467. @ini_set( 'zlib.output_compression', 'Off' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_ini_set
  468. @session_write_close(); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.VIP.SessionFunctionsUsage.session_session_write_close
  469. }
  470. /**
  471. * Clean all output buffers.
  472. *
  473. * Can prevent errors, for example: transfer closed with 3 bytes remaining to read.
  474. */
  475. private static function clean_buffers() {
  476. if ( ob_get_level() ) {
  477. $levels = ob_get_level();
  478. for ( $i = 0; $i < $levels; $i++ ) {
  479. @ob_end_clean(); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  480. }
  481. } else {
  482. @ob_end_clean(); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  483. }
  484. }
  485. /**
  486. * Read file chunked.
  487. *
  488. * Reads file in chunks so big downloads are possible without changing PHP.INI - http://codeigniter.com/wiki/Download_helper_for_large_files/.
  489. *
  490. * @param string $file File.
  491. * @param int $start Byte offset/position of the beginning from which to read from the file.
  492. * @param int $length Length of the chunk to be read from the file in bytes, 0 means full file.
  493. * @return bool Success or fail
  494. */
  495. public static function readfile_chunked( $file, $start = 0, $length = 0 ) {
  496. if ( ! defined( 'WC_CHUNK_SIZE' ) ) {
  497. define( 'WC_CHUNK_SIZE', 1024 * 1024 );
  498. }
  499. $handle = @fopen( $file, 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_read_fopen
  500. if ( false === $handle ) {
  501. return false;
  502. }
  503. if ( ! $length ) {
  504. $length = @filesize( $file ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  505. }
  506. $read_length = (int) WC_CHUNK_SIZE;
  507. if ( $length ) {
  508. $end = $start + $length - 1;
  509. @fseek( $handle, $start ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  510. $p = @ftell( $handle ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  511. while ( ! @feof( $handle ) && $p <= $end ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  512. // Don't run past the end of file.
  513. if ( $p + $read_length > $end ) {
  514. $read_length = $end - $p + 1;
  515. }
  516. echo @fread( $handle, $read_length ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.XSS.EscapeOutput.OutputNotEscaped, WordPress.WP.AlternativeFunctions.file_system_read_fread
  517. $p = @ftell( $handle ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
  518. if ( ob_get_length() ) {
  519. ob_flush();
  520. flush();
  521. }
  522. }
  523. } else {
  524. while ( ! @feof( $handle ) ) { // @codingStandardsIgnoreLine.
  525. echo @fread( $handle, $read_length ); // @codingStandardsIgnoreLine.
  526. if ( ob_get_length() ) {
  527. ob_flush();
  528. flush();
  529. }
  530. }
  531. }
  532. return @fclose( $handle ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_read_fclose
  533. }
  534. /**
  535. * Filter headers for IE to fix issues over SSL.
  536. *
  537. * IE bug prevents download via SSL when Cache Control and Pragma no-cache headers set.
  538. *
  539. * @param array $headers HTTP headers.
  540. * @return array
  541. */
  542. public static function ie_nocache_headers_fix( $headers ) {
  543. if ( is_ssl() && ! empty( $GLOBALS['is_IE'] ) ) {
  544. $headers['Cache-Control'] = 'private';
  545. unset( $headers['Pragma'] );
  546. }
  547. return $headers;
  548. }
  549. /**
  550. * Die with an error message if the download fails.
  551. *
  552. * @param string $message Error message.
  553. * @param string $title Error title.
  554. * @param integer $status Error status.
  555. */
  556. private static function download_error( $message, $title = '', $status = 404 ) {
  557. /*
  558. * Since we will now render a message instead of serving a download, we should unwind some of the previously set
  559. * headers.
  560. */
  561. header( 'Content-Type: ' . get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ) );
  562. header_remove( 'Content-Description;' );
  563. header_remove( 'Content-Disposition' );
  564. header_remove( 'Content-Transfer-Encoding' );
  565. if ( ! strstr( $message, '<a ' ) ) {
  566. $message .= ' <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="wc-forward">' . esc_html__( 'Go to shop', 'woocommerce' ) . '</a>';
  567. }
  568. wp_die( $message, $title, array( 'response' => $status ) ); // WPCS: XSS ok.
  569. }
  570. }
  571. WC_Download_Handler::init();