Merge branch 'master' into update/erasure-requests

This commit is contained in:
Mike Jolley 2018-05-02 14:06:47 +01:00
commit e807c6151f
28 changed files with 722 additions and 585 deletions

View File

@ -606,7 +606,7 @@ if ( ! class_exists( 'WC_Admin_Settings', false ) ) :
<?php
if ( ! empty( $countries ) ) {
foreach ( $countries as $key => $val ) {
echo '<option value="' . esc_attr( $key ) . '"' . wc_selected( $key, $selections ) . '>' . esc_html( $val ) . '</option>';
echo '<option value="' . esc_attr( $key ) . '"' . wc_selected( $key, $selections ) . '>' . esc_html( $val ) . '</option>'; // WPCS: XSS ok.
}
}
?>
@ -722,7 +722,8 @@ if ( ! class_exists( 'WC_Admin_Settings', false ) ) :
}
// Options to update will be stored here and saved later.
$update_options = array();
$update_options = array();
$autoload_options = array();
// Loop options and get values to save.
foreach ( $options as $option ) {
@ -825,6 +826,8 @@ if ( ! class_exists( 'WC_Admin_Settings', false ) ) :
$update_options[ $option_name ] = $value;
}
$autoload_options[ $option_name ] = isset( $option['autoload'] ) ? (bool) $option['autoload'] : true;
/**
* Fire an action before saved.
*
@ -835,7 +838,7 @@ if ( ! class_exists( 'WC_Admin_Settings', false ) ) :
// Save all options in our array.
foreach ( $update_options as $name => $value ) {
update_option( $name, $value );
update_option( $name, $value, $autoload_options[ $name ] ? 'yes' : 'no' );
}
return true;

View File

@ -2,13 +2,11 @@
/**
* Debug/Status page
*
* @package WooCommerce/Admin/System Status
* @version 2.2.0
* @package WooCommerce/Admin/System Status
* @version 2.2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Status Class.
@ -35,9 +33,9 @@ class WC_Admin_Status {
public static function status_tools() {
$tools = self::get_tools();
if ( ! empty( $_GET['action'] ) && ! empty( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( $_REQUEST['_wpnonce'], 'debug_action' ) ) {
if ( ! empty( $_GET['action'] ) && ! empty( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_REQUEST['_wpnonce'] ), 'debug_action' ) ) { // WPCS: input var ok, sanitization ok.
$tools_controller = new WC_REST_System_Status_Tools_Controller();
$action = wc_clean( $_GET['action'] );
$action = wc_clean( wp_unslash( $_GET['action'] ) ); // WPCS: input var ok.
if ( array_key_exists( $action, $tools ) ) {
$response = $tools_controller->execute_tool( $action );
@ -55,9 +53,9 @@ class WC_Admin_Status {
}
}
// Display message if settings settings have been saved
if ( isset( $_REQUEST['settings-updated'] ) ) {
echo '<div class="updated inline"><p>' . __( 'Your changes have been saved.', 'woocommerce' ) . '</p></div>';
// Display message if settings settings have been saved.
if ( isset( $_REQUEST['settings-updated'] ) ) { // WPCS: input var ok.
echo '<div class="updated inline"><p>' . esc_html__( 'Your changes have been saved.', 'woocommerce' ) . '</p></div>';
}
include_once dirname( __FILE__ ) . '/views/html-admin-page-status-tools.php';
@ -88,18 +86,17 @@ class WC_Admin_Status {
* Show the log page contents for file log handler.
*/
public static function status_logs_file() {
$logs = self::scan_log_files();
if ( ! empty( $_REQUEST['log_file'] ) && isset( $logs[ sanitize_title( $_REQUEST['log_file'] ) ] ) ) {
$viewed_log = $logs[ sanitize_title( $_REQUEST['log_file'] ) ];
if ( ! empty( $_REQUEST['log_file'] ) && isset( $logs[ sanitize_title( wp_unslash( $_REQUEST['log_file'] ) ) ] ) ) { // WPCS: input var ok, CSRF ok.
$viewed_log = $logs[ sanitize_title( wp_unslash( $_REQUEST['log_file'] ) ) ]; // WPCS: input var ok, CSRF ok.
} elseif ( ! empty( $logs ) ) {
$viewed_log = current( $logs );
}
$handle = ! empty( $viewed_log ) ? self::get_log_file_handle( $viewed_log ) : '';
if ( ! empty( $_REQUEST['handle'] ) ) {
if ( ! empty( $_REQUEST['handle'] ) ) { // WPCS: input var ok, CSRF ok.
self::remove_log();
}
@ -110,14 +107,11 @@ class WC_Admin_Status {
* Show the log page contents for db log handler.
*/
public static function status_logs_db() {
// Flush
if ( ! empty( $_REQUEST['flush-logs'] ) ) {
if ( ! empty( $_REQUEST['flush-logs'] ) ) { // WPCS: input var ok, CSRF ok.
self::flush_db_logs();
}
// Bulk actions
if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['log'] ) ) {
if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['log'] ) ) { // WPCS: input var ok, CSRF ok.
self::log_table_bulk_actions();
}
@ -131,24 +125,24 @@ class WC_Admin_Status {
* Retrieve metadata from a file. Based on WP Core's get_file_data function.
*
* @since 2.1.1
* @param string $file Path to the file
* @param string $file Path to the file.
* @return string
*/
public static function get_file_version( $file ) {
// Avoid notices if file does not exist
// Avoid notices if file does not exist.
if ( ! file_exists( $file ) ) {
return '';
}
// We don't need to write to the file, so just open for reading.
$fp = fopen( $file, 'r' );
$fp = fopen( $file, 'r' ); // @codingStandardsIgnoreLine.
// Pull only the first 8kiB of the file in.
$file_data = fread( $fp, 8192 );
$file_data = fread( $fp, 8192 ); // @codingStandardsIgnoreLine.
// PHP will close file handle, but we are good citizens.
fclose( $fp );
fclose( $fp ); // @codingStandardsIgnoreLine.
// Make sure we catch CR-only line endings.
$file_data = str_replace( "\r", "\n", $file_data );
@ -164,7 +158,7 @@ class WC_Admin_Status {
/**
* Return the log file handle.
*
* @param string $filename
* @param string $filename Filename to get the handle for.
* @return string
*/
public static function get_log_file_handle( $filename ) {
@ -174,19 +168,18 @@ class WC_Admin_Status {
/**
* Scan the template files.
*
* @param string $template_path
* @param string $template_path Path to the template directory.
* @return array
*/
public static function scan_template_files( $template_path ) {
$files = @scandir( $template_path );
$files = @scandir( $template_path ); // @codingStandardsIgnoreLine.
$result = array();
if ( ! empty( $files ) ) {
foreach ( $files as $key => $value ) {
if ( ! in_array( $value, array( '.', '..' ) ) ) {
if ( ! in_array( $value, array( '.', '..' ), true ) ) {
if ( is_dir( $template_path . DIRECTORY_SEPARATOR . $value ) ) {
$sub_files = self::scan_template_files( $template_path . DIRECTORY_SEPARATOR . $value );
@ -208,22 +201,7 @@ class WC_Admin_Status {
* @return array
*/
public static function scan_log_files() {
$files = @scandir( WC_LOG_DIR );
$result = array();
if ( ! empty( $files ) ) {
foreach ( $files as $key => $value ) {
if ( ! in_array( $value, array( '.', '..' ) ) ) {
if ( ! is_dir( $value ) && strstr( $value, '.log' ) ) {
$result[ sanitize_title( $value ) ] = $value;
}
}
}
}
return $result;
return WC_Log_Handler_File::get_log_files();
}
/**
@ -252,9 +230,10 @@ class WC_Admin_Status {
if ( is_object( $api ) && ! is_wp_error( $api ) ) {
$update_theme_version = $api->version;
} elseif ( strstr( $theme->{'Author URI'}, 'woothemes' ) ) { // Check WooThemes Theme Version.
$theme_dir = substr( strtolower( str_replace( ' ', '', $theme->Name ) ), 0, 45 );
$theme_dir = substr( strtolower( str_replace( ' ', '', $theme->Name ) ), 0, 45 ); // @codingStandardsIgnoreLine.
$theme_version_data = get_transient( $theme_dir . '_version_data' );
if ( false === ( $theme_version_data = get_transient( $theme_dir . '_version_data' ) ) ) {
if ( false === $theme_version_data ) {
$theme_changelog = wp_safe_remote_get( 'http://dzv365zjfbd8v.cloudfront.net/changelogs/' . $theme_dir . '/changelog.txt' );
$cl_lines = explode( "\n", wp_remote_retrieve_body( $theme_changelog ) );
if ( ! empty( $cl_lines ) ) {
@ -288,13 +267,13 @@ class WC_Admin_Status {
* Remove/delete the chosen file.
*/
public static function remove_log() {
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'remove_log' ) ) {
wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( wp_unslash( $_REQUEST['_wpnonce'] ), 'remove_log' ) ) { // WPCS: input var ok, sanitization ok.
wp_die( esc_html__( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
}
if ( ! empty( $_REQUEST['handle'] ) ) {
if ( ! empty( $_REQUEST['handle'] ) ) { // WPCS: input var ok.
$log_handler = new WC_Log_Handler_File();
$log_handler->remove( $_REQUEST['handle'] );
$log_handler->remove( wp_unslash( $_REQUEST['handle'] ) ); // WPCS: input var ok, sanitization ok.
}
wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=wc-status&tab=logs' ) ) );
@ -307,8 +286,8 @@ class WC_Admin_Status {
* @since 3.0.0
*/
private static function flush_db_logs() {
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-status-logs' ) ) {
wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-status-logs' ) ) { // WPCS: input var ok, sanitization ok.
wp_die( esc_html__( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
}
WC_Log_Handler_DB::flush();
@ -323,13 +302,13 @@ class WC_Admin_Status {
* @since 3.0.0
*/
private static function log_table_bulk_actions() {
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-status-logs' ) ) {
wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-status-logs' ) ) { // WPCS: input var ok, sanitization ok.
wp_die( esc_html__( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
}
$log_ids = array_map( 'absint', (array) $_REQUEST['log'] );
$log_ids = array_map( 'absint', (array) isset( $_REQUEST['log'] ) ? wp_unslash( $_REQUEST['log'] ) : array() ); // WPCS: input var ok, sanitization ok.
if ( 'delete' === $_REQUEST['action'] || 'delete' === $_REQUEST['action2'] ) {
if ( ( isset( $_REQUEST['action'] ) && 'delete' === $_REQUEST['action'] ) || ( isset( $_REQUEST['action2'] ) && 'delete' === $_REQUEST['action2'] ) ) { // WPCS: input var ok, sanitization ok.
WC_Log_Handler_DB::delete( $log_ids );
wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=wc-status&tab=logs' ) ) );
exit();

View File

@ -1217,7 +1217,7 @@ class WC_Helper {
}
if ( ! $activated ) {
self::log( 'Could not activate a subscription upon plugin activation: ' . $$filename );
self::log( 'Could not activate a subscription upon plugin activation: ' . $filename );
return;
}

View File

@ -2,377 +2,369 @@
/**
* WooCommerce Shipping Settings
*
* @author WooThemes
* @category Admin
* @package WooCommerce/Admin
* @version 2.6.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
defined( 'ABSPATH' ) || exit;
if ( class_exists( 'WC_Settings_Shipping', false ) ) {
return new WC_Settings_Shipping();
}
if ( ! class_exists( 'WC_Settings_Shipping', false ) ) :
/**
* WC_Settings_Shipping.
*/
class WC_Settings_Shipping extends WC_Settings_Page {
/**
* WC_Settings_Shipping.
* Constructor.
*/
class WC_Settings_Shipping extends WC_Settings_Page {
public function __construct() {
$this->id = 'shipping';
$this->label = __( 'Shipping', 'woocommerce' );
/**
* Constructor.
*/
public function __construct() {
$this->id = 'shipping';
$this->label = __( 'Shipping', 'woocommerce' );
parent::__construct();
}
parent::__construct();
}
/**
* Add this page to settings.
*
* @param array $pages Current pages.
* @return array|mixed
*/
public function add_settings_page( $pages ) {
return wc_shipping_enabled() ? parent::add_settings_page( $pages ) : $pages;
}
/**
* Add this page to settings.
*
* @param array $pages
*
* @return array|mixed
*/
public function add_settings_page( $pages ) {
return wc_shipping_enabled() ? parent::add_settings_page( $pages ) : $pages;
}
/**
* Get sections.
*
* @return array
*/
public function get_sections() {
$sections = array(
'' => __( 'Shipping zones', 'woocommerce' ),
'options' => __( 'Shipping options', 'woocommerce' ),
'classes' => __( 'Shipping classes', 'woocommerce' ),
);
/**
* Get sections.
*
* @return array
*/
public function get_sections() {
$sections = array(
'' => __( 'Shipping zones', 'woocommerce' ),
'options' => __( 'Shipping options', 'woocommerce' ),
'classes' => __( 'Shipping classes', 'woocommerce' ),
);
if ( ! defined( 'WC_INSTALLING' ) ) {
// Load shipping methods so we can show any global options they may have.
$shipping_methods = WC()->shipping->load_shipping_methods();
foreach ( $shipping_methods as $method ) {
if ( ! $method->has_settings() ) {
continue;
}
$title = empty( $method->method_title ) ? ucfirst( $method->id ) : $method->method_title;
$sections[ strtolower( $method->id ) ] = esc_html( $title );
}
}
return apply_filters( 'woocommerce_get_sections_' . $this->id, $sections );
}
/**
* Get settings array.
*
* @param string $current_section
*
* @return array
*/
public function get_settings( $current_section = '' ) {
$settings = array();
if ( '' === $current_section ) {
$settings = apply_filters(
'woocommerce_shipping_settings', array(
array(
'title' => __( 'Shipping options', 'woocommerce' ),
'type' => 'title',
'id' => 'shipping_options',
),
array(
'title' => __( 'Calculations', 'woocommerce' ),
'desc' => __( 'Enable the shipping calculator on the cart page', 'woocommerce' ),
'id' => 'woocommerce_enable_shipping_calc',
'default' => 'yes',
'type' => 'checkbox',
'checkboxgroup' => 'start',
'autoload' => false,
),
array(
'desc' => __( 'Hide shipping costs until an address is entered', 'woocommerce' ),
'id' => 'woocommerce_shipping_cost_requires_address',
'default' => 'no',
'type' => 'checkbox',
'checkboxgroup' => 'end',
'autoload' => false,
),
array(
'title' => __( 'Shipping destination', 'woocommerce' ),
'desc' => __( 'This controls which shipping address is used by default.', 'woocommerce' ),
'id' => 'woocommerce_ship_to_destination',
'default' => 'billing',
'type' => 'radio',
'options' => array(
'shipping' => __( 'Default to customer shipping address', 'woocommerce' ),
'billing' => __( 'Default to customer billing address', 'woocommerce' ),
'billing_only' => __( 'Force shipping to the customer billing address', 'woocommerce' ),
),
'autoload' => false,
'desc_tip' => true,
'show_if_checked' => 'option',
),
array(
'title' => __( 'Debug mode', 'woocommerce' ),
'desc' => __( 'Enable debug mode', 'woocommerce' ),
'desc_tip' => __( 'Enable shipping debug mode to show matching shipping zones and to bypass shipping rate cache.', 'woocommerce' ),
'id' => 'woocommerce_shipping_debug_mode',
'default' => 'no',
'type' => 'checkbox',
'autoload' => false,
),
array(
'type' => 'sectionend',
'id' => 'shipping_options',
),
)
);
}
return apply_filters( 'woocommerce_get_settings_' . $this->id, $settings, $current_section );
}
/**
* Output the settings.
*/
public function output() {
global $current_section, $hide_save_button;
// Load shipping methods so we can show any global options they may have
if ( ! defined( 'WC_INSTALLING' ) ) {
// Load shipping methods so we can show any global options they may have.
$shipping_methods = WC()->shipping->load_shipping_methods();
if ( '' === $current_section ) {
$this->output_zones_screen();
} elseif ( 'options' === $current_section ) {
$settings = $this->get_settings();
WC_Admin_Settings::output_fields( $settings );
} elseif ( 'classes' === $current_section ) {
$hide_save_button = true;
$this->output_shipping_class_screen();
} else {
foreach ( $shipping_methods as $method ) {
if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ) ) && $method->has_settings() ) {
$method->admin_options();
}
foreach ( $shipping_methods as $method ) {
if ( ! $method->has_settings() ) {
continue;
}
$title = empty( $method->method_title ) ? ucfirst( $method->id ) : $method->method_title;
$sections[ strtolower( $method->id ) ] = esc_html( $title );
}
}
return apply_filters( 'woocommerce_get_sections_' . $this->id, $sections );
}
/**
* Get settings array.
*
* @param string $current_section Current section.
* @return array
*/
public function get_settings( $current_section = '' ) {
$settings = array();
if ( '' === $current_section ) {
$settings = apply_filters(
'woocommerce_shipping_settings', array(
array(
'title' => __( 'Shipping options', 'woocommerce' ),
'type' => 'title',
'id' => 'shipping_options',
),
array(
'title' => __( 'Calculations', 'woocommerce' ),
'desc' => __( 'Enable the shipping calculator on the cart page', 'woocommerce' ),
'id' => 'woocommerce_enable_shipping_calc',
'default' => 'yes',
'type' => 'checkbox',
'checkboxgroup' => 'start',
'autoload' => false,
),
array(
'desc' => __( 'Hide shipping costs until an address is entered', 'woocommerce' ),
'id' => 'woocommerce_shipping_cost_requires_address',
'default' => 'no',
'type' => 'checkbox',
'checkboxgroup' => 'end',
),
array(
'title' => __( 'Shipping destination', 'woocommerce' ),
'desc' => __( 'This controls which shipping address is used by default.', 'woocommerce' ),
'id' => 'woocommerce_ship_to_destination',
'default' => 'billing',
'type' => 'radio',
'options' => array(
'shipping' => __( 'Default to customer shipping address', 'woocommerce' ),
'billing' => __( 'Default to customer billing address', 'woocommerce' ),
'billing_only' => __( 'Force shipping to the customer billing address', 'woocommerce' ),
),
'autoload' => false,
'desc_tip' => true,
'show_if_checked' => 'option',
),
array(
'title' => __( 'Debug mode', 'woocommerce' ),
'desc' => __( 'Enable debug mode', 'woocommerce' ),
'desc_tip' => __( 'Enable shipping debug mode to show matching shipping zones and to bypass shipping rate cache.', 'woocommerce' ),
'id' => 'woocommerce_shipping_debug_mode',
'default' => 'no',
'type' => 'checkbox',
),
array(
'type' => 'sectionend',
'id' => 'shipping_options',
),
)
);
}
return apply_filters( 'woocommerce_get_settings_' . $this->id, $settings, $current_section );
}
/**
* Output the settings.
*/
public function output() {
global $current_section, $hide_save_button;
// Load shipping methods so we can show any global options they may have.
$shipping_methods = WC()->shipping->load_shipping_methods();
if ( '' === $current_section ) {
$this->output_zones_screen();
} elseif ( 'options' === $current_section ) {
$settings = $this->get_settings();
WC_Admin_Settings::output_fields( $settings );
} elseif ( 'classes' === $current_section ) {
$hide_save_button = true;
$this->output_shipping_class_screen();
} else {
foreach ( $shipping_methods as $method ) {
if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ), true ) && $method->has_settings() ) {
$method->admin_options();
}
}
}
/**
* Save settings.
*/
public function save() {
global $current_section;
switch ( $current_section ) {
case 'options':
WC_Admin_Settings::save_fields( $this->get_settings() );
break;
case 'classes':
case '':
break;
default:
$wc_shipping = WC_Shipping::instance();
foreach ( $wc_shipping->get_shipping_methods() as $method_id => $method ) {
if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ) ) ) {
do_action( 'woocommerce_update_options_' . $this->id . '_' . $method->id );
}
}
break;
}
if ( $current_section ) {
do_action( 'woocommerce_update_options_' . $this->id . '_' . $current_section );
}
// Increments the transient version to invalidate cache.
WC_Cache_Helper::get_transient_version( 'shipping', true );
}
/**
* Handles output of the shipping zones page in admin.
*/
protected function output_zones_screen() {
global $hide_save_button;
if ( isset( $_REQUEST['zone_id'] ) ) {
$hide_save_button = true;
$this->zone_methods_screen( wc_clean( $_REQUEST['zone_id'] ) );
} elseif ( isset( $_REQUEST['instance_id'] ) ) {
$this->instance_settings_screen( absint( $_REQUEST['instance_id'] ) );
} else {
$hide_save_button = true;
$this->zones_screen();
}
}
/**
* Show method for a zone
*
* @param int $zone_id
*/
protected function zone_methods_screen( $zone_id ) {
if ( 'new' === $zone_id ) {
$zone = new WC_Shipping_Zone();
} else {
$zone = WC_Shipping_Zones::get_zone( absint( $zone_id ) );
}
if ( ! $zone ) {
wp_die( __( 'Zone does not exist!', 'woocommerce' ) );
}
$allowed_countries = WC()->countries->get_allowed_countries();
$wc_shipping = WC_Shipping::instance();
$shipping_methods = $wc_shipping->get_shipping_methods();
$continents = WC()->countries->get_continents();
// Prepare locations.
$locations = array();
$postcodes = array();
foreach ( $zone->get_zone_locations() as $location ) {
if ( 'postcode' === $location->type ) {
$postcodes[] = $location->code;
} else {
$locations[] = $location->type . ':' . $location->code;
}
}
wp_localize_script(
'wc-shipping-zone-methods', 'shippingZoneMethodsLocalizeScript', array(
'methods' => $zone->get_shipping_methods( false, 'json' ),
'zone_name' => $zone->get_zone_name(),
'zone_id' => $zone->get_id(),
'wc_shipping_zones_nonce' => wp_create_nonce( 'wc_shipping_zones_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'save_changes_prompt' => __( 'Do you wish to save your changes first? Your changed data will be discarded if you choose to cancel.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
'add_method_failed' => __( 'Shipping method could not be added. Please retry.', 'woocommerce' ),
'yes' => __( 'Yes', 'woocommerce' ),
'no' => __( 'No', 'woocommerce' ),
'default_zone_name' => __( 'Zone', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-zone-methods' );
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zone-methods.php';
}
/**
* Show zones
*/
protected function zones_screen() {
$allowed_countries = WC()->countries->get_allowed_countries();
$continents = WC()->countries->get_continents();
$method_count = wc_get_shipping_method_count();
wp_localize_script(
'wc-shipping-zones', 'shippingZonesLocalizeScript', array(
'zones' => WC_Shipping_Zones::get_zones(),
'default_zone' => array(
'zone_id' => 0,
'zone_name' => '',
'zone_order' => null,
),
'wc_shipping_zones_nonce' => wp_create_nonce( 'wc_shipping_zones_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'delete_confirmation_msg' => __( 'Are you sure you want to delete this zone? This action cannot be undone.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
'no_shipping_methods_offered' => __( 'No shipping methods offered to this zone.', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-zones' );
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zones.php';
}
/**
* Show instance settings
*
* @param int $instance_id
*/
protected function instance_settings_screen( $instance_id ) {
$zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
if ( ! $shipping_method ) {
wp_die( __( 'Invalid shipping method!', 'woocommerce' ) );
}
if ( ! $zone ) {
wp_die( __( 'Zone does not exist!', 'woocommerce' ) );
}
if ( ! $shipping_method->has_settings() ) {
wp_die( __( 'This shipping method does not have any settings to configure.', 'woocommerce' ) );
}
if ( ! empty( $_POST['save'] ) ) {
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) {
echo '<div class="updated error"><p>' . __( 'Edit failed. Please try again.', 'woocommerce' ) . '</p></div>';
}
$shipping_method->process_admin_options();
$shipping_method->display_errors();
}
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zones-instance.php';
}
/**
* Handles output of the shipping class settings screen.
*/
protected function output_shipping_class_screen() {
$wc_shipping = WC_Shipping::instance();
wp_localize_script(
'wc-shipping-classes', 'shippingClassesLocalizeScript', array(
'classes' => $wc_shipping->get_shipping_classes(),
'default_shipping_class' => array(
'term_id' => 0,
'name' => '',
'description' => '',
),
'wc_shipping_classes_nonce' => wp_create_nonce( 'wc_shipping_classes_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-classes' );
// Extendable columns to show on the shipping classes screen.
$shipping_class_columns = apply_filters(
'woocommerce_shipping_classes_columns', array(
'wc-shipping-class-name' => __( 'Shipping class', 'woocommerce' ),
'wc-shipping-class-slug' => __( 'Slug', 'woocommerce' ),
'wc-shipping-class-description' => __( 'Description', 'woocommerce' ),
'wc-shipping-class-count' => __( 'Product count', 'woocommerce' ),
)
);
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-classes.php';
}
}
endif;
/**
* Save settings.
*/
public function save() {
global $current_section;
switch ( $current_section ) {
case 'options':
WC_Admin_Settings::save_fields( $this->get_settings() );
break;
case 'classes':
case '':
break;
default:
$wc_shipping = WC_Shipping::instance();
foreach ( $wc_shipping->get_shipping_methods() as $method_id => $method ) {
if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ), true ) ) {
do_action( 'woocommerce_update_options_' . $this->id . '_' . $method->id );
}
}
break;
}
if ( $current_section ) {
do_action( 'woocommerce_update_options_' . $this->id . '_' . $current_section );
}
// Increments the transient version to invalidate cache.
WC_Cache_Helper::get_transient_version( 'shipping', true );
}
/**
* Handles output of the shipping zones page in admin.
*/
protected function output_zones_screen() {
global $hide_save_button;
if ( isset( $_REQUEST['zone_id'] ) ) { // WPCS: input var ok, CSRF ok.
$hide_save_button = true;
$this->zone_methods_screen( wc_clean( wp_unslash( $_REQUEST['zone_id'] ) ) ); // WPCS: input var ok, CSRF ok.
} elseif ( isset( $_REQUEST['instance_id'] ) ) {
$this->instance_settings_screen( absint( wp_unslash( $_REQUEST['instance_id'] ) ) ); // WPCS: input var ok, CSRF ok.
} else {
$hide_save_button = true;
$this->zones_screen();
}
}
/**
* Show method for a zone
*
* @param int $zone_id Zone ID.
*/
protected function zone_methods_screen( $zone_id ) {
if ( 'new' === $zone_id ) {
$zone = new WC_Shipping_Zone();
} else {
$zone = WC_Shipping_Zones::get_zone( absint( $zone_id ) );
}
if ( ! $zone ) {
wp_die( esc_html__( 'Zone does not exist!', 'woocommerce' ) );
}
$allowed_countries = WC()->countries->get_allowed_countries();
$wc_shipping = WC_Shipping::instance();
$shipping_methods = $wc_shipping->get_shipping_methods();
$continents = WC()->countries->get_continents();
// Prepare locations.
$locations = array();
$postcodes = array();
foreach ( $zone->get_zone_locations() as $location ) {
if ( 'postcode' === $location->type ) {
$postcodes[] = $location->code;
} else {
$locations[] = $location->type . ':' . $location->code;
}
}
wp_localize_script(
'wc-shipping-zone-methods', 'shippingZoneMethodsLocalizeScript', array(
'methods' => $zone->get_shipping_methods( false, 'json' ),
'zone_name' => $zone->get_zone_name(),
'zone_id' => $zone->get_id(),
'wc_shipping_zones_nonce' => wp_create_nonce( 'wc_shipping_zones_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'save_changes_prompt' => __( 'Do you wish to save your changes first? Your changed data will be discarded if you choose to cancel.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
'add_method_failed' => __( 'Shipping method could not be added. Please retry.', 'woocommerce' ),
'yes' => __( 'Yes', 'woocommerce' ),
'no' => __( 'No', 'woocommerce' ),
'default_zone_name' => __( 'Zone', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-zone-methods' );
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zone-methods.php';
}
/**
* Show zones
*/
protected function zones_screen() {
$allowed_countries = WC()->countries->get_allowed_countries();
$continents = WC()->countries->get_continents();
$method_count = wc_get_shipping_method_count();
wp_localize_script(
'wc-shipping-zones', 'shippingZonesLocalizeScript', array(
'zones' => WC_Shipping_Zones::get_zones(),
'default_zone' => array(
'zone_id' => 0,
'zone_name' => '',
'zone_order' => null,
),
'wc_shipping_zones_nonce' => wp_create_nonce( 'wc_shipping_zones_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'delete_confirmation_msg' => __( 'Are you sure you want to delete this zone? This action cannot be undone.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
'no_shipping_methods_offered' => __( 'No shipping methods offered to this zone.', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-zones' );
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zones.php';
}
/**
* Show instance settings
*
* @param int $instance_id Shipping instance ID.
*/
protected function instance_settings_screen( $instance_id ) {
$zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
if ( ! $shipping_method ) {
wp_die( esc_html__( 'Invalid shipping method!', 'woocommerce' ) );
}
if ( ! $zone ) {
wp_die( esc_html__( 'Zone does not exist!', 'woocommerce' ) );
}
if ( ! $shipping_method->has_settings() ) {
wp_die( esc_html__( 'This shipping method does not have any settings to configure.', 'woocommerce' ) );
}
if ( ! empty( $_POST['save'] ) ) { // WPCS: input var ok, sanitization ok.
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( wp_unslash( $_REQUEST['_wpnonce'] ), 'woocommerce-settings' ) ) { // WPCS: input var ok, sanitization ok.
echo '<div class="updated error"><p>' . esc_html__( 'Edit failed. Please try again.', 'woocommerce' ) . '</p></div>';
}
$shipping_method->process_admin_options();
$shipping_method->display_errors();
}
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-zones-instance.php';
}
/**
* Handles output of the shipping class settings screen.
*/
protected function output_shipping_class_screen() {
$wc_shipping = WC_Shipping::instance();
wp_localize_script(
'wc-shipping-classes', 'shippingClassesLocalizeScript', array(
'classes' => $wc_shipping->get_shipping_classes(),
'default_shipping_class' => array(
'term_id' => 0,
'name' => '',
'description' => '',
),
'wc_shipping_classes_nonce' => wp_create_nonce( 'wc_shipping_classes_nonce' ),
'strings' => array(
'unload_confirmation_msg' => __( 'Your changed data will be lost if you leave this page without saving.', 'woocommerce' ),
'save_failed' => __( 'Your changes were not saved. Please retry.', 'woocommerce' ),
),
)
);
wp_enqueue_script( 'wc-shipping-classes' );
// Extendable columns to show on the shipping classes screen.
$shipping_class_columns = apply_filters(
'woocommerce_shipping_classes_columns', array(
'wc-shipping-class-name' => __( 'Shipping class', 'woocommerce' ),
'wc-shipping-class-slug' => __( 'Slug', 'woocommerce' ),
'wc-shipping-class-description' => __( 'Description', 'woocommerce' ),
'wc-shipping-class-count' => __( 'Product count', 'woocommerce' ),
)
);
include_once dirname( __FILE__ ) . '/views/html-admin-page-shipping-classes.php';
}
}
return new WC_Settings_Shipping();

View File

@ -1,8 +1,11 @@
<?php
/**
* Tax settings.
*
* @package Settings.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
defined( 'ABSPATH' ) || exit;
$settings = array(
@ -65,6 +68,7 @@ $settings = array(
'id' => 'woocommerce_tax_classes',
'css' => 'width:100%; height: 65px;',
'type' => 'textarea',
/* Translators: %s New line char. */
'default' => sprintf( __( 'Reduced rate%sZero rate', 'woocommerce' ), PHP_EOL ),
),
@ -81,16 +85,15 @@ $settings = array(
),
array(
'title' => __( 'Display prices during cart and checkout', 'woocommerce' ),
'id' => 'woocommerce_tax_display_cart',
'default' => 'excl',
'type' => 'select',
'class' => 'wc-enhanced-select',
'options' => array(
'title' => __( 'Display prices during cart and checkout', 'woocommerce' ),
'id' => 'woocommerce_tax_display_cart',
'default' => 'excl',
'type' => 'select',
'class' => 'wc-enhanced-select',
'options' => array(
'incl' => __( 'Including tax', 'woocommerce' ),
'excl' => __( 'Excluding tax', 'woocommerce' ),
),
'autoload' => false,
),
array(

View File

@ -119,37 +119,42 @@ class WC_REST_System_Status_Tools_Controller extends WC_REST_Controller {
*/
public function get_tools() {
$tools = array(
'clear_transients' => array(
'clear_transients' => array(
'name' => __( 'WooCommerce transients', 'woocommerce' ),
'button' => __( 'Clear transients', 'woocommerce' ),
'desc' => __( 'This tool will clear the product/shop transients cache.', 'woocommerce' ),
),
'clear_expired_transients' => array(
'clear_expired_transients' => array(
'name' => __( 'Expired transients', 'woocommerce' ),
'button' => __( 'Clear transients', 'woocommerce' ),
'desc' => __( 'This tool will clear ALL expired transients from WordPress.', 'woocommerce' ),
),
'delete_orphaned_variations' => array(
'delete_orphaned_variations' => array(
'name' => __( 'Orphaned variations', 'woocommerce' ),
'button' => __( 'Delete orphaned variations', 'woocommerce' ),
'desc' => __( 'This tool will delete all variations which have no parent.', 'woocommerce' ),
),
'add_order_indexes' => array(
'clear_expired_download_permissions' => array(
'name' => __( 'Used-up download permissions', 'woocommerce' ),
'button' => __( 'Clean up download permissions', 'woocommerce' ),
'desc' => __( 'This tool will delete expired download permissions and permissions with 0 remaining downloads.', 'woocommerce' ),
),
'add_order_indexes' => array(
'name' => __( 'Order address indexes', 'woocommerce' ),
'button' => __( 'Index orders', 'woocommerce' ),
'desc' => __( 'This tool will add address indexes to orders that do not have them yet. This improves order search results.', 'woocommerce' ),
),
'recount_terms' => array(
'recount_terms' => array(
'name' => __( 'Term counts', 'woocommerce' ),
'button' => __( 'Recount terms', 'woocommerce' ),
'desc' => __( 'This tool will recount product terms - useful when changing your settings in a way which hides products from the catalog.', 'woocommerce' ),
),
'reset_roles' => array(
'reset_roles' => array(
'name' => __( 'Capabilities', 'woocommerce' ),
'button' => __( 'Reset capabilities', 'woocommerce' ),
'desc' => __( 'This tool will reset the admin, customer and shop_manager roles to default. Use this if your users cannot access all of the WooCommerce admin pages.', 'woocommerce' ),
),
'clear_sessions' => array(
'clear_sessions' => array(
'name' => __( 'Clear customer sessions', 'woocommerce' ),
'button' => __( 'Clear', 'woocommerce' ),
'desc' => sprintf(
@ -158,7 +163,7 @@ class WC_REST_System_Status_Tools_Controller extends WC_REST_Controller {
__( 'This tool will delete all customer session data from the database, including current carts and saved carts in the database.', 'woocommerce' )
),
),
'install_pages' => array(
'install_pages' => array(
'name' => __( 'Create default WooCommerce pages', 'woocommerce' ),
'button' => __( 'Create pages', 'woocommerce' ),
'desc' => sprintf(
@ -167,7 +172,7 @@ class WC_REST_System_Status_Tools_Controller extends WC_REST_Controller {
__( 'This tool will install all the missing WooCommerce pages. Pages already defined and set up will not be replaced.', 'woocommerce' )
),
),
'delete_taxes' => array(
'delete_taxes' => array(
'name' => __( 'Delete WooCommerce tax rates', 'woocommerce' ),
'button' => __( 'Delete tax rates', 'woocommerce' ),
'desc' => sprintf(
@ -176,12 +181,12 @@ class WC_REST_System_Status_Tools_Controller extends WC_REST_Controller {
__( 'This option will delete ALL of your tax rates, use with caution. This action cannot be reversed.', 'woocommerce' )
),
),
'reset_tracking' => array(
'reset_tracking' => array(
'name' => __( 'Reset usage tracking', 'woocommerce' ),
'button' => __( 'Reset', 'woocommerce' ),
'desc' => __( 'This will reset your usage tracking settings, causing it to show the opt-in banner again and not sending any data.', 'woocommerce' ),
),
'regenerate_thumbnails' => array(
'regenerate_thumbnails' => array(
'name' => __( 'Regenerate shop thumbnails', 'woocommerce' ),
'button' => __( 'Regenerate', 'woocommerce' ),
'desc' => __( 'This will regenerate all shop thumbnails to match your theme and/or image settings.', 'woocommerce' ),
@ -427,6 +432,21 @@ class WC_REST_System_Status_Tools_Controller extends WC_REST_Controller {
$message = sprintf( __( '%d orphaned variations deleted', 'woocommerce' ), $result );
break;
case 'clear_expired_download_permissions':
// Delete expired download permissions and ones with 0 downloads remaining.
$result = absint(
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions
WHERE ( downloads_remaining != '' AND downloads_remaining = 0 ) OR ( access_expires IS NOT NULL AND access_expires < %s )",
date( 'Y-m-d', current_time( 'timestamp' ) )
)
)
);
/* translators: %d: amount of permissions */
$message = sprintf( __( '%d permissions deleted', 'woocommerce' ), $result );
break;
case 'add_order_indexes':
/*
* Add billing and shipping address indexes containing the customer name for orders

View File

@ -91,8 +91,10 @@ final class WC_Cart_Session {
if ( is_array( $cart ) ) {
$cart_contents = array();
update_meta_cache( 'post', wp_list_pluck( $cart, 'product_id' ) ); // Prime meta cache to reduce future queries.
update_object_term_cache( wp_list_pluck( $cart, 'product_id' ), 'product' );
// Prime caches to reduce future queries.
if ( is_callable( '_prime_post_caches' ) ) {
_prime_post_caches( wp_list_pluck( $cart, 'product_id' ) );
}
foreach ( $cart as $key => $values ) {
$product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );

View File

@ -481,6 +481,9 @@ final class WC_Cart_Totals {
* @return array of taxes
*/
protected function get_item_tax_rates( $item ) {
if ( ! wc_tax_enabled() ) {
return array();
}
$tax_class = $item->product->get_tax_class();
return isset( $this->item_tax_rates[ $tax_class ] ) ? $this->item_tax_rates[ $tax_class ] : $this->item_tax_rates[ $tax_class ] = WC_Tax::get_rates( $item->product->get_tax_class(), $this->cart->get_customer() );
}

View File

@ -353,6 +353,7 @@ class WC_Install {
wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_sessions' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_personal_data' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_logs' );
wp_clear_scheduled_hook( 'woocommerce_geoip_updater' );
wp_clear_scheduled_hook( 'woocommerce_tracker_send_event' );
@ -367,7 +368,8 @@ class WC_Install {
}
wp_schedule_event( time(), 'daily', 'woocommerce_cleanup_personal_data' );
wp_schedule_event( time(), 'twicedaily', 'woocommerce_cleanup_sessions' );
wp_schedule_event( time() + ( 3 * HOUR_IN_SECONDS ), 'daily', 'woocommerce_cleanup_logs' );
wp_schedule_event( time() + ( 6 * HOUR_IN_SECONDS ), 'twicedaily', 'woocommerce_cleanup_sessions' );
wp_schedule_event( strtotime( 'first tuesday of next month' ), 'monthly', 'woocommerce_geoip_updater' );
wp_schedule_event( time() + 10, apply_filters( 'woocommerce_tracker_event_recurrence', 'daily' ), 'woocommerce_tracker_send_event' );
@ -437,6 +439,12 @@ class WC_Install {
}
}
}
// Define other defaults if not in setting screens.
add_option( 'woocommerce_single_image_width', '600', '', 'yes' );
add_option( 'woocommerce_thumbnail_image_width', '300', '', 'yes' );
add_option( 'woocommerce_checkout_highlight_required_fields', 'no', '', 'yes' );
add_option( 'woocommerce_demo_store', 'no', '', 'no' );
}
/**

View File

@ -1,16 +1,16 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Provides logging capabilities for debugging purposes.
*
* @class WC_Logger
* @version 2.0.0
* @package WooCommerce/Classes
* @category Class
* @author WooThemes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Logger class.
*/
class WC_Logger implements WC_Logger_Interface {
@ -31,12 +31,8 @@ class WC_Logger implements WC_Logger_Interface {
/**
* Constructor for the logger.
*
* @param array $handlers Optional. Array of log handlers. If $handlers is not provided,
* the filter 'woocommerce_register_log_handlers' will be used to define the handlers.
* If $handlers is provided, the filter will not be applied and the handlers will be
* used directly.
* @param string $threshold Optional. Define an explicit threshold. May be configured
* via WC_LOG_THRESHOLD. By default, all logs will be processed.
* @param array $handlers Optional. Array of log handlers. If $handlers is not provided, the filter 'woocommerce_register_log_handlers' will be used to define the handlers. If $handlers is provided, the filter will not be applied and the handlers will be used directly.
* @param string $threshold Optional. Define an explicit threshold. May be configured via WC_LOG_THRESHOLD. By default, all logs will be processed.
*/
public function __construct( $handlers = null, $threshold = null ) {
if ( null === $handlers ) {
@ -48,7 +44,7 @@ class WC_Logger implements WC_Logger_Interface {
if ( ! empty( $handlers ) && is_array( $handlers ) ) {
foreach ( $handlers as $handler ) {
$implements = class_implements( $handler );
if ( is_object( $handler ) && is_array( $implements ) && in_array( 'WC_Log_Handler_Interface', $implements ) ) {
if ( is_object( $handler ) && is_array( $implements ) && in_array( 'WC_Log_Handler_Interface', $implements, true ) ) {
$register_handlers[] = $handler;
} else {
wc_doing_it_wrong(
@ -80,7 +76,7 @@ class WC_Logger implements WC_Logger_Interface {
/**
* Determine whether to handle or ignore log.
*
* @param string $level emergency|alert|critical|error|warning|notice|info|debug
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @return bool True if the log should be handled.
*/
protected function should_handle( $level ) {
@ -96,15 +92,17 @@ class WC_Logger implements WC_Logger_Interface {
* This is not the preferred method for adding log messages. Please use log() or any one of
* the level methods (debug(), info(), etc.). This method may be deprecated in the future.
*
* @param string $handle
* @param string $message
* @param string $level
*
* @param string $handle File handle.
* @param string $message Message to log.
* @param string $level Logging level.
* @return bool
*/
public function add( $handle, $message, $level = WC_Log_Levels::NOTICE ) {
$message = apply_filters( 'woocommerce_logger_add_message', $message, $handle );
$this->log( $level, $message, array( 'source' => $handle, '_legacy' => true ) );
$this->log( $level, $message, array(
'source' => $handle,
'_legacy' => true,
) );
wc_do_deprecated_action( 'woocommerce_log_add', array( $handle, $message ), '3.0', 'This action has been deprecated with no alternative.' );
return true;
}
@ -122,7 +120,7 @@ class WC_Logger implements WC_Logger_Interface {
* 'info': Informational messages.
* 'debug': Debug-level messages.
* @param string $message Log message.
* @param array $context Optional. Additional information for log handlers.
* @param array $context Optional. Additional information for log handlers.
*/
public function log( $level, $message, $context = array() ) {
if ( ! WC_Log_Levels::is_valid_level( $level ) ) {
@ -132,7 +130,7 @@ class WC_Logger implements WC_Logger_Interface {
if ( $this->should_handle( $level ) ) {
$timestamp = current_time( 'timestamp' );
$message = apply_filters( 'woocommerce_logger_log_message', $message, $level, $context );
$message = apply_filters( 'woocommerce_logger_log_message', $message, $level, $context );
foreach ( $this->handlers as $handler ) {
$handler->handle( $timestamp, $level, $message, $context );
@ -147,8 +145,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function emergency( $message, $context = array() ) {
$this->log( WC_Log_Levels::EMERGENCY, $message, $context );
@ -162,8 +160,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function alert( $message, $context = array() ) {
$this->log( WC_Log_Levels::ALERT, $message, $context );
@ -177,8 +175,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function critical( $message, $context = array() ) {
$this->log( WC_Log_Levels::CRITICAL, $message, $context );
@ -192,8 +190,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function error( $message, $context = array() ) {
$this->log( WC_Log_Levels::ERROR, $message, $context );
@ -209,8 +207,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function warning( $message, $context = array() ) {
$this->log( WC_Log_Levels::WARNING, $message, $context );
@ -223,8 +221,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function notice( $message, $context = array() ) {
$this->log( WC_Log_Levels::NOTICE, $message, $context );
@ -238,8 +236,8 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function info( $message, $context = array() ) {
$this->log( WC_Log_Levels::INFO, $message, $context );
@ -252,25 +250,44 @@ class WC_Logger implements WC_Logger_Interface {
*
* @see WC_Logger::log
*
* @param string $message
* @param array $context
* @param string $message Message to log.
* @param array $context Log context.
*/
public function debug( $message, $context = array() ) {
$this->log( WC_Log_Levels::DEBUG, $message, $context );
}
/**
* Clear entries from chosen file.
*
* @deprecated 3.0.0
*
* @param string $handle
* Clear entries for a chosen file/source.
*
* @param string $source Source/handle to clear.
* @return bool
*/
public function clear( $handle ) {
wc_deprecated_function( 'WC_Logger::clear', '3.0', 'WC_Log_Handler_File::clear' );
$handler = new WC_Log_Handler_File();
return $handler->clear( $handle );
public function clear( $source = '' ) {
if ( ! $source ) {
return false;
}
foreach ( $this->handlers as $handler ) {
if ( is_callable( array( $handler, 'clear' ) ) ) {
$handler->clear( $source );
}
}
return true;
}
/**
* Clear all logs older than a defined number of days. Defaults to 30 days.
*
* @since 3.4.0
*/
public function clear_expired_logs() {
$days = absint( apply_filters( 'woocommerce_logger_days_to_retain_logs', 30 ) );
$timestamp = strtotime( "-{$days} days" );
foreach ( $this->handlers as $handler ) {
if ( is_callable( array( $handler, 'delete_logs_before_timestamp' ) ) ) {
$handler->delete_logs_before_timestamp( $timestamp );
}
}
}
}

View File

@ -20,21 +20,21 @@ class WC_Product_Variable extends WC_Product {
*
* @var array
*/
protected $children = array();
protected $children = null;
/**
* Array of visible children variation IDs. Determined by children.
*
* @var array
*/
protected $visible_children = array();
protected $visible_children = null;
/**
* Array of variation attributes IDs. Determined by children.
*
* @var array
*/
protected $variation_attributes = array();
protected $variation_attributes = null;
/**
* Get internal type.
@ -194,6 +194,8 @@ class WC_Product_Variable extends WC_Product {
/**
* Return a products child ids.
*
* This is lazy loaded as it's not used often and does require several queries.
*
* @param bool|string $visible_only Visible only.
* @return array Children ids
*/
@ -204,25 +206,43 @@ class WC_Product_Variable extends WC_Product {
return $visible_only ? $this->get_visible_children() : $this->get_children();
}
if ( null === $this->children ) {
$children = $this->data_store->read_children( $this );
$this->set_children( $children['all'] );
$this->set_visible_children( $children['visible'] );
}
return apply_filters( 'woocommerce_get_children', $this->children, $this, false );
}
/**
* Return a products child ids - visible only.
*
* This is lazy loaded as it's not used often and does require several queries.
*
* @since 3.0.0
* @return array Children ids
*/
public function get_visible_children() {
if ( null === $this->visible_children ) {
$children = $this->data_store->read_children( $this );
$this->set_children( $children['all'] );
$this->set_visible_children( $children['visible'] );
}
return apply_filters( 'woocommerce_get_children', $this->visible_children, $this, true );
}
/**
* Return an array of attributes used for variations, as well as their possible values.
*
* This is lazy loaded as it's not used often and does require several queries.
*
* @return array Attributes and their available values
*/
public function get_variation_attributes() {
if ( null === $this->variation_attributes ) {
$this->variation_attributes = $this->data_store->read_variation_attributes( $this );
}
return $this->variation_attributes;
}

View File

@ -409,27 +409,6 @@ class WC_Webhook extends WC_Legacy_Webhook {
'Body' => wp_slash( $request['body'] ),
),
);
if ( is_wp_error( $response ) ) {
$message['Webhook Delivery']['Response'] = array(
'Code' => $response->get_error_code(),
'Message' => $response->get_error_message(),
'Headers' => array(),
'Body' => '',
);
} else {
$message['Webhook Delivery']['Response'] = array(
'Code' => wp_remote_retrieve_response_code( $response ),
'Message' => wp_remote_retrieve_response_message( $response ),
'Headers' => wp_remote_retrieve_headers( $response ),
'Body' => wp_remote_retrieve_body( $response ),
);
}
$logger->info(
wc_print_r( $message, true ), array(
'source' => 'webhooks-delivery',
)
);
// Parse response.
if ( is_wp_error( $response ) ) {
@ -437,7 +416,6 @@ class WC_Webhook extends WC_Legacy_Webhook {
$response_message = $response->get_error_message();
$response_headers = array();
$response_body = '';
} else {
$response_code = wp_remote_retrieve_response_code( $response );
$response_message = wp_remote_retrieve_response_message( $response );
@ -445,6 +423,18 @@ class WC_Webhook extends WC_Legacy_Webhook {
$response_body = wp_remote_retrieve_body( $response );
}
$message['Webhook Delivery']['Response'] = array(
'Code' => $response_code,
'Message' => $response_message,
'Headers' => $response_headers,
'Body' => $response_body,
);
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
$message['Webhook Delivery']['Body'] = 'Webhook body is not logged unless WP_DEBUG mode is turned on. This is to avoid the storing of personal data in the logs.';
$message['Webhook Delivery']['Response']['Body'] = 'Webhook body is not logged unless WP_DEBUG mode is turned on. This is to avoid the storing of personal data in the logs.';
}
$logger->info(
wc_print_r( $message, true ), array(
'source' => 'webhooks-delivery',

View File

@ -105,12 +105,6 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple
// Make sure data which does not apply to variables is unset.
$product->set_regular_price( '' );
$product->set_sale_price( '' );
// Set directly since individual data needs changed at the WC_Product_Variation level -- these datasets just pull.
$children = $this->read_children( $product );
$product->set_children( $children['all'] );
$product->set_visible_children( $children['visible'] );
$product->set_variation_attributes( $this->read_variation_attributes( $product ) );
}
/**
@ -120,7 +114,7 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple
* @param bool $force_read True to bypass the transient.
* @return array
*/
protected function read_children( &$product, $force_read = false ) {
public function read_children( &$product, $force_read = false ) {
$children_transient_name = 'wc_product_children_' . $product->get_id();
$children = get_transient( $children_transient_name );
@ -166,7 +160,7 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple
* @param WC_Product $product Product object.
* @return array
*/
protected function read_variation_attributes( &$product ) {
public function read_variation_attributes( &$product ) {
global $wpdb;
$variation_attributes = array();
@ -367,7 +361,7 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple
protected function get_price_hash( &$product, $for_display = false ) {
global $wp_filter;
$price_hash = $for_display ? array( get_option( 'woocommerce_tax_display_shop', 'excl' ), WC_Tax::get_rates() ) : array( false );
$price_hash = $for_display && wc_tax_enabled() ? array( get_option( 'woocommerce_tax_display_shop', 'excl' ), WC_Tax::get_rates() ) : array( false );
$filter_names = array( 'woocommerce_variation_prices_price', 'woocommerce_variation_prices_regular_price', 'woocommerce_variation_prices_sale_price' );
foreach ( $filter_names as $filter_name ) {

View File

@ -132,7 +132,7 @@ class WC_Product_CSV_Exporter extends WC_CSV_Batch_Exporter {
public function prepare_data_to_export() {
$columns = $this->get_column_names();
$args = apply_filters( "woocommerce_product_export_{$this->export_type}_query_args", array(
'status' => array( 'private', 'publish', 'draft', 'future' ),
'status' => array( 'private', 'publish', 'draft', 'future', 'pending' ),
'type' => $this->product_types_to_export,
'limit' => $this->get_limit(),
'page' => $this->get_page(),

View File

@ -60,8 +60,7 @@ class WC_Gateway_Paypal extends WC_Payment_Gateway {
$this->email = $this->get_option( 'email' );
$this->receiver_email = $this->get_option( 'receiver_email', $this->email );
$this->identity_token = $this->get_option( 'identity_token' );
self::$log_enabled = $this->debug;
self::$log_enabled = $this->debug;
if ( $this->testmode ) {
/* translators: %s: Link to PayPal sandbox testing guide page */
@ -116,6 +115,26 @@ class WC_Gateway_Paypal extends WC_Payment_Gateway {
}
}
/**
* Processes and saves options.
* If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
*
* @return bool was anything saved?
*/
public function process_admin_options() {
$saved = parent::process_admin_options();
// Maybe clear logs.
if ( 'yes' !== $this->get_option( 'debug', 'no' ) ) {
if ( empty( self::$log ) ) {
self::$log = wc_get_logger();
}
self::$log->clear( 'paypal' );
}
return $saved;
}
/**
* Get gateway icon.
*

View File

@ -99,16 +99,15 @@ class WC_Gateway_Paypal_IPN_Handler extends WC_Gateway_Paypal_Response {
// Post back to get a response.
$response = wp_safe_remote_post( $this->sandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr', $params );
WC_Gateway_Paypal::log( 'IPN Request: ' . wc_print_r( $params, true ) );
WC_Gateway_Paypal::log( 'IPN Response: ' . wc_print_r( $response, true ) );
// Check to see if the request was valid.
if ( ! is_wp_error( $response ) && $response['response']['code'] >= 200 && $response['response']['code'] < 300 && strstr( $response['body'], 'VERIFIED' ) ) {
WC_Gateway_Paypal::log( 'Received valid response from PayPal' );
WC_Gateway_Paypal::log( 'Received valid response from PayPal IPN' );
return true;
}
WC_Gateway_Paypal::log( 'Received invalid response from PayPal' );
WC_Gateway_Paypal::log( 'Received invalid response from PayPal IPN' );
if ( is_wp_error( $response ) ) {
WC_Gateway_Paypal::log( 'Error response: ' . $response->get_error_message() );
@ -347,15 +346,6 @@ class WC_Gateway_Paypal_IPN_Handler extends WC_Gateway_Paypal_Response {
* @param array $posted Posted data.
*/
protected function save_paypal_meta_data( $order, $posted ) {
if ( ! empty( $posted['payer_email'] ) ) {
update_post_meta( $order->get_id(), 'Payer PayPal address', wc_clean( $posted['payer_email'] ) );
}
if ( ! empty( $posted['first_name'] ) ) {
update_post_meta( $order->get_id(), 'Payer first name', wc_clean( $posted['first_name'] ) );
}
if ( ! empty( $posted['last_name'] ) ) {
update_post_meta( $order->get_id(), 'Payer last name', wc_clean( $posted['last_name'] ) );
}
if ( ! empty( $posted['payment_type'] ) ) {
update_post_meta( $order->get_id(), 'Payment type', wc_clean( $posted['payment_type'] ) );
}

View File

@ -83,16 +83,15 @@ class WC_Gateway_Paypal_PDT_Handler extends WC_Gateway_Paypal_Response {
* Check Response for PDT.
*/
public function check_response() {
if ( empty( $_REQUEST['cm'] ) || empty( $_REQUEST['tx'] ) || empty( $_REQUEST['st'] ) ) {
if ( empty( $_REQUEST['cm'] ) || empty( $_REQUEST['tx'] ) || empty( $_REQUEST['st'] ) ) { // WPCS: Input var ok, CSRF ok, sanitization ok.
return;
}
$order_id = wc_clean( wp_unslash( $_REQUEST['cm'] ) );
$status = wc_clean( strtolower( wp_unslash( $_REQUEST['st'] ) ) ); // phpcs:ignore WordPress.VIP.ValidatedSanitizedInput.InputNotSanitized
$amount = wc_clean( wp_unslash( $_REQUEST['amt'] ) ); // phpcs:ignore WordPress.VIP.ValidatedSanitizedInput.InputNotValidated
$transaction = wc_clean( wp_unslash( $_REQUEST['tx'] ) );
$order = $this->get_paypal_order( $order_id );
$order_id = wc_clean( wp_unslash( $_REQUEST['cm'] ) ); // WPCS: input var ok, CSRF ok, sanitization ok.
$status = wc_clean( strtolower( wp_unslash( $_REQUEST['st'] ) ) ); // WPCS: input var ok, CSRF ok, sanitization ok.
$amount = wc_clean( wp_unslash( $_REQUEST['amt'] ) ); // WPCS: input var ok, CSRF ok, sanitization ok.
$transaction = wc_clean( wp_unslash( $_REQUEST['tx'] ) ); // WPCS: input var ok, CSRF ok, sanitization ok.
$order = $this->get_paypal_order( $order_id );
if ( ! $order || ! $order->has_status( 'pending' ) ) {
return false;
@ -101,7 +100,7 @@ class WC_Gateway_Paypal_PDT_Handler extends WC_Gateway_Paypal_Response {
$transaction_result = $this->validate_transaction( $transaction );
if ( $transaction_result ) {
WC_Gateway_Paypal::log( 'PDT Transaction Result: ' . wc_print_r( $transaction_result, true ) );
WC_Gateway_Paypal::log( 'PDT Transaction Status: ' . wc_print_r( $status, true ) );
update_post_meta( $order->get_id(), '_paypal_status', $status );
update_post_meta( $order->get_id(), '_transaction_id', $transaction );
@ -114,19 +113,10 @@ class WC_Gateway_Paypal_PDT_Handler extends WC_Gateway_Paypal_Response {
} else {
$this->payment_complete( $order, $transaction, __( 'PDT payment completed', 'woocommerce' ) );
// Log paypal transaction fee and other meta data.
// Log paypal transaction fee and payment type.
if ( ! empty( $transaction_result['mc_fee'] ) ) {
update_post_meta( $order->get_id(), 'PayPal Transaction Fee', $transaction_result['mc_fee'] );
}
if ( ! empty( $transaction_result['payer_email'] ) ) {
update_post_meta( $order->get_id(), 'Payer PayPal address', $transaction_result['payer_email'] );
}
if ( ! empty( $transaction_result['first_name'] ) ) {
update_post_meta( $order->get_id(), 'Payer first name', $transaction_result['first_name'] );
}
if ( ! empty( $transaction_result['last_name'] ) ) {
update_post_meta( $order->get_id(), 'Payer last name', $transaction_result['last_name'] );
}
if ( ! empty( $transaction_result['payment_type'] ) ) {
update_post_meta( $order->get_id(), 'Payment type', $transaction_result['payment_type'] );
}

View File

@ -61,16 +61,26 @@ class WC_Gateway_Paypal_Request {
* @return string
*/
public function get_request_url( $order, $sandbox = false ) {
if ( $sandbox ) {
$this->endpoint = 'https://www.sandbox.paypal.com/cgi-bin/webscr?test_ipn=1&';
} else {
$this->endpoint = 'https://www.paypal.com/cgi-bin/webscr?';
}
$paypal_args = http_build_query( $this->get_paypal_args( $order ), '', '&' );
$this->endpoint = $sandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr?test_ipn=1&' : 'https://www.paypal.com/cgi-bin/webscr?';
$paypal_args = $this->get_paypal_args( $order );
$mask = array(
'first_name' => '***',
'last_name' => '***',
'address1' => '***',
'address2' => '***',
'city' => '***',
'state' => '***',
'zip' => '***',
'country' => '***',
'email' => '***@***',
'night_phone_a' => '***',
'night_phone_b' => '***',
'night_phone_c' => '***',
);
WC_Gateway_Paypal::log( 'PayPal Request Args for order ' . $order->get_order_number() . ': ' . wc_print_r( $paypal_args, true ) );
WC_Gateway_Paypal::log( 'PayPal Request Args for order ' . $order->get_order_number() . ': ' . wc_print_r( array_merge( $paypal_args, array_intersect_key( $mask, $paypal_args ) ), true ) );
return $this->endpoint . $paypal_args;
return $this->endpoint . http_build_query( $paypal_args, '', '&' );
}
/**

View File

@ -55,7 +55,7 @@ return array(
'label' => __( 'Enable logging', 'woocommerce' ),
'default' => 'no',
/* translators: %s: URL */
'description' => sprintf( __( 'Log PayPal events, such as IPN requests, inside %s', 'woocommerce' ), '<code>' . WC_Log_Handler_File::get_log_file_path( 'paypal' ) . '</code>' ),
'description' => sprintf( __( 'Log PayPal events, such as IPN requests, inside %s Note: this may log personal information. We recommend using this for debugging purposes only and deleting the logs when finished.', 'woocommerce' ), '<code>' . WC_Log_Handler_File::get_log_file_path( 'paypal' ) . '</code>' ),
),
'ipn_notification' => array(
'title' => __( 'IPN Email Notifications', 'woocommerce' ),

View File

@ -76,7 +76,7 @@ class WC_Log_Handler_DB extends WC_Log_Handler {
);
if ( ! empty( $context ) ) {
$insert['context'] = serialize( $context );
$insert['context'] = serialize( $context ); // @codingStandardsIgnoreLine.
}
return false !== $wpdb->insert( "{$wpdb->prefix}woocommerce_log", $insert, $format );
@ -93,6 +93,23 @@ class WC_Log_Handler_DB extends WC_Log_Handler {
return $wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}woocommerce_log" );
}
/**
* Clear entries for a chosen handle/source.
*
* @param string $source Log source.
* @return bool
*/
public function clear( $source ) {
global $wpdb;
return $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_log WHERE source = %s",
$source
)
);
}
/**
* Delete selected logs from DB.
*
@ -111,10 +128,26 @@ class WC_Log_Handler_DB extends WC_Log_Handler {
$query_in = '(' . implode( ',', $format ) . ')';
return $wpdb->query(
return $wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_log WHERE log_id IN {$query_in}" ); // @codingStandardsIgnoreLine.
}
/**
* Delete all logs older than a defined timestamp.
*
* @since 3.4.0
* @param integer $timestamp Timestamp to delete logs before.
*/
public static function delete_logs_before_timestamp( $timestamp = 0 ) {
if ( ! $timestamp ) {
return;
}
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_log WHERE log_id IN {$query_in}", // phpcs:ignore WordPress.WP.PreparedSQL.NotPrepared
$log_ids
"DELETE FROM {$wpdb->prefix}woocommerce_log WHERE timestamp < %d",
$timestamp
)
);
}
@ -140,7 +173,7 @@ class WC_Log_Handler_DB extends WC_Log_Handler {
$debug_backtrace_arg = false;
}
$trace = debug_backtrace( $debug_backtrace_arg ); // phpcs:ignore PHPCompatibility.PHP.NewFunctionParameters.debug_backtrace_optionsFound
$trace = debug_backtrace( $debug_backtrace_arg ); // @codingStandardsIgnoreLine.
foreach ( $trace as $t ) {
if ( isset( $t['file'] ) ) {
$filename = pathinfo( $t['file'], PATHINFO_FILENAME );

View File

@ -48,12 +48,11 @@ class WC_Log_Handler_File extends WC_Log_Handler {
* @param int $log_size_limit Optional. Size limit for log files. Default 5mb.
*/
public function __construct( $log_size_limit = null ) {
if ( null === $log_size_limit ) {
$log_size_limit = 5 * 1024 * 1024;
}
$this->log_size_limit = $log_size_limit;
$this->log_size_limit = apply_filters( 'woocommerce_log_file_size_limit', $log_size_limit );
add_action( 'plugins_loaded', array( $this, 'write_cached_logs' ) );
}
@ -66,7 +65,7 @@ class WC_Log_Handler_File extends WC_Log_Handler {
public function __destruct() {
foreach ( $this->handles as $handle ) {
if ( is_resource( $handle ) ) {
fclose( $handle );
fclose( $handle ); // @codingStandardsIgnoreLine.
}
}
}
@ -144,15 +143,15 @@ class WC_Log_Handler_File extends WC_Log_Handler {
if ( $file ) {
if ( ! file_exists( $file ) ) {
$temphandle = @fopen( $file, 'w+' );
@fclose( $temphandle );
$temphandle = @fopen( $file, 'w+' ); // @codingStandardsIgnoreLine.
@fclose( $temphandle ); // @codingStandardsIgnoreLine.
if ( defined( 'FS_CHMOD_FILE' ) ) {
@chmod( $file, FS_CHMOD_FILE ); // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.chmod_chmod
@chmod( $file, FS_CHMOD_FILE ); // @codingStandardsIgnoreLine.
}
}
$resource = @fopen( $file, $mode );
$resource = @fopen( $file, $mode ); // @codingStandardsIgnoreLine.
if ( $resource ) {
$this->handles[ $handle ] = $resource;
@ -183,7 +182,7 @@ class WC_Log_Handler_File extends WC_Log_Handler {
$result = false;
if ( $this->is_open( $handle ) ) {
$result = fclose( $this->handles[ $handle ] );
$result = fclose( $this->handles[ $handle ] ); // @codingStandardsIgnoreLine.
unset( $this->handles[ $handle ] );
}
@ -206,7 +205,7 @@ class WC_Log_Handler_File extends WC_Log_Handler {
}
if ( $this->open( $handle ) && is_resource( $this->handles[ $handle ] ) ) {
$result = fwrite( $this->handles[ $handle ], $entry . PHP_EOL );
$result = fwrite( $this->handles[ $handle ], $entry . PHP_EOL ); // @codingStandardsIgnoreLine.
} else {
$this->cache_log( $entry, $handle );
}
@ -356,13 +355,17 @@ class WC_Log_Handler_File extends WC_Log_Handler {
/**
* Get a log file name.
*
* File names consist of the handle, followed by the date, followed by a hash, .log.
*
* @since 3.3
* @param string $handle Log name.
* @return bool|string The log file name or false if cannot be determined.
*/
public static function get_log_file_name( $handle ) {
if ( function_exists( 'wp_hash' ) ) {
return sanitize_file_name( $handle . '-' . wp_hash( $handle ) . '.log' );
$date_suffix = date( 'Y-m-d', current_time( 'timestamp', true ) );
$hash_suffix = wp_hash( $handle );
return sanitize_file_name( implode( '-', array( $handle, $date_suffix, $hash_suffix ) ) . '.log' );
} else {
wc_doing_it_wrong( __METHOD__, __( 'This method should not be called before plugins_loaded.', 'woocommerce' ), '3.3' );
return false;
@ -391,4 +394,48 @@ class WC_Log_Handler_File extends WC_Log_Handler {
}
}
/**
* Delete all logs older than a defined timestamp.
*
* @since 3.4.0
* @param integer $timestamp Timestamp to delete logs before.
*/
public static function delete_logs_before_timestamp( $timestamp = 0 ) {
if ( ! $timestamp ) {
return;
}
$log_files = self::get_log_files();
foreach ( $log_files as $log_file ) {
$last_modified = filemtime( trailingslashit( WC_LOG_DIR ) . $log_file );
if ( $last_modified < $timestamp ) {
@unlink( trailingslashit( WC_LOG_DIR ) . $log_file ); // @codingStandardsIgnoreLine.
}
}
}
/**
* Get all log files in the log directory.
*
* @since 3.4.0
* @return array
*/
public static function get_log_files() {
$files = @scandir( WC_LOG_DIR ); // @codingStandardsIgnoreLine.
$result = array();
if ( ! empty( $files ) ) {
foreach ( $files as $key => $value ) {
if ( ! in_array( $value, array( '.', '..' ), true ) ) {
if ( ! is_dir( $value ) && strstr( $value, '.log' ) ) {
$result[ sanitize_title( $value ) ] = $value;
}
}
}
}
return $result;
}
}

View File

@ -574,9 +574,10 @@ class WC_Shortcode_Products {
ob_start();
if ( $products && $products->ids ) {
// Prime meta cache to reduce future queries.
update_meta_cache( 'post', $products->ids );
update_object_term_cache( $products->ids, 'product' );
// Prime caches to reduce future queries.
if ( is_callable( '_prime_post_caches' ) ) {
_prime_post_caches( $products->ids );
}
// Setup the loop.
wc_setup_loop(

View File

@ -1660,6 +1660,20 @@ function wc_get_logger() {
return $logger;
}
/**
* Trigger logging cleanup using the logging class.
*
* @since 3.4.0
*/
function wc_cleanup_logs() {
$logger = wc_get_logger();
if ( is_callable( array( $logger, 'clear_expired_logs' ) ) ) {
$logger->clear_expired_logs();
}
}
add_action( 'woocommerce_cleanup_logs', 'wc_cleanup_logs' );
/**
* Prints human-readable information about a variable.
*

View File

@ -498,9 +498,6 @@ function wc_product_post_class( $classes, $class = '', $post_id = '' ) {
if ( ! $product->get_default_attributes() ) {
$classes[] = 'has-default-attributes';
}
if ( $product->has_child() ) {
$classes[] = 'has-children';
}
}
}

View File

@ -197,8 +197,9 @@ class WC_Tests_Log_Handler_File extends WC_Unit_Test_Case {
*/
public function test_get_log_file_path() {
$log_dir = trailingslashit( WC_LOG_DIR );
$date_suffix = date( 'Y-m-d', current_time( 'timestamp', true ) );
$hash_name = sanitize_file_name( wp_hash( 'unit-tests' ) );
$this->assertEquals( $log_dir . 'unit-tests-' . $hash_name . '.log', WC_Log_Handler_File::get_log_file_path( 'unit-tests' ) );
$this->assertEquals( $log_dir . 'unit-tests-' . $date_suffix . '-' . $hash_name . '.log', WC_Log_Handler_File::get_log_file_path( 'unit-tests' ) );
}
}

View File

@ -25,7 +25,10 @@ class WC_Tests_Logger extends WC_Unit_Test_Case {
$this->greaterThanOrEqual( $time ),
$this->equalTo( 'notice' ),
$this->equalTo( 'this is a message' ),
$this->equalTo( array( 'source' => 'unit-tests', '_legacy' => true ) )
$this->equalTo( array(
'source' => 'unit-tests',
'_legacy' => true,
) )
);
$log = new WC_Logger( array( $handler ), 'debug' );
@ -39,11 +42,10 @@ class WC_Tests_Logger extends WC_Unit_Test_Case {
*/
public function test_clear() {
$file = wc_get_log_file_path( 'unit-tests' );
file_put_contents( $file, 'Test file content.' );
file_put_contents( $file, 'Test file content.' ); // @codingStandardsIgnoreLine.
$log = new WC_Logger();
$log->clear( 'unit-tests' );
$this->assertEquals( '', file_get_contents( $file ) );
$this->setExpectedDeprecated( 'WC_Logger::clear' );
}
/**

View File

@ -239,8 +239,9 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case {
public function test_wc_get_log_file_path() {
$log_dir = trailingslashit( WC_LOG_DIR );
$hash_name = sanitize_file_name( wp_hash( 'unit-tests' ) );
$date_suffix = date( 'Y-m-d', current_time( 'timestamp', true ) );
$this->assertEquals( $log_dir . 'unit-tests-' . $hash_name . '.log', wc_get_log_file_path( 'unit-tests' ) );
$this->assertEquals( $log_dir . 'unit-tests-' . $date_suffix . '-' . $hash_name . '.log', wc_get_log_file_path( 'unit-tests' ) );
}
/**

View File

@ -16,6 +16,7 @@ wp_clear_scheduled_hook( 'woocommerce_scheduled_sales' );
wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_sessions' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_personal_data' );
wp_clear_scheduled_hook( 'woocommerce_cleanup_logs' );
wp_clear_scheduled_hook( 'woocommerce_geoip_updater' );
wp_clear_scheduled_hook( 'woocommerce_tracker_send_event' );