Test Failed
Pull Request — master (#238)
by Jonathan
02:43
created

Object_Sync_Sf_Logging   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 391
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
wmc 35
lcom 2
cbo 1
dl 0
loc 391
rs 9.6
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 2
A init() 0 19 3
A set_log_visibility() 0 23 1
A add_prune_interval() 0 16 1
A get_schedule_frequency() 0 24 4
A set_log_types() 0 4 1
A set_prune_option() 0 7 2
A set_prune_age() 0 8 2
A set_prune_args() 0 4 1
B setup() 0 22 8
A add() 0 12 1
A get_logs() 0 9 1
A get_connected_logs() 0 35 4
A get_log_count() 0 30 4
1
<?php
2
/**
3
 * Class file for the Object_Sync_Sf_Logging class. Extend the WP_Logging class for the purposes of Object Sync for Salesforce.
4
 *
5
 * @file
6
 */
7
8
if ( ! class_exists( 'Object_Sync_Salesforce' ) ) {
9
	die();
10
}
11
12
/**
13
 * Log events based on plugin settings
14
 */
15
class Object_Sync_Sf_Logging extends WP_Logging {
16
17
	protected $wpdb;
18
	protected $version;
19
	protected $slug;
20
	protected $option_prefix;
21
22
	public $enabled;
23
	public $statuses_to_log;
24
25
26
	/**
27
	 * Constructor which sets content type and pruning for logs
28
	 *
29
	 * @param object $wpdb An instance of the wpdb class.
30
	 * @param string $version The version of this plugin.
31
	 * @param string $slug The plugin slug
32
	 * @param string $option_prefix The plugin's option prefix
33
	 * @throws \Exception
34
	 */
35
	public function __construct( $wpdb, $version, $slug = '', $option_prefix = '' ) {
36
		$this->wpdb          = $wpdb;
37
		$this->version       = $version;
38
		$this->slug          = $slug;
39
		$this->option_prefix = isset( $option_prefix ) ? $option_prefix : 'object_sync_for_salesforce_';
40
41
		$this->enabled         = get_option( $this->option_prefix . 'enable_logging', false );
42
		$this->statuses_to_log = get_option( $this->option_prefix . 'statuses_to_log', array() );
43
44
		$this->schedule_name = 'wp_logging_prune_routine';
45
46
		$this->init();
47
48
	}
49
50
	/**
51
	 * Start. This creates a schedule for pruning logs, and also the custom content type
52
	 *
53
	 * @throws \Exception
54
	 */
55
	private function init() {
56
		if ( '1' === $this->enabled ) {
57
			add_filter( 'cron_schedules', array( $this, 'add_prune_interval' ) );
0 ignored issues
show
introduced by
Detected changing of cron_schedules, but could not detect the interval value.
Loading history...
58
			add_filter( 'wp_log_types', array( $this, 'set_log_types' ), 10, 1 );
59
			add_filter( 'wp_logging_should_we_prune', array( $this, 'set_prune_option' ), 10, 1 );
60
			add_filter( 'wp_logging_prune_when', array( $this, 'set_prune_age' ), 10, 1 );
61
			add_filter( 'wp_logging_prune_query_args', array( $this, 'set_prune_args' ), 10, 1 );
62
			add_filter( 'wp_logging_post_type_args', array( $this, 'set_log_visibility' ), 10, 1 );
63
64
			$schedule_unit   = get_option( $this->option_prefix . 'logs_how_often_unit', '' );
65
			$schedule_number = get_option( $this->option_prefix . 'logs_how_often_number', '' );
66
			$frequency       = $this->get_schedule_frequency( $schedule_unit, $schedule_number );
67
			$key             = $frequency['key'];
68
69
			if ( ! wp_next_scheduled( $this->schedule_name ) ) {
70
				wp_schedule_event( time(), $key, $this->schedule_name );
71
			}
72
		}
73
	}
74
75
	public function set_log_visibility( $log_args ) {
76
		// set public to true overrides the WP_DEBUG setting that is the default on the class
77
		// capabilities makes it so (currently) only admin users can see the log posts in their admin view
78
		// note: a public value of true is required to show Logs as a nav menu item on the admin.
79
		// however, if we don't set exclude_from_search to true and publicly_queryable to false, logs *can* appear in search results
80
		$log_args['public']              = true;
81
		$log_args['publicly_queryable']  = false;
82
		$log_args['exclude_from_search'] = true;
83
		$log_args['capabilities']        = array(
84
			'edit_post'          => 'configure_salesforce',
85
			'read_post'          => 'configure_salesforce',
86
			'delete_post'        => 'configure_salesforce',
87
			'edit_posts'         => 'configure_salesforce',
88
			'edit_others_posts'  => 'configure_salesforce',
89
			'delete_posts'       => 'configure_salesforce',
90
			'publish_posts'      => 'configure_salesforce',
91
			'read_private_posts' => 'configure_salesforce',
92
		);
93
94
		$log_args = apply_filters( $this->option_prefix . 'logging_post_type_args', $log_args );
95
96
		return $log_args;
97
	}
98
99
	/**
100
	 * Add interval to wp schedules based on admin settings
101
	 *
102
	 * @param array $schedules An array of scheduled cron items.
103
	 * @return array $frequency
104
	 */
105
	public function add_prune_interval( $schedules ) {
106
107
		$schedule_unit   = get_option( $this->option_prefix . 'logs_how_often_unit', '' );
108
		$schedule_number = get_option( $this->option_prefix . 'logs_how_often_number', '' );
109
		$frequency       = $this->get_schedule_frequency( $schedule_unit, $schedule_number );
110
		$key             = $frequency['key'];
111
		$seconds         = $frequency['seconds'];
112
113
		$schedules[ $key ] = array(
114
			'interval' => $seconds * $schedule_number,
115
			'display'  => 'Every ' . $schedule_number . ' ' . $schedule_unit,
116
		);
117
118
		return $schedules;
119
120
	}
121
122
	/**
123
	 * Convert the schedule frequency from the admin settings into an array
124
	 * interval must be in seconds for the class to use it
125
	 *
126
	 * @param string $unit A unit of time.
127
	 * @param number $number The number of those units.
128
	 * @return array
129
	 */
130
	public function get_schedule_frequency( $unit, $number ) {
131
132
		switch ( $unit ) {
133
			case 'minutes':
134
				$seconds = 60;
135
				break;
136
			case 'hours':
137
				$seconds = 3600;
138
				break;
139
			case 'days':
140
				$seconds = 86400;
141
				break;
142
			default:
143
				$seconds = 0;
144
		}
145
146
		$key = $unit . '_' . $number;
147
148
		return array(
149
			'key'     => $key,
150
			'seconds' => $seconds,
151
		);
152
153
	}
154
155
	/**
156
	 * Set terms for Salesforce logs
157
	 *
158
	 * @param array $terms An array of string log types in the WP_Logging class.
159
	 * @return array $terms
160
	 */
161
	public function set_log_types( $terms ) {
162
		$terms[] = 'salesforce';
163
		return $terms;
164
	}
165
166
	/**
167
	 * Should logs be pruned at all?
168
	 *
169
	 * @param string $should_we_prune Whether to prune old log items.
170
	 * @return string $should_we_prune Whether to prune old log items.
171
	 */
172
	public function set_prune_option( $should_we_prune ) {
173
		$should_we_prune = get_option( $this->option_prefix . 'prune_logs', $should_we_prune );
174
		if ( '1' === $should_we_prune ) {
175
			$should_we_prune = true;
176
		}
177
		return $should_we_prune;
178
	}
179
180
	/**
181
	 * Set how often to prune the Salesforce logs
182
	 *
183
	 * @param string $how_old How old the oldest non-pruned log items should be allowed to be.
184
	 * @return string $how_old
185
	 */
186
	public function set_prune_age( $how_old ) {
187
		$value = get_option( $this->option_prefix . 'logs_how_old', '' ) . ' ago';
188
		if ( '' !== $value ) {
189
			return $value;
190
		} else {
191
			return $how_old;
192
		}
193
	}
194
195
	/**
196
	 * Set arguments for only getting the Salesforce logs
197
	 *
198
	 * @param array $args Argument array for get_posts determining what posts are eligible for pruning.
199
	 * @return array $args
200
	 */
201
	public function set_prune_args( $args ) {
202
		$args['wp_log_type'] = 'salesforce';
203
		return $args;
204
	}
205
206
	/**
207
	 * Setup new log entry
208
	 *
209
	 * Check and see if we should log anything, and if so, send it to add()
210
	 *
211
	 * @access      public
212
	 * @since       1.0
213
	 *
214
	 * @param       string|array $title_or_params A log post title, or the full array of parameters
215
	 * @param       string $message The log message.
216
	 * @param       string|0 $trigger The type of log triggered. Usually one of: debug, notice, warning, error.
0 ignored issues
show
Documentation introduced by
The doc-type string|0 could not be parsed: Unknown type name "0" at position 7. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
217
	 * @param       int $parent The parent WordPress object.
218
	 * @param       string $status The log status.
219
	 *
220
	 * @uses        self::add()
221
	 * @see         Object_Sync_Sf_Mapping::__construct()    the location of the bitmasks that define the logging triggers.
222
	 *
223
	 * @return      void
224
	 */
225
	public function setup( $title_or_params, $message = '', $trigger = 0, $parent = 0, $status = '' ) {
226
227
		if ( is_array( $title_or_params ) ) {
228
			$title   = $title_or_params['title'];
229
			$message = $title_or_params['message'];
230
			$trigger = $title_or_params['trigger'];
231
			$parent  = $title_or_params['parent'];
232
			$status  = $title_or_params['status'];
233
		} else {
234
			$title = $title_or_params;
235
		}
236
237
		if ( '1' === $this->enabled && in_array( $status, maybe_unserialize( $this->statuses_to_log ), true ) ) {
238
			$triggers_to_log = get_option( $this->option_prefix . 'triggers_to_log', array() );
239
			// if we force strict on this in_array, it fails because the mapping triggers are bit operators, as indicated in Object_Sync_Sf_Mapping class's method __construct()
240
			if ( in_array( $trigger, maybe_unserialize( $triggers_to_log ) ) || 0 === $trigger ) {
241
				$this->add( $title, $message, $parent );
242
			} elseif ( is_array( $trigger ) && array_intersect( $trigger, maybe_unserialize( $triggers_to_log ) ) ) {
243
				$this->add( $title, $message, $parent );
244
			}
245
		}
246
	}
247
248
	/**
249
	 * Create new log entry
250
	 *
251
	 * This is just a simple and fast way to log something. Use self::insert_log()
252
	 * if you need to store custom meta data
253
	 *
254
	 * @access      public
255
	 * @since       1.0
256
	 *
257
	 * @param       string $title A log post title.
258
	 *
259
	 * @uses        self::insert_log()
260
	 * @param       string $message The log message.
261
	 * @param       int $parent The parent WordPress object.
262
	 * @param       string $type The type of log message; defaults to 'salesforce'.
263
	 *
264
	 * @return      int The ID of the new log entry
265
	 */
266
	public static function add( $title = '', $message = '', $parent = 0, $type = 'salesforce' ) {
267
268
		$log_data = array(
269
			'post_title'   => esc_html( $title ),
270
			'post_content' => wp_kses_post( $message ),
271
			'post_parent'  => absint( $parent ),
272
			'log_type'     => esc_attr( $type ),
273
		);
274
275
		return self::insert_log( $log_data );
276
277
	}
278
279
280
	/**
281
	 * Easily retrieves log items for a particular object ID
282
	 *
283
	 * @access      private
284
	 * @since       1.0
285
	 *
286
	 * @param       int $object_id A WordPress object ID.
287
	 * @param       string $type The type of log item; defaults to 'salesforce' because that's the type of logs we create.
288
	 * @param       int $paged Which page of results do we want?
289
	 *
290
	 * @uses        self::get_connected_logs()
291
	 *
292
	 * @return      array
293
	 */
294
	public static function get_logs( $object_id = 0, $type = 'salesforce', $paged = null ) {
295
		return self::get_connected_logs(
296
			array(
297
				'post_parent' => (int) $object_id,
298
				'paged'       => (int) $paged,
299
				'log_type'    => (string) $type,
300
			)
301
		);
302
	}
303
304
305
	/**
306
	 * Retrieve all connected logs
307
	 *
308
	 * Used for retrieving logs related to particular items, such as a specific purchase.
309
	 *
310
	 * @access  private
311
	 * @since   1.0
312
	 *
313
	 * @param   Array $args An array of arguments for get_posts().
314
	 *
315
	 * @uses    wp_parse_args()
316
	 * @uses    get_posts()
317
	 * @uses    get_query_var()
318
	 * @uses    self::valid_type()
319
	 *
320
	 * @return  array / false
321
	 */
322
	public static function get_connected_logs( $args = array() ) {
323
324
		$defaults = array(
325
			'post_parent'    => 0,
326
			'post_type'      => 'wp_log',
327
			'posts_per_page' => 10,
328
			'post_status'    => 'publish',
329
			'paged'          => get_query_var( 'paged' ),
330
			'log_type'       => 'salesforce',
331
		);
332
333
		$query_args = wp_parse_args( $args, $defaults );
334
335
		if ( $query_args['log_type'] && self::valid_type( $query_args['log_type'] ) ) {
336
337
			$query_args['tax_query'] = array(
0 ignored issues
show
introduced by
Detected usage of tax_query, possible slow query.
Loading history...
338
				array(
339
					'taxonomy' => 'wp_log_type',
340
					'field'    => 'slug',
341
					'terms'    => $query_args['log_type'],
342
				),
343
			);
344
345
		}
346
347
		$logs = get_posts( $query_args );
348
349
		if ( $logs ) {
350
			return $logs;
351
		}
352
353
		// no logs found.
354
		return false;
355
356
	}
357
358
359
	/**
360
	 * Retrieves number of log entries connected to particular object ID
361
	 *
362
	 * @access  private
363
	 * @since   1.0
364
	 *
365
	 * @param       int $object_id A WordPress object ID.
366
	 * @param       string $type The type of log item; defaults to 'salesforce' because that's the type of logs we create.
367
	 * @param       Array $meta_query A WordPress meta query, parseable by WP_Meta_Query.
368
	 *
369
	 * @uses    WP_Query()
370
	 * @uses    self::valid_type()
371
	 *
372
	 * @return  int
373
	 */
374
	public static function get_log_count( $object_id = 0, $type = 'salesforce', $meta_query = null ) {
375
376
		$query_args = array(
377
			'post_parent'    => (int) $object_id,
378
			'post_type'      => 'wp_log',
379
			'posts_per_page' => 100,
0 ignored issues
show
introduced by
Detected high pagination limit, posts_per_page is set to 100
Loading history...
380
			'post_status'    => 'publish',
381
		);
382
383
		if ( ! empty( $type ) && self::valid_type( $type ) ) {
384
385
			$query_args['tax_query'] = array(
0 ignored issues
show
introduced by
Detected usage of tax_query, possible slow query.
Loading history...
386
				array(
387
					'taxonomy' => 'wp_log_type',
388
					'field'    => 'slug',
389
					'terms'    => sanitize_key( $type ),
390
				),
391
			);
392
393
		}
394
395
		if ( ! empty( $meta_query ) ) {
396
			$query_args['meta_query'] = $meta_query;
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
397
		}
398
399
		$logs = new WP_Query( $query_args );
400
401
		return (int) $logs->post_count;
402
403
	}
404
405
}
406