| 1 |
<?php |
| 2 |
/** |
| 3 |
* The log rotation class. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component\Logger |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component\Logger; |
| 9 |
|
| 10 |
use WP_Defender\Traits\IO; |
| 11 |
|
| 12 |
/** |
| 13 |
* Deals rotation log file naming & purging old logs. |
| 14 |
*/ |
| 15 |
class Rotation_Logger implements Rotation_Logger_Interface { |
| 16 |
use IO; |
| 17 |
|
| 18 |
public const ROTATION_FREQUENCY = 7; |
| 19 |
public const ROTATION_UNIT = 'day'; |
| 20 |
|
| 21 |
/** |
| 22 |
* Class constructor to clear file status cache. |
| 23 |
*/ |
| 24 |
public function __construct() { |
| 25 |
clearstatcache(); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Generate a new filename with date suffix. |
| 30 |
* |
| 31 |
* @param string $filename Filename which requires date suffix. |
| 32 |
* |
| 33 |
* @return string Formatted date suffixed file name. |
| 34 |
*/ |
| 35 |
public function generate_file_name( $filename ) { |
| 36 |
$file_parts = pathinfo( $filename ); |
| 37 |
|
| 38 |
$file_name = $file_parts['filename'] . gmdate( '-Y-m-d' ); |
| 39 |
|
| 40 |
if ( ! empty( $file_parts['extension'] ) ) { |
| 41 |
$file_name .= '.' . $file_parts['extension']; |
| 42 |
} |
| 43 |
|
| 44 |
return $file_name; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Purge logs whose modified time exceeded the threshold limit. |
| 49 |
* |
| 50 |
* @param string $directory_path Pathname of the directory. |
| 51 |
* @param int $count A period as integer value. |
| 52 |
* @param string $unit A standard datetime relative format unit, like days or months. |
| 53 |
*/ |
| 54 |
public function purge_old_log( |
| 55 |
$directory_path = '', |
| 56 |
$count = self::ROTATION_FREQUENCY, |
| 57 |
$unit = self::ROTATION_UNIT |
| 58 |
) { |
| 59 |
$threshold_timestamp = strtotime( '-' . $count . $unit ); |
| 60 |
$directory_path = $directory_path ?: $this->get_tmp_path(); |
| 61 |
$iterator = new \GlobIterator( $directory_path . '/*.log' ); |
| 62 |
|
| 63 |
while ( $iterator->valid() ) { |
| 64 |
|
| 65 |
if ( $iterator->getMTime() < $threshold_timestamp ) { |
| 66 |
wp_delete_file( $iterator->getPathname() ); |
| 67 |
} |
| 68 |
|
| 69 |
$iterator->next(); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Invoke all init methods. |
| 75 |
*/ |
| 76 |
public function init() { |
| 77 |
/** |
| 78 |
* Delete old logs rotationally. |
| 79 |
*/ |
| 80 |
if ( ! wp_next_scheduled( 'wpdef_log_rotational_delete' ) ) { |
| 81 |
wp_schedule_event( time(), 'daily', 'wpdef_log_rotational_delete' ); |
| 82 |
} |
| 83 |
add_action( 'wpdef_log_rotational_delete', array( &$this, 'purge_old_log' ) ); |
| 84 |
} |
| 85 |
} |
| 86 |
|