PageRenderTime 42ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

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

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