Completed
Push — mehul/issue/1427 ( ad1d03 )
by Ravinder
757:24 queued 740:01
created

Give_Logging::delete_logs()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 12
nop 3
dl 0
loc 31
rs 8.8017
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 24 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Class for logging events and errors
4
 *
5
 * @package     Give
6
 * @subpackage  Classes/Give_Logging
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Give_Logging Class
19
 *
20
 * A general use class for logging events and errors.
21
 *
22
 * @since 1.0
23
 */
24
class Give_Logging {
25
26
	/**
27
	 * Class Constructor
28
	 *
29
	 * Set up the Give Logging Class.
30
	 *
31
	 * @since  1.0
32
	 * @access public
33
	 */
34
	public function __construct() {
35
	}
36
37
38
	/**
39
	 * Setup hooks
40
	 *
41
	 * @since  1.7
42
	 * @access public
43
	 */
44
	public function __setup_hooks() {
45
		// Create the log post type
46
		add_action( 'init', array( $this, 'register_post_type' ), 1 );
47
48
		// Create types taxonomy and default types
49
		add_action( 'init', array( $this, 'register_taxonomy' ), 1 );
50
51
		add_action( 'save_post_give_payment', array( $this, 'background_process_delete_cache' ) );
52
		add_action( 'save_post_give_forms', array( $this, 'background_process_delete_cache' ) );
53
		add_action( 'save_post_give_log', array( $this, 'background_process_delete_cache' ) );
54
		add_action( 'give_delete_log_cache', array( $this, 'delete_cache' ) );
55
	}
56
57
	/**
58
	 * Log Post Type
59
	 *
60
	 * Registers the 'give_log' Post Type.
61
	 *
62
	 * @since  1.0
63
	 * @access public
64
	 *
65
	 * @return void
66
	 */
67
	public function register_post_type() {
68
		/* Logs post type */
69
		$log_args = array(
70
			'labels'              => array(
71
				'name' => esc_html__( 'Logs', 'give' ),
72
			),
73
			'public'              => false,
74
			'exclude_from_search' => true,
75
			'publicly_queryable'  => false,
76
			'show_ui'             => false,
77
			'query_var'           => false,
78
			'rewrite'             => false,
79
			'capability_type'     => 'post',
80
			'supports'            => array( 'title', 'editor' ),
81
			'can_export'          => true,
82
		);
83
84
		register_post_type( 'give_log', $log_args );
85
	}
86
87
	/**
88
	 * Log Type Taxonomy
89
	 *
90
	 * Registers the "Log Type" taxonomy.  Used to determine the type of log entry.
91
	 *
92
	 * @since  1.0
93
	 * @access public
94
	 *
95
	 * @return void
96
	 */
97
	public function register_taxonomy() {
98
		register_taxonomy( 'give_log_type', 'give_log', array(
99
			'public' => false,
100
		) );
101
	}
102
103
	/**
104
	 * Log Types
105
	 *
106
	 * Sets up the default log types and allows for new ones to be created.
107
	 *
108
	 * @since  1.0
109
	 * @access public
110
	 *
111
	 * @return array $terms
112
	 */
113
	public function log_types() {
114
		$terms = array(
115
			'sale',
116
			'gateway_error',
117
			'api_request',
118
		);
119
120
		return apply_filters( 'give_log_types', $terms );
121
	}
122
123
	/**
124
	 * Check if a log type is valid
125
	 *
126
	 * Checks to see if the specified type is in the registered list of types.
127
	 *
128
	 * @since  1.0
129
	 * @access public
130
	 *
131
	 * @param  string $type Log type.
132
	 *
133
	 * @return bool         Whether log type is valid.
134
	 */
135
	public function valid_type( $type ) {
136
		return in_array( $type, $this->log_types() );
137
	}
138
139
	/**
140
	 * Create new log entry
141
	 *
142
	 * This is just a simple and fast way to log something. Use $this->insert_log()
143
	 * if you need to store custom meta data.
144
	 *
145
	 * @since  1.0
146
	 * @access public
147
	 *
148
	 * @param  string $title   Log entry title. Default is empty.
149
	 * @param  string $message Log entry message. Default is empty.
150
	 * @param  int    $parent  Log entry parent. Default is 0.
151
	 * @param  string $type    Log type. Default is null.
152
	 *
153
	 * @return int             Log ID.
154
	 */
155
	public function add( $title = '', $message = '', $parent = 0, $type = null ) {
156
		$log_data = array(
157
			'post_title'   => $title,
158
			'post_content' => $message,
159
			'post_parent'  => $parent,
160
			'log_type'     => $type,
161
		);
162
163
		return $this->insert_log( $log_data );
164
	}
165
166
	/**
167
	 * Get Logs
168
	 *
169
	 * Retrieves log items for a particular object ID.
170
	 *
171
	 * @since  1.0
172
	 * @access public
173
	 *
174
	 * @param  int    $object_id Log object ID. Default is 0.
175
	 * @param  string $type      Log type. Default is null.
176
	 * @param  int    $paged     Page number Default is null.
177
	 *
178
	 * @return array             An array of the connected logs.
0 ignored issues
show
Documentation introduced by
Should the return type not be array|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
179
	 */
180
	public function get_logs( $object_id = 0, $type = null, $paged = null ) {
181
		return $this->get_connected_logs( array(
182
			'post_parent' => $object_id,
183
			'paged'       => $paged,
184
			'log_type'    => $type,
185
		) );
186
	}
187
188
	/**
189
	 * Stores a log entry
190
	 *
191
	 * @since  1.0
192
	 * @access public
193
	 *
194
	 * @param  array $log_data Log entry data.
195
	 * @param  array $log_meta Log entry meta.
196
	 *
197
	 * @return int             The ID of the newly created log item.
198
	 */
199
	public function insert_log( $log_data = array(), $log_meta = array() ) {
200
		$defaults = array(
201
			'post_type'    => 'give_log',
202
			'post_status'  => 'publish',
203
			'post_parent'  => 0,
204
			'post_content' => '',
205
			'log_type'     => false,
206
		);
207
208
		$args = wp_parse_args( $log_data, $defaults );
209
210
		/**
211
		 * Fires before inserting log entry.
212
		 *
213
		 * @since 1.0
214
		 *
215
		 * @param array $log_data Log entry data.
216
		 * @param array $log_meta Log entry meta.
217
		 */
218
		do_action( 'give_pre_insert_log', $log_data, $log_meta );
219
220
		// Store the log entry
221
		$log_id = wp_insert_post( $args );
222
223
		// Set the log type, if any
224
		if ( $log_data['log_type'] && $this->valid_type( $log_data['log_type'] ) ) {
225
			wp_set_object_terms( $log_id, $log_data['log_type'], 'give_log_type', false );
226
		}
227
228
		// Set log meta, if any
229
		if ( $log_id && ! empty( $log_meta ) ) {
230
			foreach ( (array) $log_meta as $key => $meta ) {
231
				give_update_meta( $log_id, '_give_log_' . sanitize_key( $key ), $meta );
232
			}
233
		}
234
235
		/**
236
		 * Fires after inserting log entry.
237
		 *
238
		 * @since 1.0
239
		 *
240
		 * @param int   $log_id   Log entry id.
241
		 * @param array $log_data Log entry data.
242
		 * @param array $log_meta Log entry meta.
243
		 */
244
		do_action( 'give_post_insert_log', $log_id, $log_data, $log_meta );
245
246
		return $log_id;
247
	}
248
249
	/**
250
	 * Update and existing log item
251
	 *
252
	 * @since  1.0
253
	 * @access public
254
	 *
255
	 * @param  array $log_data Log entry data.
256
	 * @param  array $log_meta Log entry meta.
257
	 *
258
	 * @return bool|null       True if successful, false otherwise.
259
	 */
260
	public function update_log( $log_data = array(), $log_meta = array() ) {
261
262
		/**
263
		 * Fires before updating log entry.
264
		 *
265
		 * @since 1.0
266
		 *
267
		 * @param array $log_data Log entry data.
268
		 * @param array $log_meta Log entry meta.
269
		 */
270
		do_action( 'give_pre_update_log', $log_data, $log_meta );
271
272
		$defaults = array(
273
			'post_type'   => 'give_log',
274
			'post_status' => 'publish',
275
			'post_parent' => 0,
276
		);
277
278
		$args = wp_parse_args( $log_data, $defaults );
279
280
		// Store the log entry
281
		$log_id = wp_update_post( $args );
282
283
		if ( $log_id && ! empty( $log_meta ) ) {
284
			foreach ( (array) $log_meta as $key => $meta ) {
285
				if ( ! empty( $meta ) ) {
286
					give_update_meta( $log_id, '_give_log_' . sanitize_key( $key ), $meta );
287
				}
288
			}
289
		}
290
291
		/**
292
		 * Fires after updating log entry.
293
		 *
294
		 * @since 1.0
295
		 *
296
		 * @param int   $log_id   Log entry id.
297
		 * @param array $log_data Log entry data.
298
		 * @param array $log_meta Log entry meta.
299
		 */
300
		do_action( 'give_post_update_log', $log_id, $log_data, $log_meta );
301
	}
302
303
	/**
304
	 * Retrieve all connected logs
305
	 *
306
	 * Used for retrieving logs related to particular items, such as a specific donation.
307
	 *
308
	 * @since  1.0
309
	 * @access public
310
	 *
311
	 * @param  array $args Query arguments.
312
	 *
313
	 * @return array|false Array if logs were found, false otherwise.
314
	 */
315
	public function get_connected_logs( $args = array() ) {
316
317
		$defaults = array(
318
			'post_type'      => 'give_log',
319
			'posts_per_page' => 20,
320
			'post_status'    => 'publish',
321
			'paged'          => get_query_var( 'paged' ),
322
			'log_type'       => false,
323
			'date_query'     => null
324
		);
325
326
		$query_args = wp_parse_args( $args, $defaults );
327
328
		if ( $query_args['log_type'] && $this->valid_type( $query_args['log_type'] ) ) {
329
			$query_args['tax_query'] = array(
330
				array(
331
					'taxonomy' => 'give_log_type',
332
					'field'    => 'slug',
333
					'terms'    => $query_args['log_type'],
334
				),
335
			);
336
		}
337
338
		// Retrieve logs based on specific timeframe
339
		if ( !empty ( $query_args['date_query'] ) && is_array( $query_args['date_query'] ) ) {
340
			if ( ! empty( $query_args['date_query']['start_date'] ) ) {
341
				$query_args['date_query']['after'] =  array(
342
					'year'  => date( 'Y', strtotime( $query_args['date_query']['start_date'] ) ),
343
					'month' => date( 'm', strtotime( $query_args['date_query']['start_date'] ) ),
344
					'day'   => date( 'd', strtotime( $query_args['date_query']['start_date'] ) )
345
				);
346
			}
347
348
			if ( ! empty( $query_args['date_query']['end_date'] ) ) {
349
				$query_args['date_query']['before'] =  array(
350
					'year'  => date( 'Y', strtotime( $query_args['date_query']['end_date'] ) ),
351
					'month' => date( 'm', strtotime( $query_args['date_query']['end_date'] ) ),
352
					'day'   => date( 'd', strtotime( $query_args['date_query']['end_date'] ) )
353
				);
354
			}
355
			$query_args['date_query']['inclusive'] = true;
356
		}
357
358
		$logs = get_posts( $query_args );
359
360
		if ( $logs ) {
361
			return $logs;
362
		}
363
364
		// No logs found
365
		return false;
366
	}
367
368
	/**
369
	 * Retrieve Log Count
370
	 *
371
	 * Retrieves number of log entries connected to particular object ID.
372
	 *
373
	 * @since  1.0
374
	 * @access public
375
	 *
376
	 * @param  int    $object_id  Log object ID. Default is 0.
377
	 * @param  string $type       Log type. Default is null.
378
	 * @param  array  $meta_query Log meta query. Default is null.
379
	 * @param  array  $date_query Log data query. Default is null.
380
	 *
381
	 * @return int                Log count.
382
	 */
383
	public function get_log_count( $object_id = 0, $type = null, $meta_query = null, $date_query = null ) {
384
385
		$query_args = array(
386
			'post_type'      => 'give_log',
387
			'posts_per_page' => - 1,
388
			'post_status'    => 'publish',
389
			'fields'         => 'ids',
390
		);
391
392
		if ( $object_id ) {
393
			$query_args['post_parent'] = $object_id;
394
		}
395
396
		if ( ! empty( $type ) && $this->valid_type( $type ) ) {
397
			$query_args['tax_query'] = array(
398
				array(
399
					'taxonomy' => 'give_log_type',
400
					'field'    => 'slug',
401
					'terms'    => $type,
402
				),
403
			);
404
		}
405
406
		if ( ! empty( $meta_query ) ) {
407
			$query_args['meta_query'] = $meta_query;
408
		}
409
410
		if ( ! empty( $date_query ) ) {
411
			$query_args['date_query'] = $date_query;
412
		}
413
414
		// Get cache key for current query.
415
		$cache_key = Give_Cache::get_key( 'get_log_count', $query_args );
416
417
		// check if cache already exist or not.
418
		if ( ! ( $logs_count = Give_Cache::get( $cache_key ) ) ) {
419
			$logs       = new WP_Query( $query_args );
420
			$logs_count = (int) $logs->post_count;
421
422
			// Cache results.
423
			Give_Cache::set( $cache_key, $logs_count );
424
		}
425
426
		return $logs_count;
427
	}
428
429
	/**
430
	 * Delete Logs
431
	 *
432
	 * Remove log entries connected to particular object ID.
433
	 *
434
	 * @since  1.0
435
	 * @access public
436
	 *
437
	 * @param  int    $object_id  Log object ID. Default is 0.
438
	 * @param  string $type       Log type. Default is null.
439
	 * @param  array  $meta_query Log meta query. Default is null.
440
	 *
441
	 * @return void
442
	 */
443
	public function delete_logs( $object_id = 0, $type = null, $meta_query = null ) {
444
		$query_args = array(
445
			'post_parent'    => $object_id,
446
			'post_type'      => 'give_log',
447
			'posts_per_page' => - 1,
448
			'post_status'    => 'publish',
449
			'fields'         => 'ids',
450
		);
451
452
		if ( ! empty( $type ) && $this->valid_type( $type ) ) {
453
			$query_args['tax_query'] = array(
454
				array(
455
					'taxonomy' => 'give_log_type',
456
					'field'    => 'slug',
457
					'terms'    => $type,
458
				),
459
			);
460
		}
461
462
		if ( ! empty( $meta_query ) ) {
463
			$query_args['meta_query'] = $meta_query;
464
		}
465
466
		$logs = get_posts( $query_args );
467
468
		if ( $logs ) {
469
			foreach ( $logs as $log ) {
470
				wp_delete_post( $log, true );
471
			}
472
		}
473
	}
474
475
	/**
476
	 * Setup cron to delete log cache in background.
477
	 *
478
	 * @since  1.7
479
	 * @access public
480
	 *
481
	 * @param int $post_id
482
	 */
483
	public function background_process_delete_cache( $post_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $post_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
484
		// Delete log cache immediately
485
		wp_schedule_single_event( time() - 5, 'give_delete_log_cache' );
486
	}
487
488
	/**
489
	 * Delete all logging cache when form, log or payment updates
490
	 *
491
	 * @since  1.7
492
	 * @access public
493
	 *
494
	 * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
495
	 */
496
	public function delete_cache() {
497
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
498
499
		// Add log related keys to delete.
500
		$cache_option_names = $wpdb->get_col(
501
			$wpdb->prepare(
502
				"SELECT *
503
						FROM {$wpdb->options}
504
						where option_name LIKE '%%%s%%'
505
						OR option_name LIKE '%%%s%%'",
506
				'give_cache_get_logs',
507
				'give_cache_get_log_count'
508
			),
509
			1 // option_name
510
		);
511
512
		// Bailout.
513
		if ( empty( $cache_option_names ) ) {
514
			return false;
515
		}
516
517
		Give_Cache::delete( $cache_option_names );
518
	}
519
}
520
521
// Initiate the logging system
522
$GLOBALS['give_logs'] = new Give_Logging();
523
$GLOBALS['give_logs']->__setup_hooks();
524
525
/**
526
 * Record a log entry
527
 *
528
 * A wrapper function for the Give_Logging class add() method.
529
 *
530
 * @since  1.0
531
 *
532
 * @param  string $title   Log title. Default is empty.
533
 * @param  string $message Log message. Default is empty.
534
 * @param  int    $parent  Parent log. Default is 0.
535
 * @param  string $type    Log type. Default is null.
536
 *
537
 * @return int             ID of the new log entry.
538
 */
539
function give_record_log( $title = '', $message = '', $parent = 0, $type = null ) {
540
	/* @var Give_Logging $give_logs */
541
	global $give_logs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
542
	$log = $give_logs->add( $title, $message, $parent, $type );
543
544
	return $log;
545
}
546