PageRenderTime 54ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/woocommerce/includes/class-wc-download-handler.php

https://gitlab.com/iamgraeme/royalmile
PHP | 426 lines | 314 code | 34 blank | 78 comment | 29 complexity | 603c59da87c7abde263ebe5112318451 MD5 | raw file
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. exit; // Exit if accessed directly
  4. }
  5. /**
  6. * Download handler.
  7. *
  8. * Handle digital downloads.
  9. *
  10. * @class WC_Download_Handler
  11. * @version 2.2.0
  12. * @package WooCommerce/Classes
  13. * @category Class
  14. * @author WooThemes
  15. */
  16. class WC_Download_Handler {
  17. /**
  18. * Hook in methods.
  19. */
  20. public static function init() {
  21. if ( isset( $_GET['download_file'] ) && isset( $_GET['order'] ) && isset( $_GET['email'] ) ) {
  22. add_action( 'init', array( __CLASS__, 'download_product' ) );
  23. }
  24. add_action( 'woocommerce_download_file_redirect', array( __CLASS__, 'download_file_redirect' ), 10, 2 );
  25. add_action( 'woocommerce_download_file_xsendfile', array( __CLASS__, 'download_file_xsendfile' ), 10, 2 );
  26. add_action( 'woocommerce_download_file_force', array( __CLASS__, 'download_file_force' ), 10, 2 );
  27. }
  28. /**
  29. * Check if we need to download a file and check validity.
  30. */
  31. public static function download_product() {
  32. $product_id = absint( $_GET['download_file'] );
  33. $_product = wc_get_product( $product_id );
  34. $download_data = self::get_download_data( array(
  35. 'product_id' => $product_id,
  36. 'order_key' => wc_clean( $_GET['order'] ),
  37. 'email' => sanitize_email( str_replace( ' ', '+', $_GET['email'] ) ),
  38. 'download_id' => wc_clean( isset( $_GET['key'] ) ? preg_replace( '/\s+/', ' ', $_GET['key'] ) : '' )
  39. ) );
  40. if ( $_product && $download_data ) {
  41. self::check_current_user_can_download( $download_data );
  42. do_action( 'woocommerce_download_product', $download_data->user_email, $download_data->order_key, $download_data->product_id, $download_data->user_id, $download_data->download_id, $download_data->order_id );
  43. self::count_download( $download_data );
  44. self::download( $_product->get_file_download_path( $download_data->download_id ), $download_data->product_id );
  45. } else {
  46. self::download_error( __( 'Invalid download link.', 'woocommerce' ) );
  47. }
  48. }
  49. /**
  50. * Get a download from the database.
  51. *
  52. * @param array $args Contains email, order key, product id and download id
  53. * @return object
  54. * @access private
  55. */
  56. private static function get_download_data( $args = array() ) {
  57. global $wpdb;
  58. $query = "SELECT * FROM " . $wpdb->prefix . "woocommerce_downloadable_product_permissions ";
  59. $query .= "WHERE user_email = %s ";
  60. $query .= "AND order_key = %s ";
  61. $query .= "AND product_id = %s ";
  62. if ( $args['download_id'] ) {
  63. $query .= "AND download_id = %s ";
  64. }
  65. $query .= "ORDER BY downloads_remaining DESC";
  66. return $wpdb->get_row( $wpdb->prepare( $query, array( $args['email'], $args['order_key'], $args['product_id'], $args['download_id'] ) ) );
  67. }
  68. /**
  69. * Perform checks to see if the current user can download the file.
  70. * @param object $download_data
  71. * @access private
  72. */
  73. private static function check_current_user_can_download( $download_data ) {
  74. self::check_order_is_valid( $download_data );
  75. self::check_downloads_remaining( $download_data );
  76. self::check_download_expiry( $download_data );
  77. self::check_download_login_required( $download_data );
  78. }
  79. /**
  80. * Check if an order is valid for downloading from.
  81. * @param array $download_data
  82. * @access private
  83. */
  84. private static function check_order_is_valid( $download_data ) {
  85. if ( $download_data->order_id && ( $order = wc_get_order( $download_data->order_id ) ) && ! $order->is_download_permitted() ) {
  86. self::download_error( __( 'Invalid order.', 'woocommerce' ), '', 403 );
  87. }
  88. }
  89. /**
  90. * Check if there are downloads remaining.
  91. * @param array $download_data
  92. * @access private
  93. */
  94. private static function check_downloads_remaining( $download_data ) {
  95. if ( '0' == $download_data->downloads_remaining ) {
  96. self::download_error( __( 'Sorry, you have reached your download limit for this file', 'woocommerce' ), '', 403 );
  97. }
  98. }
  99. /**
  100. * Check if the download has expired.
  101. * @param array $download_data
  102. * @access private
  103. */
  104. private static function check_download_expiry( $download_data ) {
  105. if ( $download_data->access_expires > 0 && strtotime( $download_data->access_expires ) < strtotime( 'midnight', current_time( 'timestamp' ) ) ) {
  106. self::download_error( __( 'Sorry, this download has expired', 'woocommerce' ), '', 403 );
  107. }
  108. }
  109. /**
  110. * Check if a download requires the user to login first.
  111. * @param array $download_data
  112. * @access private
  113. */
  114. private static function check_download_login_required( $download_data ) {
  115. if ( $download_data->user_id && 'yes' === get_option( 'woocommerce_downloads_require_login' ) ) {
  116. if ( ! is_user_logged_in() ) {
  117. if ( wc_get_page_id( 'myaccount' ) ) {
  118. wp_safe_redirect( add_query_arg( 'wc_error', urlencode( __( 'You must be logged in to download files.', 'woocommerce' ) ), wc_get_page_permalink( 'myaccount' ) ) );
  119. exit;
  120. } else {
  121. 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 );
  122. }
  123. } elseif ( ! current_user_can( 'download_file', $download_data ) ) {
  124. self::download_error( __( 'This is not your download link.', 'woocommerce' ), '', 403 );
  125. }
  126. }
  127. }
  128. /**
  129. * Log the download + increase counts.
  130. * @param object $download_data
  131. */
  132. public static function count_download( $download_data ) {
  133. global $wpdb;
  134. $wpdb->update(
  135. $wpdb->prefix . 'woocommerce_downloadable_product_permissions',
  136. array(
  137. 'download_count' => $download_data->download_count + 1,
  138. 'downloads_remaining' => $download_data->downloads_remaining > 0 ? $download_data->downloads_remaining - 1 : $download_data->downloads_remaining,
  139. ),
  140. array(
  141. 'permission_id' => absint( $download_data->permission_id ),
  142. ),
  143. array( '%d', '%s' ),
  144. array( '%d' )
  145. );
  146. }
  147. /**
  148. * Download a file - hook into init function.
  149. * @param string $file_path URL to file
  150. * @param integer $product_id of the product being downloaded
  151. */
  152. public static function download( $file_path, $product_id ) {
  153. if ( ! $file_path ) {
  154. self::download_error( __( 'No file defined', 'woocommerce' ) );
  155. }
  156. $filename = basename( $file_path );
  157. if ( strstr( $filename, '?' ) ) {
  158. $filename = current( explode( '?', $filename ) );
  159. }
  160. $filename = apply_filters( 'woocommerce_file_download_filename', $filename, $product_id );
  161. $file_download_method = apply_filters( 'woocommerce_file_download_method', get_option( 'woocommerce_file_download_method', 'force' ), $product_id );
  162. // Add action to prevent issues in IE
  163. add_action( 'nocache_headers', array( __CLASS__, 'ie_nocache_headers_fix' ) );
  164. // Trigger download via one of the methods
  165. do_action( 'woocommerce_download_file_' . $file_download_method, $file_path, $filename );
  166. }
  167. /**
  168. * Redirect to a file to start the download.
  169. * @param string $file_path
  170. * @param string $filename
  171. */
  172. public static function download_file_redirect( $file_path, $filename = '' ) {
  173. header( 'Location: ' . $file_path );
  174. exit;
  175. }
  176. /**
  177. * Parse file path and see if its remote or local.
  178. * @param string $file_path
  179. * @return array
  180. */
  181. public static function parse_file_path( $file_path ) {
  182. $wp_uploads = wp_upload_dir();
  183. $wp_uploads_dir = $wp_uploads['basedir'];
  184. $wp_uploads_url = $wp_uploads['baseurl'];
  185. // Replace uploads dir, site url etc with absolute counterparts if we can
  186. $replacements = array(
  187. $wp_uploads_url => $wp_uploads_dir,
  188. network_site_url( '/', 'https' ) => ABSPATH,
  189. network_site_url( '/', 'http' ) => ABSPATH,
  190. site_url( '/', 'https' ) => ABSPATH,
  191. site_url( '/', 'http' ) => ABSPATH
  192. );
  193. $file_path = str_replace( array_keys( $replacements ), array_values( $replacements ), $file_path );
  194. $parsed_file_path = parse_url( $file_path );
  195. $remote_file = true;
  196. // See if path needs an abspath prepended to work
  197. if ( file_exists( ABSPATH . $file_path ) ) {
  198. $remote_file = false;
  199. $file_path = ABSPATH . $file_path;
  200. // Check if we have an absolute path
  201. } elseif ( ( ! isset( $parsed_file_path['scheme'] ) || ! in_array( $parsed_file_path['scheme'], array( 'http', 'https', 'ftp' ) ) ) && isset( $parsed_file_path['path'] ) && file_exists( $parsed_file_path['path'] ) ) {
  202. $remote_file = false;
  203. $file_path = $parsed_file_path['path'];
  204. }
  205. return array(
  206. 'remote_file' => $remote_file,
  207. 'file_path' => $file_path
  208. );
  209. }
  210. /**
  211. * Download a file using X-Sendfile, X-Lighttpd-Sendfile, or X-Accel-Redirect if available.
  212. * @param string $file_path
  213. * @param string $filename
  214. */
  215. public static function download_file_xsendfile( $file_path, $filename ) {
  216. $parsed_file_path = self::parse_file_path( $file_path );
  217. if ( function_exists( 'apache_get_modules' ) && in_array( 'mod_xsendfile', apache_get_modules() ) ) {
  218. self::download_headers( $parsed_file_path['file_path'], $filename );
  219. header( "X-Sendfile: " . $parsed_file_path['file_path'] );
  220. exit;
  221. } elseif ( stristr( getenv( 'SERVER_SOFTWARE' ), 'lighttpd' ) ) {
  222. self::download_headers( $parsed_file_path['file_path'], $filename );
  223. header( "X-Lighttpd-Sendfile: " . $parsed_file_path['file_path'] );
  224. exit;
  225. } elseif ( stristr( getenv( 'SERVER_SOFTWARE' ), 'nginx' ) || stristr( getenv( 'SERVER_SOFTWARE' ), 'cherokee' ) ) {
  226. self::download_headers( $parsed_file_path['file_path'], $filename );
  227. $xsendfile_path = trim( preg_replace( '`^' . str_replace( '\\', '/', getcwd() ) . '`', '', $parsed_file_path['file_path'] ), '/' );
  228. header( "X-Accel-Redirect: /$xsendfile_path" );
  229. exit;
  230. }
  231. // Fallback
  232. self::download_file_force( $file_path, $filename );
  233. }
  234. /**
  235. * Force download - this is the default method.
  236. * @param string $file_path
  237. * @param string $filename
  238. */
  239. public static function download_file_force( $file_path, $filename ) {
  240. $parsed_file_path = self::parse_file_path( $file_path );
  241. self::download_headers( $parsed_file_path['file_path'], $filename );
  242. if ( ! self::readfile_chunked( $parsed_file_path['file_path'] ) ) {
  243. if ( $parsed_file_path['remote_file'] ) {
  244. self::download_file_redirect( $file_path );
  245. } else {
  246. self::download_error( __( 'File not found', 'woocommerce' ) );
  247. }
  248. }
  249. exit;
  250. }
  251. /**
  252. * Get content type of a download.
  253. * @param string $file_path
  254. * @return string
  255. * @access private
  256. */
  257. private static function get_download_content_type( $file_path ) {
  258. $file_extension = strtolower( substr( strrchr( $file_path, "." ), 1 ) );
  259. $ctype = "application/force-download";
  260. foreach ( get_allowed_mime_types() as $mime => $type ) {
  261. $mimes = explode( '|', $mime );
  262. if ( in_array( $file_extension, $mimes ) ) {
  263. $ctype = $type;
  264. break;
  265. }
  266. }
  267. return $ctype;
  268. }
  269. /**
  270. * Set headers for the download.
  271. * @param string $file_path
  272. * @param string $filename
  273. * @access private
  274. */
  275. private static function download_headers( $file_path, $filename ) {
  276. self::check_server_config();
  277. self::clean_buffers();
  278. nocache_headers();
  279. header( "X-Robots-Tag: noindex, nofollow", true );
  280. header( "Content-Type: " . self::get_download_content_type( $file_path ) );
  281. header( "Content-Description: File Transfer" );
  282. header( "Content-Disposition: attachment; filename=\"" . $filename . "\";" );
  283. header( "Content-Transfer-Encoding: binary" );
  284. if ( $size = @filesize( $file_path ) ) {
  285. header( "Content-Length: " . $size );
  286. }
  287. }
  288. /**
  289. * Check and set certain server config variables to ensure downloads work as intended.
  290. */
  291. private static function check_server_config() {
  292. wc_set_time_limit( 0 );
  293. if ( function_exists( 'get_magic_quotes_runtime' ) && get_magic_quotes_runtime() && version_compare( phpversion(), '5.4', '<' ) ) {
  294. set_magic_quotes_runtime( 0 );
  295. }
  296. if ( function_exists( 'apache_setenv' ) ) {
  297. @apache_setenv( 'no-gzip', 1 );
  298. }
  299. @ini_set( 'zlib.output_compression', 'Off' );
  300. @session_write_close();
  301. }
  302. /**
  303. * Clean all output buffers.
  304. *
  305. * Can prevent errors, for example: transfer closed with 3 bytes remaining to read.
  306. *
  307. * @access private
  308. */
  309. private static function clean_buffers() {
  310. if ( ob_get_level() ) {
  311. $levels = ob_get_level();
  312. for ( $i = 0; $i < $levels; $i++ ) {
  313. @ob_end_clean();
  314. }
  315. } else {
  316. @ob_end_clean();
  317. }
  318. }
  319. /**
  320. * readfile_chunked.
  321. *
  322. * Reads file in chunks so big downloads are possible without changing PHP.INI - http://codeigniter.com/wiki/Download_helper_for_large_files/.
  323. *
  324. * @param string $file
  325. * @return bool Success or fail
  326. */
  327. public static function readfile_chunked( $file ) {
  328. $chunksize = 1024 * 1024;
  329. $handle = @fopen( $file, 'r' );
  330. if ( false === $handle ) {
  331. return false;
  332. }
  333. while ( ! @feof( $handle ) ) {
  334. echo @fread( $handle, $chunksize );
  335. if ( ob_get_length() ) {
  336. ob_flush();
  337. flush();
  338. }
  339. }
  340. return @fclose( $handle );
  341. }
  342. /**
  343. * Filter headers for IE to fix issues over SSL.
  344. *
  345. * IE bug prevents download via SSL when Cache Control and Pragma no-cache headers set.
  346. *
  347. * @param array $headers
  348. * @return array
  349. */
  350. public static function ie_nocache_headers_fix( $headers ) {
  351. if ( is_ssl() && ! empty( $GLOBALS['is_IE'] ) ) {
  352. $headers['Cache-Control'] = 'private';
  353. unset( $headers['Pragma'] );
  354. }
  355. return $headers;
  356. }
  357. /**
  358. * Die with an error message if the download fails.
  359. * @param string $message
  360. * @param string $title
  361. * @param integer $status
  362. * @access private
  363. */
  364. private static function download_error( $message, $title = '', $status = 404 ) {
  365. if ( ! strstr( $message, '<a ' ) ) {
  366. $message .= ' <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="wc-forward">' . __( 'Go to shop', 'woocommerce' ) . '</a>';
  367. }
  368. wp_die( $message, $title, array( 'response' => $status ) );
  369. }
  370. }
  371. WC_Download_Handler::init();