class-learndash-logger.php 9.38 KB
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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
<?php
/**
 * This class provides an easy way to log everything.
 *
 * @since 4.5.0
 *
 * @package LearnDash
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Learndash_Logger' ) ) {
	/**
	 * Logger class.
	 *
	 * @since 4.5.0
	 */
	abstract class Learndash_Logger {
		private const PATH_ID                   = 'learndash_logs';
		private const PATH                      = 'learndash' . DIRECTORY_SEPARATOR . 'logs';
		private const EXTENSION                 = '.log';
		private const SUFFIXES_META_KEY         = 'learndash_log_suffixes';
		private const DEFAULT_MAX_SIZE_IN_BYTES = 10485760; // 10MB.

		/**
		 * Instructions to protect the path against direct access.
		 *
		 * @since 4.5.0
		 *
		 * @var string
		 */
		private static $file_protection_instructions = '';

		/**
		 * Log file stream.
		 *
		 * @since 4.5.0
		 *
		 * @var resource|null|false
		 */
		private $log_stream = null;

		/**
		 * List on initialized loggers.
		 *
		 * @since 4.5.0
		 *
		 * @var Learndash_Logger[]
		 */
		private static $loggers = array();

		/**
		 * Returns the logger instance if available.
		 *
		 * @since 4.5.0
		 *
		 * @param string $name Logger name.
		 *
		 * @return Learndash_Logger|null
		 */
		public static function get_instance( string $name ): ?self {
			return self::$loggers[ $name ] ?? null;
		}

		/**
		 * Logger destructor.
		 *
		 * @since 4.5.0
		 *
		 * @return void
		 */
		public function __destruct() {
			if ( is_resource( $this->log_stream ) ) {
				fclose( $this->log_stream ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
			}
		}

		/**
		 * Inits a logger.
		 *
		 * @since 4.5.0
		 *
		 * @return void
		 */
		final public function init(): void {
			self::$loggers[ $this->get_name() ] = $this;
		}

		/**
		 * Returns the label.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		abstract public function get_label(): string;

		/**
		 * Returns the name.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		abstract public function get_name(): string;

		/**
		 * Creates the logger resource if needed.
		 *
		 * @since 4.5.0
		 *
		 * @return void
		 */
		private function maybe_create_resource() {
			if ( is_resource( $this->log_stream ) ) {
				return;
			}

			try {
				$this->maybe_rotate_file();

				$this->log_stream = fopen( // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fopen
					self::get_log_path( $this->get_name() ),
					'a'
				);
			} catch ( Exception $e ) {
				return;
			}
		}

		/**
		 * Rotates the log file if needed.
		 *
		 * @return void
		 */
		private function maybe_rotate_file() {
			$log_path = self::get_log_path( $this->get_name() );
			if ( ! is_file( $log_path ) ) {
				return;
			}

			$file_size = filesize( $log_path );
			if ( ! $file_size ) {
				return;
			}

			/**
			 * Filters the maximum log file size in bytes.
			 *
			 * @since 4.5.0
			 *
			 * @param int              $max_size         Maximum log file size in bytes.
			 * @param Learndash_Logger $learndash_logger Logger instance.
			 */
			$max_file_size = apply_filters( 'learndash_logger_max_file_size', self::DEFAULT_MAX_SIZE_IN_BYTES, $this );
			if ( $file_size < $max_file_size ) {
				return;
			}

			// calculate the new size.
			$new_file_size = min( $max_file_size, $file_size * 0.9 ); // reduce the file size by 10%.

			// create a temporary file to save the new data.
			$temp_path = $log_path . '.tmp';
			$temp_file = fopen( $temp_path, 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fopen

			if ( ! $temp_file ) {
				return;
			}

			// copy the data from the log file to the temporary file skipping the first part.
			$log_file = fopen( $log_path, 'r' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fopen

			if ( ! $log_file ) {
				return;
			}

			fseek( $log_file, (int) ( $file_size - $new_file_size ) );
			while ( ! feof( $log_file ) ) {
				if ( $content = fgets( $log_file ) ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.Found,Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure
					fwrite( $temp_file, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fwrite
				}
			}

			// move the temporary file to the log file.
			rename( $temp_path, $log_path );

			fclose( $temp_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
			fclose( $log_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
		}

		/**
		 * Writes to the log file.
		 *
		 * @since 4.5.0
		 *
		 * @param string $formatted_message Formatted message.
		 * @param string $prefix            Prefix. Default empty.
		 *
		 * @return void
		 */
		private function write( string $formatted_message, string $prefix = '' ): void {
			try {
				if ( ! $this->is_enabled() ) {
					return;
				}
			} catch ( Exception $e ) {
				return;
			}

			$this->maybe_create_resource();
			if ( ! is_resource( $this->log_stream ) ) {
				return;
			}

			if ( ! empty( $prefix ) ) {
				$formatted_message = '[' . $prefix . '] ' . $formatted_message;
			}

			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fwrite
			fwrite( $this->log_stream, current_time( 'Y-m-d H:i:s: ' ) . $formatted_message . PHP_EOL );
		}

		/**
		 * Writes an information to the log file.
		 *
		 * @since 4.5.0
		 *
		 * @param string $message Message.
		 * @param string $prefix  Prefix. Optional.
		 *
		 * @return void
		 */
		public function info( string $message, string $prefix = '' ): void {
			$this->write( $message, $prefix );
		}

		/**
		 * Writes an error to the log file.
		 *
		 * @since 4.5.0
		 *
		 * @param string $message Message.
		 * @param string $prefix Prefix. Optional.
		 *
		 * @return void
		 */
		public function error( string $message, string $prefix = '' ): void {
			$this->write( 'Error: ' . $message, $prefix );
		}

		/**
		 * Returns the download URL.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		public function get_download_url(): string {
			return Learndash_Admin_File_Download_Handler::get_download_url(
				self::PATH_ID,
				basename( $this->get_log_path( $this->get_name() ) )
			);
		}

		/**
		 * Checks if the logger file exists.
		 *
		 * @since 4.5.0
		 *
		 * @return bool True if the logger file exists, false otherwise.
		 */
		public function log_exists(): bool {
			return file_exists( $this->get_log_path( $this->get_name() ) );
		}

		/**
		 * Returns the log content.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		public function get_content(): string {
			$log_path = $this->get_log_path( $this->get_name() );

			if ( ! file_exists( $log_path ) ) {
				return '';
			}

			$content = file_get_contents( $log_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents

			if ( false === $content ) {
				return '';
			}

			return $content;
		}

		/**
		 * Deletes the log content.
		 *
		 * @since 4.5.0
		 *
		 * @return bool
		 */
		public function delete_content(): bool {
			$log_path = $this->get_log_path( $this->get_name() );

			if ( ! file_exists( $log_path ) ) {
				return true;
			}

			return unlink( $log_path );
		}

		/**
		 * Returns the path to the log file in the "uploads" directory.
		 *
		 * @param string $file_name Log file name. Default empty.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		private static function get_log_path( string $file_name = '' ): string {
			$log_path = trailingslashit( wp_upload_dir()['basedir'] ) . self::PATH;

			if ( ! empty( $file_name ) ) {
				$logs_suffixes = (array) get_option( self::SUFFIXES_META_KEY, array() );

				if ( ! isset( $logs_suffixes[ $file_name ] ) ) {
					$logs_suffixes[ $file_name ] = uniqid( '', true );
					update_option( self::SUFFIXES_META_KEY, $logs_suffixes );
				}

				$log_path .= DIRECTORY_SEPARATOR . $file_name . $logs_suffixes[ $file_name ] . self::EXTENSION;
			}

			return $log_path;
		}

		/**
		 * Initialize the log directory
		 *
		 * @since 4.5.0
		 *
		 * @return void
		 */
		public static function init_log_directory() {
			$log_dir = self::get_log_path();

			if ( ! is_dir( $log_dir ) ) {
				wp_mkdir_p( $log_dir );
			}

			learndash_put_directory_index_file( trailingslashit( $log_dir ) . 'index.php' );

			Learndash_Admin_File_Download_Handler::register_file_path( self::PATH_ID, $log_dir );

			self::$file_protection_instructions = Learndash_Admin_File_Download_Handler::try_to_protect_file_path( $log_dir );
		}

		/**
		 * Returns the file protection instructions.
		 *
		 * @since 4.5.0
		 *
		 * @return string
		 */
		public static function get_file_protection_instructions(): string {
			return self::$file_protection_instructions;
		}

		/**
		 * Gets loggers select. Keys are logger names and values are logger labels.
		 *
		 * @since 4.5.0
		 *
		 * @return array<string,string>
		 */
		public static function get_select_list(): array {
			$result = array();

			foreach ( self::$loggers as $logger ) {
				$result[ $logger->get_name() ] = $logger->get_label();
			}

			return $result;
		}

		/**
		 * Returns true if the logger is enabled, false otherwise.
		 *
		 * @since 4.5.0
		 *
		 * @throws Exception If the call is too early.
		 *
		 * @return bool
		 */
		public function is_enabled(): bool {
			if ( empty( self::$loggers ) ) {
				throw new Exception( 'The loggers are not initialized yet.' );
			}

			$enabled = LearnDash_Settings_Section::get_section_setting(
				'LearnDash_Settings_Section_Logs',
				$this->get_name()
			);

			return 'yes' === $enabled;
		}
	}
}