Overview

Namespaces

  • None
  • VSP
    • Core
      • Abstracts
      • Interfaces
      • Traits
        • WC_Compatibility
    • Deprecation
    • Helper
    • Modules
      • Addons
      • Logger

Classes

  • VSP\Ajax
  • VSP\Ajaxer
  • VSP\Base
  • VSP\Cache
  • VSP\Core\Abstracts\Addon
  • VSP\Core\Abstracts\Log_Handler
  • VSP\Core\Abstracts\Plugin_Settings
  • VSP\Core\Instance_Handler
  • VSP\Deprecation\Actions
  • VSP\Deprecation\Filters
  • VSP\Error
  • VSP\Framework
  • VSP\Framework_Admin
  • VSP\Framework_Base
  • VSP\Framework_Modules
  • VSP\Helper
  • VSP\Helper\Price_Calculation
  • VSP\Modules\Addons
  • VSP\Modules\Addons\Admin
  • VSP\Modules\Addons\Core
  • VSP\Modules\Logger
  • VSP\Modules\Logger\File_Handler
  • VSP\Modules\Logger\Levels
  • VSP\Modules\Shortcode
  • VSP\Modules\System_Logs
  • VSP\Modules\System_Tools
  • VSP\Modules\WPOnion
  • VSP\Setup
  • VSP\WC_Compatibility
  • VSP_Framework_Loader

Interfaces

  • VSP\Core\Interfaces\Log_Handler
  • VSP\Core\Interfaces\Logger

Traits

  • VSP\Core\Traits\Array_Helper
  • VSP\Core\Traits\Framework
  • VSP\Core\Traits\String_Helper
  • VSP\Core\Traits\URL
  • VSP\Core\Traits\WC_Compatibility\Product
  • VSP\Core\Traits\WC_Compatibility\Version
  • VSP\Core\Traits\WC_Helper
  • VSP\Core\Traits\WP

Functions

  • vsp_add_wc_required_notice
  • vsp_ajax_action
  • vsp_current_screen
  • vsp_date_format
  • vsp_delete_cache
  • vsp_doing_it_wrong
  • vsp_force_load
  • vsp_force_load_vendors
  • vsp_get_cache
  • vsp_get_cache_defaults
  • vsp_get_file_paths
  • vsp_get_logger
  • vsp_get_time_in_seconds
  • vsp_is_admin
  • vsp_is_ajax
  • vsp_is_cron
  • vsp_is_error
  • vsp_is_frontend
  • vsp_is_heartbeat
  • vsp_is_json
  • vsp_is_request
  • vsp_is_screen
  • vsp_json_last_error
  • vsp_list_files
  • vsp_list_log_files
  • vsp_load_core_assets
  • vsp_load_file
  • vsp_log_msg
  • vsp_logger
  • vsp_make_log_list_tree
  • vsp_maybe_load
  • vsp_placeholder_img
  • vsp_print_log_files_ui
  • vsp_register_assets
  • vsp_register_plugin
  • vsp_send_callback_error
  • vsp_send_callback_success
  • vsp_send_json_callback
  • vsp_set_cache
  • vsp_set_time_limit
  • vsp_slashit
  • vsp_time_format
  • vsp_unslashit
  • vsp_url
  • vsp_validate_required_plugin
  • Overview
  • Namespace
  • Class
  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 
<?php

namespace VSP\Modules\Logger;

defined( 'ABSPATH' ) || exit;

use VSP\Core\Abstracts\Log_Handler;
use VSP\Setup;

/**
 * Class VSP_Log_Handler_File
 *
 * @author Varun Sridharan <varunsridharan23@gmail.com>
 */
class File_Handler extends Log_Handler {
    /**
     * sub_path
     *
     * @var bool
     */
    protected $sub_path = false;

    /**
     * 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();

    /**
     * @var null
     */
    protected $file_name = null;

    /**
     * VSP_Log_Handler_File constructor.
     *
     * @param bool                $sub_path
     * @param string|boolean|null $file_name
     * @param int                 $log_size_limit Optional. Size limit for log files. Default 5mb.
     */
    public function __construct( $sub_path = false, $file_name = null, $log_size_limit = null ) {
        if ( null === $log_size_limit || false === $log_size_limit ) {
            $log_size_limit = 5 * 1024 * 1024;
        }

        $this->log_size_limit = $log_size_limit;
        $this->sub_path       = $sub_path;
        $this->file_name      = $file_name;
        add_action( 'vsp/init', array( $this, 'write_cached_logs' ), 1 );
    }

    /**
     * Destructor.
     *
     * Cleans up open file handles.
     */
    public function __destruct() {
        foreach ( $this->handles as $handle ) {
            if ( is_resource( $handle ) ) {
                fclose( $handle );
            }
        }
    }

    /**
     * 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 VSP_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( 'vsp/log/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;
    }

    /**
     * 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 );
        } else {
            $this->cache_log( $entry, $handle );
        }
        return false !== $result;
    }

    /**
     * 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 = $this->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;
            }
        }
        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 function get_log_file_path( $handle ) {
        if ( function_exists( 'wp_hash' ) ) {
            if ( false !== $this->sub_path ) {
                Setup::check_create_log_folder( vsp_slashit( VSP_LOG_DIR ) . $this->sub_path );
                return vsp_slashit( VSP_LOG_DIR ) . vsp_slashit( $this->sub_path ) . $this->get_log_file_name( $handle );
            } else {
                Setup::check_create_log_folder( vsp_slashit( VSP_LOG_DIR ) );
                return vsp_slashit( VSP_LOG_DIR ) . $this->get_log_file_name( $handle );
            }
        } else {
            vsp_doing_it_wrong( __METHOD__, esc_html__( 'This method should not be called before plugins_loaded.', 'vsp-framework' ), '3.0' );
            return false;
        }
    }

    /**
     * Get a log file name.
     *
     * @param string $handle Log name.
     *
     * @return bool|string The log file name or false if cannot be determined.
     */
    public function get_log_file_name( $handle ) {
        if ( function_exists( 'wp_hash' ) ) {
            if ( empty( $this->file_name ) ) {
                return sanitize_file_name( $handle . '-' . wp_hash( $handle . '_' . $this->sub_path ) . '.log' );
            } else {
                return sanitize_file_name( $this->file_name . '-' . wp_hash( $handle . '_' . $this->sub_path ) . '.log' );
            }
        } else {
            vsp_doing_it_wrong( __METHOD__, esc_html__( 'This method should not be called before plugins_loaded.', 'vsp-framework' ), '3.3' );
            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 ] );
    }

    /**
     * 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 = $this->get_log_file_path( "{$handle}{$suffix}" );
        $rename_to   = $this->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;
        }
    }

    /**
     * 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 ] );
            unset( $this->handles[ $handle ] );
        }
        return $result;
    }

    /**
     * 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 = $this->get_log_file_path( $handle );
        if ( $file ) {
            if ( ! file_exists( $file ) ) {
                $temphandle = @fopen( $file, 'w+' );
                @fclose( $temphandle );
                if ( defined( 'FS_CHMOD_FILE' ) ) {
                    @chmod( $file, FS_CHMOD_FILE );
                }
            }
            $resource = @fopen( $file, $mode );
            if ( $resource ) {
                $this->handles[ $handle ] = $resource;
                return true;
            }
        }
        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,
        );
    }

    /**
     * Clear entries from chosen file.
     *
     * @param string $handle Log handle.
     *
     * @return bool
     */
    public function clear( $handle ) {
        $result = false;
        $this->close( $handle );
        if ( $this->open( $handle, 'w' ) && is_resource( $this->handles[ $handle ] ) ) {
            $result = true;
        }
        do_action( 'vsp/log/clear', $handle );
        return $result;
    }

    /**
     * Remove/delete the chosen file.
     *
     * @param string $handle Log handle.
     *
     * @return bool
     */
    public function remove( $handle ) {
        $removed = false;
        $file    = $this->get_log_file_path( $handle );
        if ( $file ) {
            if ( is_file( $file ) && is_writable( $file ) ) { // phpcs:ignore WordPress.VIP.FileSystemWritesDisallow.file_ops_is_writable
                $this->close( $handle ); // 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( 'vsp/log/remove', $handle, $removed );
        }
        return $removed;
    }

    /**
     * Write cached logs.
     */
    public function write_cached_logs() {
        foreach ( $this->cached_logs as $log ) {
            $this->add( $log['entry'], $log['handle'] );
        }
    }
}
API documentation generated by ApiGen