initial commit

This commit is contained in:
2021-12-10 12:03:04 +00:00
commit c46c7ddbf0
3643 changed files with 582794 additions and 0 deletions

View File

@ -0,0 +1,189 @@
<?php
/**
* Class WC_Log_Handler_DB file.
*
* @package WooCommerce\Log Handlers
*/
use Automattic\Jetpack\Constants;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Handles log entries by writing to database.
*
* @class WC_Log_Handler_DB
* @version 1.0.0
* @package WooCommerce\Classes\Log_Handlers
*/
class WC_Log_Handler_DB extends WC_Log_Handler {
/**
* Handle a log entry.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param array $context {
* Additional information for log handlers.
*
* @type string $source Optional. Source will be available in log table.
* If no source is provided, attempt to provide sensible default.
* }
*
* @see WC_Log_Handler_DB::get_log_source() for default source.
*
* @return bool False if value was not handled and true if value was handled.
*/
public function handle( $timestamp, $level, $message, $context ) {
if ( isset( $context['source'] ) && $context['source'] ) {
$source = $context['source'];
} else {
$source = $this->get_log_source();
}
return $this->add( $timestamp, $level, $message, $source, $context );
}
/**
* Add a log entry to chosen file.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param string $source Log source. Useful for filtering and sorting.
* @param array $context Context will be serialized and stored in database.
*
* @return bool True if write was successful.
*/
protected static function add( $timestamp, $level, $message, $source, $context ) {
global $wpdb;
$insert = array(
'timestamp' => date( 'Y-m-d H:i:s', $timestamp ),
'level' => WC_Log_Levels::get_level_severity( $level ),
'message' => $message,
'source' => $source,
);
$format = array(
'%s',
'%d',
'%s',
'%s',
'%s', // possible serialized context.
);
if ( ! empty( $context ) ) {
$insert['context'] = serialize( $context ); // @codingStandardsIgnoreLine.
}
return false !== $wpdb->insert( "{$wpdb->prefix}woocommerce_log", $insert, $format );
}
/**
* Clear all logs from the DB.
*
* @return bool True if flush was successful.
*/
public static function flush() {
global $wpdb;
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.
*
* @param int|string|array $log_ids Log ID or array of Log IDs to be deleted.
*
* @return bool
*/
public static function delete( $log_ids ) {
global $wpdb;
if ( ! is_array( $log_ids ) ) {
$log_ids = array( $log_ids );
}
$format = array_fill( 0, count( $log_ids ), '%d' );
$query_in = '(' . implode( ',', $format ) . ')';
return $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_log WHERE log_id IN {$query_in}", $log_ids ) ); // @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 timestamp < %s",
date( 'Y-m-d H:i:s', $timestamp )
)
);
}
/**
* Get appropriate source based on file name.
*
* Try to provide an appropriate source in case none is provided.
*
* @return string Text to use as log source. "" (empty string) if none is found.
*/
protected static function get_log_source() {
static $ignore_files = array( 'class-wc-log-handler-db', 'class-wc-logger' );
/**
* PHP < 5.3.6 correct behavior
*
* @see http://php.net/manual/en/function.debug-backtrace.php#refsect1-function.debug-backtrace-parameters
*/
if ( Constants::is_defined( 'DEBUG_BACKTRACE_IGNORE_ARGS' ) ) {
$debug_backtrace_arg = DEBUG_BACKTRACE_IGNORE_ARGS; // phpcs:ignore PHPCompatibility.Constants.NewConstants.debug_backtrace_ignore_argsFound
} else {
$debug_backtrace_arg = false;
}
$trace = debug_backtrace( $debug_backtrace_arg ); // @codingStandardsIgnoreLine.
foreach ( $trace as $t ) {
if ( isset( $t['file'] ) ) {
$filename = pathinfo( $t['file'], PATHINFO_FILENAME );
if ( ! in_array( $filename, $ignore_files, true ) ) {
return $filename;
}
}
}
return '';
}
}

View File

@ -0,0 +1,226 @@
<?php
/**
* Class WC_Log_Handler_Email file.
*
* @package WooCommerce\Log Handlers
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Handles log entries by sending an email.
*
* WARNING!
* This log handler has known limitations.
*
* Log messages are aggregated and sent once per request (if necessary). If the site experiences a
* problem, the log email may never be sent. This handler should be used with another handler which
* stores logs in order to prevent loss.
*
* It is not recommended to use this handler on a high traffic site. There will be a maximum of 1
* email sent per request per handler, but that could still be a dangerous amount of emails under
* heavy traffic. Do not confuse this handler with an appropriate monitoring solution!
*
* If you understand these limitations, feel free to use this handler or borrow parts of the design
* to implement your own!
*
* @class WC_Log_Handler_Email
* @version 1.0.0
* @package WooCommerce\Classes\Log_Handlers
*/
class WC_Log_Handler_Email extends WC_Log_Handler {
/**
* Minimum log level this handler will process.
*
* @var int Integer representation of minimum log level to handle.
*/
protected $threshold;
/**
* Stores email recipients.
*
* @var array
*/
protected $recipients = array();
/**
* Stores log messages.
*
* @var array
*/
protected $logs = array();
/**
* Stores integer representation of maximum logged level.
*
* @var int
*/
protected $max_severity = null;
/**
* Constructor for log handler.
*
* @param string|array $recipients Optional. Email(s) to receive log messages. Defaults to site admin email.
* @param string $threshold Optional. Minimum level that should receive log messages.
* Default 'alert'. One of: emergency|alert|critical|error|warning|notice|info|debug.
*/
public function __construct( $recipients = null, $threshold = 'alert' ) {
if ( null === $recipients ) {
$recipients = get_option( 'admin_email' );
}
if ( is_array( $recipients ) ) {
foreach ( $recipients as $recipient ) {
$this->add_email( $recipient );
}
} else {
$this->add_email( $recipients );
}
$this->set_threshold( $threshold );
add_action( 'shutdown', array( $this, 'send_log_email' ) );
}
/**
* Set handler severity threshold.
*
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
*/
public function set_threshold( $level ) {
$this->threshold = WC_Log_Levels::get_level_severity( $level );
}
/**
* Determine whether handler should handle log.
*
* @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 ) {
return $this->threshold <= WC_Log_Levels::get_level_severity( $level );
}
/**
* Handle a log entry.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param array $context Optional. Additional information for log handlers.
*
* @return bool False if value was not handled and true if value was handled.
*/
public function handle( $timestamp, $level, $message, $context ) {
if ( $this->should_handle( $level ) ) {
$this->add_log( $timestamp, $level, $message, $context );
return true;
}
return false;
}
/**
* Send log email.
*
* @return bool True if email is successfully sent otherwise false.
*/
public function send_log_email() {
$result = false;
if ( ! empty( $this->logs ) ) {
$subject = $this->get_subject();
$body = $this->get_body();
$result = wp_mail( $this->recipients, $subject, $body );
$this->clear_logs();
}
return $result;
}
/**
* Build subject for log email.
*
* @return string subject
*/
protected function get_subject() {
$site_name = get_bloginfo( 'name' );
$max_level = strtoupper( WC_Log_Levels::get_severity_level( $this->max_severity ) );
$log_count = count( $this->logs );
return sprintf(
/* translators: 1: Site name 2: Maximum level 3: Log count */
_n(
'[%1$s] %2$s: %3$s WooCommerce log message',
'[%1$s] %2$s: %3$s WooCommerce log messages',
$log_count,
'woocommerce'
),
$site_name,
$max_level,
$log_count
);
}
/**
* Build body for log email.
*
* @return string body
*/
protected function get_body() {
$site_name = get_bloginfo( 'name' );
$entries = implode( PHP_EOL, $this->logs );
$log_count = count( $this->logs );
return _n(
'You have received the following WooCommerce log message:',
'You have received the following WooCommerce log messages:',
$log_count,
'woocommerce'
) . PHP_EOL
. PHP_EOL
. $entries
. PHP_EOL
. PHP_EOL
/* translators: %s: Site name */
. sprintf( __( 'Visit %s admin area:', 'woocommerce' ), $site_name )
. PHP_EOL
. admin_url();
}
/**
* Adds an email to the list of recipients.
*
* @param string $email Email address to add.
*/
public function add_email( $email ) {
array_push( $this->recipients, $email );
}
/**
* Add log message.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param array $context Additional information for log handlers.
*/
protected function add_log( $timestamp, $level, $message, $context ) {
$this->logs[] = $this->format_entry( $timestamp, $level, $message, $context );
$log_severity = WC_Log_Levels::get_level_severity( $level );
if ( $this->max_severity < $log_severity ) {
$this->max_severity = $log_severity;
}
}
/**
* Clear log messages.
*/
protected function clear_logs() {
$this->logs = array();
}
}

View File

@ -0,0 +1,446 @@
<?php
/**
* Class WC_Log_Handler_File file.
*
* @package WooCommerce\Log Handlers
*/
use Automattic\Jetpack\Constants;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Handles log entries by writing to a file.
*
* @class WC_Log_Handler_File
* @version 1.0.0
* @package WooCommerce\Classes\Log_Handlers
*/
class WC_Log_Handler_File extends WC_Log_Handler {
/**
* Stores open file handles.
*
* @var array
*/
protected $handles = array();
/**
* File size limit for log files in bytes.
*
* @var int
*/
protected $log_size_limit;
/**
* Cache logs that could not be written.
*
* If a log is written too early in the request, pluggable functions may be unavailable. These
* logs will be cached and written on 'plugins_loaded' action.
*
* @var array
*/
protected $cached_logs = array();
/**
* Constructor for the logger.
*
* @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 = apply_filters( 'woocommerce_log_file_size_limit', $log_size_limit );
add_action( 'plugins_loaded', array( $this, 'write_cached_logs' ) );
}
/**
* Destructor.
*
* Cleans up open file handles.
*/
public function __destruct() {
foreach ( $this->handles as $handle ) {
if ( is_resource( $handle ) ) {
fclose( $handle ); // @codingStandardsIgnoreLine.
}
}
}
/**
* Handle a log entry.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param array $context {
* Additional information for log handlers.
*
* @type string $source Optional. Determines log file to write to. Default 'log'.
* @type bool $_legacy Optional. Default false. True to use outdated log format
* originally used in deprecated WC_Logger::add calls.
* }
*
* @return bool False if value was not handled and true if value was handled.
*/
public function handle( $timestamp, $level, $message, $context ) {
if ( isset( $context['source'] ) && $context['source'] ) {
$handle = $context['source'];
} else {
$handle = 'log';
}
$entry = self::format_entry( $timestamp, $level, $message, $context );
return $this->add( $entry, $handle );
}
/**
* Builds a log entry text from timestamp, level and message.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug.
* @param string $message Log message.
* @param array $context Additional information for log handlers.
*
* @return string Formatted log entry.
*/
protected static function format_entry( $timestamp, $level, $message, $context ) {
if ( isset( $context['_legacy'] ) && true === $context['_legacy'] ) {
if ( isset( $context['source'] ) && $context['source'] ) {
$handle = $context['source'];
} else {
$handle = 'log';
}
$message = apply_filters( 'woocommerce_logger_add_message', $message, $handle );
$time = date_i18n( 'm-d-Y @ H:i:s' );
$entry = "{$time} - {$message}";
} else {
$entry = parent::format_entry( $timestamp, $level, $message, $context );
}
return $entry;
}
/**
* Open log file for writing.
*
* @param string $handle Log handle.
* @param string $mode Optional. File mode. Default 'a'.
* @return bool Success.
*/
protected function open( $handle, $mode = 'a' ) {
if ( $this->is_open( $handle ) ) {
return true;
}
$file = self::get_log_file_path( $handle );
if ( $file ) {
if ( ! file_exists( $file ) ) {
$temphandle = @fopen( $file, 'w+' ); // @codingStandardsIgnoreLine.
if ( is_resource( $temphandle ) ) {
@fclose( $temphandle ); // @codingStandardsIgnoreLine.
if ( Constants::is_defined( 'FS_CHMOD_FILE' ) ) {
@chmod( $file, FS_CHMOD_FILE ); // @codingStandardsIgnoreLine.
}
}
}
$resource = @fopen( $file, $mode ); // @codingStandardsIgnoreLine.
if ( $resource ) {
$this->handles[ $handle ] = $resource;
return true;
}
}
return false;
}
/**
* Check if a handle is open.
*
* @param string $handle Log handle.
* @return bool True if $handle is open.
*/
protected function is_open( $handle ) {
return array_key_exists( $handle, $this->handles ) && is_resource( $this->handles[ $handle ] );
}
/**
* Close a handle.
*
* @param string $handle Log handle.
* @return bool success
*/
protected function close( $handle ) {
$result = false;
if ( $this->is_open( $handle ) ) {
$result = fclose( $this->handles[ $handle ] ); // @codingStandardsIgnoreLine.
unset( $this->handles[ $handle ] );
}
return $result;
}
/**
* Add a log entry to chosen file.
*
* @param string $entry Log entry text.
* @param string $handle Log entry handle.
*
* @return bool True if write was successful.
*/
protected function add( $entry, $handle ) {
$result = false;
if ( $this->should_rotate( $handle ) ) {
$this->log_rotate( $handle );
}
if ( $this->open( $handle ) && is_resource( $this->handles[ $handle ] ) ) {
$result = fwrite( $this->handles[ $handle ], $entry . PHP_EOL ); // @codingStandardsIgnoreLine.
} else {
$this->cache_log( $entry, $handle );
}
return false !== $result;
}
/**
* Clear entries from chosen file.
*
* @param string $handle Log handle.
*
* @return bool
*/
public function clear( $handle ) {
$result = false;
// Close the file if it's already open.
$this->close( $handle );
/**
* $this->open( $handle, 'w' ) == Open the file for writing only. Place the file pointer at
* the beginning of the file, and truncate the file to zero length.
*/
if ( $this->open( $handle, 'w' ) && is_resource( $this->handles[ $handle ] ) ) {
$result = true;
}
do_action( 'woocommerce_log_clear', $handle );
return $result;
}
/**
* Remove/delete the chosen file.
*
* @param string $handle Log handle.
*
* @return bool
*/
public function remove( $handle ) {
$removed = false;
$logs = $this->get_log_files();
$handle = sanitize_title( $handle );
if ( isset( $logs[ $handle ] ) && $logs[ $handle ] ) {
$file = realpath( trailingslashit( WC_LOG_DIR ) . $logs[ $handle ] );
if ( 0 === stripos( $file, realpath( trailingslashit( WC_LOG_DIR ) ) ) && is_file( $file ) && is_writable( $file ) ) { // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.file_ops_is_writable
$this->close( $file ); // Close first to be certain no processes keep it alive after it is unlinked.
$removed = unlink( $file ); // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.file_ops_unlink
}
do_action( 'woocommerce_log_remove', $handle, $removed );
}
return $removed;
}
/**
* Check if log file should be rotated.
*
* Compares the size of the log file to determine whether it is over the size limit.
*
* @param string $handle Log handle.
* @return bool True if if should be rotated.
*/
protected function should_rotate( $handle ) {
$file = self::get_log_file_path( $handle );
if ( $file ) {
if ( $this->is_open( $handle ) ) {
$file_stat = fstat( $this->handles[ $handle ] );
return $file_stat['size'] > $this->log_size_limit;
} elseif ( file_exists( $file ) ) {
return filesize( $file ) > $this->log_size_limit;
} else {
return false;
}
} else {
return false;
}
}
/**
* Rotate log files.
*
* Logs are rotated by prepending '.x' to the '.log' suffix.
* The current log plus 10 historical logs are maintained.
* For example:
* base.9.log -> [ REMOVED ]
* base.8.log -> base.9.log
* ...
* base.0.log -> base.1.log
* base.log -> base.0.log
*
* @param string $handle Log handle.
*/
protected function log_rotate( $handle ) {
for ( $i = 8; $i >= 0; $i-- ) {
$this->increment_log_infix( $handle, $i );
}
$this->increment_log_infix( $handle );
}
/**
* Increment a log file suffix.
*
* @param string $handle Log handle.
* @param null|int $number Optional. Default null. Log suffix number to be incremented.
* @return bool True if increment was successful, otherwise false.
*/
protected function increment_log_infix( $handle, $number = null ) {
if ( null === $number ) {
$suffix = '';
$next_suffix = '.0';
} else {
$suffix = '.' . $number;
$next_suffix = '.' . ( $number + 1 );
}
$rename_from = self::get_log_file_path( "{$handle}{$suffix}" );
$rename_to = self::get_log_file_path( "{$handle}{$next_suffix}" );
if ( $this->is_open( $rename_from ) ) {
$this->close( $rename_from );
}
if ( is_writable( $rename_from ) ) { // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.file_ops_is_writable
return rename( $rename_from, $rename_to ); // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.file_ops_rename
} else {
return false;
}
}
/**
* Get a log file path.
*
* @param string $handle Log name.
* @return bool|string The log file path or false if path cannot be determined.
*/
public static function get_log_file_path( $handle ) {
if ( function_exists( 'wp_hash' ) ) {
return trailingslashit( WC_LOG_DIR ) . self::get_log_file_name( $handle );
} else {
wc_doing_it_wrong( __METHOD__, __( 'This method should not be called before plugins_loaded.', 'woocommerce' ), '3.0' );
return false;
}
}
/**
* 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' ) ) {
$date_suffix = date( 'Y-m-d', time() );
$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;
}
}
/**
* Cache log to write later.
*
* @param string $entry Log entry text.
* @param string $handle Log entry handle.
*/
protected function cache_log( $entry, $handle ) {
$this->cached_logs[] = array(
'entry' => $entry,
'handle' => $handle,
);
}
/**
* Write cached logs.
*/
public function write_cached_logs() {
foreach ( $this->cached_logs as $log ) {
$this->add( $log['entry'], $log['handle'] );
}
}
/**
* 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;
}
}