Completed
Push — master ( c38d6c...15bc19 )
by Zack
14:07 queued 10:41
created

GravityView_Cache   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 548
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 1

Test Coverage

Coverage 17.95%

Importance

Changes 0
Metric Value
dl 0
loc 548
ccs 28
cts 156
cp 0.1795
rs 8.3673
c 0
b 0
f 0
wmc 45
lcom 3
cbo 1

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 2
B add_hooks() 0 31 2
A entry_status_changed() 0 17 2
A entry_updated() 0 6 1
A entry_created() 0 6 1
A entry_added() 0 9 2
A get_cache_key_prefix() 0 16 2
A set_key() 0 15 2
A get_key() 0 3 1
A blacklist_add() 0 23 2
A blacklist_remove() 0 14 1
B in_blacklist() 0 26 5
B get() 0 33 5
A set() 0 22 2
B delete() 0 36 5
A schedule_transient_cleanup() 0 16 3
B delete_expired_transients() 0 42 1
B use_cache() 0 35 6

How to fix   Complexity   

Complex Class

Complex classes like GravityView_Cache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GravityView_Cache, and based on these observations, apply Extract Interface, too.

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 6 and the first side effect is on line 555.

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
/**
4
 * Handle caching using transients for GravityView
5
 */
6
class GravityView_Cache {
7
8
	const BLACKLIST_OPTION_NAME = 'gravityview_cache_blacklist';
9
10
	/**
11
	 * Form ID, or array of Form IDs
12
	 *
13
	 * @var mixed
14
	 */
15
	protected $form_ids;
16
17
	/**
18
	 * Extra request parameters used to generate the query. This is used to generate the unique transient key.
19
	 *
20
	 * @var array
21
	 */
22
	protected $args;
23
24
	/**
25
	 * The transient key used to store the cached item. 45 characters long.
26
	 *
27
	 * @var string
28
	 */
29
	private $key = '';
30
31
	/**
32
	 * @since 1.13.1
33
	 * @var array Columns in the database for leads
34
	 */
35
	private $lead_db_columns = array( 'id', 'form_id', 'post_id', 'date_created', 'is_starred', 'is_read', 'ip', 'source_url', 'user_agent', 'currency', 'payment_status', 'payment_date', 'payment_amount', 'transaction_id', 'is_fulfilled', 'created_by', 'transaction_type', 'status' );
36
37
	/**
38
	 *
39
	 * @param array|int $form_ids Form ID or array of form IDs used in a request
40
	 * @param array $args Extra request parameters used to generate the query. This is used to generate the unique transient key.
41
	 */
42
	function __construct( $form_ids = NULL, $args = array() ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
43
44
		$this->add_hooks();
45
46
		if ( ! is_null( $form_ids ) ) {
47
48
			$this->form_ids = $form_ids;
49
50
			$this->args = $args;
51
52
			$this->set_key();
53
		}
54
	}
55
56
	/**
57
	 * Add actions for clearing out caches when entries are updated.
58
	 */
59
	function add_hooks() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
60
61
		// Schedule cleanup of expired transients
62
		add_action( 'wp', array( $this, 'schedule_transient_cleanup' ) );
63
64
		// Hook in to the scheduled cleanup, if scheduled
65
		add_action( 'gravityview-expired-transients', array( $this, 'delete_expired_transients' ) );
66
67
		// Trigger this when you need to prevent any results from being cached with forms that have been modified
68
		add_action( 'gravityview_clear_form_cache', array( $this, 'blacklist_add' ) );
69
70
		/**
71
		 * @since 1.14
72
		 */
73
		add_action( 'gravityview_clear_entry_cache', array( $this, 'entry_status_changed' ) );
74
75
		add_action( 'gform_after_update_entry', array( $this, 'entry_updated' ), 10, 2 );
76
77
		add_action( 'gform_entry_created', array( $this, 'entry_created' ), 10, 2 );
78
79
		add_action( 'gform_post_add_entry', array( $this, 'entry_added' ), 10, 2 );
80
81
		/**
82
		 * @see RGFormsModel::update_lead_property() Trigger when any entry property changes
83
		 */
84
		foreach( $this->lead_db_columns as $column ) {
85
			add_action( 'gform_update_' . $column, array( $this, 'entry_status_changed' ), 10, 3 );
86
		}
87
88
		add_action( 'gform_delete_lead', array( $this, 'entry_status_changed' ), 10 );
89
	}
90
91
	/**
92
	 * Force refreshing a cache when an entry is deleted.
93
	 *
94
	 * The `gform_delete_lead` action is called before the lead is deleted; we fetch the entry to find out the form ID so it can be added to the blacklist.
95
	 *
96
	 * @since  1.5.1
97
	 *
98
	 * @param  int $lead_id Entry ID
99
	 * @param  string $property_value Previous value of the lead status passed by gform_update_status hook
100
	 * @param  string $previous_value Previous value of the lead status passed by gform_update_status hook
101
	 *
102
	 * @return void
103
	 */
104
	public function entry_status_changed( $lead_id, $property_value = '', $previous_value = '' ) {
105
106
		/** @var array $entry */
107
		$entry = GFAPI::get_entry( $lead_id );
108
109
		if ( is_wp_error( $entry ) ) {
110
111
			/** @var WP_Error $entry */
112
			do_action( 'gravityview_log_error', __METHOD__ . ' Could not retrieve entry ' . $lead_id . ' to delete it: ' . $entry->get_error_message() );
113
114
			return;
115
		}
116
117
		do_action( 'gravityview_log_debug', __METHOD__ . ' adding form ' . $entry['form_id'] . ' to blacklist because entry #' . $lead_id . ' was deleted', array( 'value' => $property_value, 'previous' => $previous_value ) );
118
119
		$this->blacklist_add( $entry['form_id'] );
120
	}
121
122
	/**
123
	 * When an entry is updated, add the entry's form to the cache blacklist
124
	 *
125
	 * @param  array $form GF form array
126
	 * @param  int $lead_id Entry ID
127
	 *
128
	 * @return void
129
	 */
130 3
	public function entry_updated( $form, $lead_id ) {
131
132 3
		do_action( 'gravityview_log_debug', 'GravityView_Cache[entry_updated] adding form ' . $form['id'] . ' to blacklist because entry #' . $lead_id . ' was updated' );
133
134 3
		$this->blacklist_add( $form['id'] );
135 3
	}
136
137
	/**
138
	 * When an entry is created, add the entry's form to the cache blacklist
139
	 *
140
	 * We don't want old caches; when an entry is added, we want to clear the cache.
141
	 *
142
	 * @param  array $entry GF entry array
143
	 * @param  array $form GF form array
144
	 *
145
	 * @return void
146
	 */
147
	public function entry_created( $entry, $form ) {
148
149
		do_action( 'gravityview_log_debug', 'GravityView_Cache[entry_created] adding form ' . $form['id'] . ' to blacklist because entry #' . $entry['id'] . ' was created' );
150
151
		$this->blacklist_add( $form['id'] );
152
	}
153
154
	/**
155
	 * Clear the cache when entries are added via GFAPI::add_entry().
156
	 *
157
	 * @param array $entry The GF Entry array
158
	 * @param array $form  The GF Form array
159
	 *
160
	 * @return void
161
	 */
162 3
	public function entry_added( $entry, $form ) {
163 3
		if ( is_wp_error( $entry ) ) {
164
			return;
165
		}
166
167 3
		do_action( 'gravityview_log_debug', 'GravityView_Cache[entry_added] adding form ' . $form['id'] . ' to blacklist because entry #' . $entry['id'] . ' was added' );
168
169 3
		$this->blacklist_add( $form['id'] );
170 3
	}
171
172
	/**
173
	 * Calculate the prefix based on the Form IDs
174
	 *
175
	 * @param  int|array $form_ids Form IDs to generate prefix for
176
	 *
177
	 * @return string           Prefix for the cache string used in set_key()
178
	 */
179
	protected function get_cache_key_prefix( $form_ids = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
180
181
		if ( is_null( $form_ids ) ) {
182
			$form_ids = $this->form_ids;
183
		}
184
185
		// Normally just one form, but supports multiple forms
186
		//
187
		// Array of IDs 12, 5, 14 would result in `f-12f-5f-14`
188
		$forms = 'f:' . implode( '&f:', (array) $form_ids );
189
190
		// Prefix for transient keys
191
		// Now the prefix would be: `gv-cache-f-12f-5f-14`
192
		return 'gv-cache-' . $forms . '-';
193
194
	}
195
196
	/**
197
	 * Set the transient key based on the form IDs and the arguments passed to the class
198
	 */
199
	protected function set_key() {
200
201
		// Don't set key if no forms have been set.
202
		if ( empty( $this->form_ids ) ) {
203
			return;
204
		}
205
206
		$key = $this->get_cache_key_prefix() . sha1( serialize( $this->args ) );
207
208
		// The transient name column can handle up to 64 characters.
209
		// The `_transient_timeout_` prefix that is prepended to the string is 11 characters.
210
		// 64 - 19 = 45
211
		// We make sure the key isn't too long or else WP doesn't store data.
212
		$this->key = substr( $key, 0, 45 );
213
	}
214
215
	/**
216
	 * Allow public access to get transient key
217
	 *
218
	 * @return string Transient key
219
	 */
220
	public function get_key() {
221
		return $this->key;
222
	}
223
224
	/**
225
	 * Add form IDs to a "blacklist" to force the cache to be refreshed
226
	 *
227
	 *
228
	 *
229
	 * @param  int|array $form_ids Form IDs to force to be updated
230
	 *
231
	 * @return boolean           False if value was not updated and true if value was updated.
232
	 */
233 3
	public function blacklist_add( $form_ids ) {
234
235 3
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
236
237 3
		$form_ids = is_array( $form_ids ) ? $form_ids : array( $form_ids );
238
239 3
		do_action( 'gravityview_log_debug', 'GravityView_Cache[blacklist_add] Adding form IDs to cache blacklist', array(
240 3
			'$form_ids'  => $form_ids,
241 3
			'$blacklist' => $blacklist
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
242
		) );
243
244
		// Add the passed form IDs
245 3
		$blacklist = array_merge( (array) $blacklist, $form_ids );
246
247
		// Don't duplicate
248 3
		$blacklist = array_unique( $blacklist );
249
250
		// Remove empty items from blacklist
251 3
		$blacklist = array_filter( $blacklist );
252
253 3
		return update_option( self::BLACKLIST_OPTION_NAME, $blacklist );
254
255
	}
256
257
	/**
258
	 * Remove Form IDs from blacklist
259
	 *
260
	 * @param  int|array $form_ids Form IDs to add
261
	 *
262
	 * @return boolean           Whether the removal was successful
263
	 */
264
	public function blacklist_remove( $form_ids ) {
265
266
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
267
268
		$updated_list = array_diff( $blacklist, (array) $form_ids );
269
270
		do_action( 'gravityview_log_debug', 'GravityView_Cache[blacklist_remove] Removing form IDs from cache blacklist', array(
271
			'$form_ids'     => $form_ids,
272
			'$blacklist'    => $blacklist,
273
			'$updated_list' => $updated_list
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
274
		) );
275
276
		return update_option( self::BLACKLIST_OPTION_NAME, $updated_list );
277
	}
278
279
280
	/**
281
	 * Is a form ID in the cache blacklist
282
	 *
283
	 * @param  int|array $form_ids Form IDs to check if in blacklist
284
	 *
285
	 * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(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...
286
	 */
287 1
	function in_blacklist( $form_ids = NULL ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
288
289 1
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
290
291
		// Use object var if exists
292 1
		$form_ids = is_null( $form_ids ) ? $this->form_ids : $form_ids;
293
294 1
		if ( empty( $form_ids ) ) {
295
296
			do_action( 'gravityview_log_debug', 'GravityView_Cache[in_blacklist] Did not add form to blacklist; empty form ID', $form_ids );
297
298
			return false;
299
		}
300
301 1
		foreach ( (array) $form_ids as $form_id ) {
302
303 1
			if ( in_array( $form_id, $blacklist ) ) {
304
305 1
				do_action( 'gravityview_log_debug', 'GravityView_Cache[in_blacklist] Form #' . esc_attr( $form_id ) . ' is in the cache blacklist' );
306
307 1
				return true;
308
			}
309
		}
310
311 1
		return false;
312
	}
313
314
315
	/**
316
	 * Get transient result
317
	 *
318
	 * @param  string $key Transient key to fetch
319
	 *
320
	 * @return mixed      False: Not using cache or cache was a WP_Error object; NULL: no results found; Mixed: cache value
321
	 */
322
	public function get( $key = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
323
324
		$key = is_null( $key ) ? $this->key : $key;
325
326
		if ( ! $this->use_cache() ) {
327
328
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Not using cached results because of GravityView_Cache->use_cache() results' );
329
330
			return false;
331
		}
332
333
		do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Fetching request with transient key ' . $key );
334
335
		$result = get_transient( $key );
336
337
		if ( is_wp_error( $result ) ) {
338
339
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Fetching request resulted in error:', $result );
340
341
			return false;
342
343
		} elseif ( $result ) {
344
345
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Cached results found for  transient key ' . $key );
346
347
			return $result;
348
		}
349
350
		do_action( 'gravityview_log_debug', 'GravityView_Cache[get] No cached results found for  transient key ' . $key );
351
352
		return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
353
354
	}
355
356
	/**
357
	 * Cache content as a transient.
358
	 *
359
	 * Cache time defaults to 1 week
360
	 *
361
	 * @param [type] $content     [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(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...
362
	 * @param [type] $filter_name Name used to modify the cache time. Will be set to `gravityview_cache_time_{$filter_name}`.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(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...
363
	 */
364
	public function set( $content, $filter_name = '' ) {
365
366
		// Don't cache empty results
367
		if ( ! empty( $content ) ) {
368
369
			/**
370
			 * @filter `gravityview_cache_time_{$filter_name}` Modify the cache time for a type of cache
371
			 * @param int $time_in_seconds Default: `DAY_IN_SECONDS`
372
			 */
373
			$cache_time = (int) apply_filters( 'gravityview_cache_time_' . $filter_name, DAY_IN_SECONDS );
374
375
			do_action( 'gravityview_log_debug', 'GravityView_Cache[set] Setting cache with transient key ' . $this->key . ' for ' . $cache_time . ' seconds' );
376
377
			return set_transient( $this->key, $content, $cache_time );
378
379
		}
380
381
		do_action( 'gravityview_log_debug', 'GravityView_Cache[set] Cache not set; content is empty' );
382
383
		return false;
384
385
	}
386
387
	/**
388
	 * Delete cached transients based on form IDs
389
	 *
390
	 * @todo Use REGEX to match forms when array of form IDs is passed, instead of using a simple LIKE
391
	 * @todo  Rate limit deleting to prevent abuse
392
	 *
393
	 * @param  int|array $form_ids Form IDs to delete
394
	 *
395
	 * @return [type]           [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(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...
396
	 */
397
	public function delete( $form_ids = NULL ) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
398
		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...
399
400
		// Use object var if exists
401
		$form_ids = is_null( $form_ids ) ? $this->form_ids : $form_ids;
402
403
		if ( empty( $form_ids ) ) {
404
			do_action( 'gravityview_log_debug', 'GravityView_Cache[delete] Did not delete cache; empty form IDs' );
405
406
			return;
407
		}
408
409
		foreach ( (array) $form_ids as $form_id ) {
410
411
			$key = $this->get_cache_key_prefix( $form_id );
412
413
			// WordPress 4.0+
414
			if ( is_callable( array( $wpdb, 'esc_like' ) ) ) {
415
				$key = $wpdb->esc_like( $key );
416
			} else {
417
				$key = like_escape( $key );
418
			}
419
420
			$key = "%" . $key . "%";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal % does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
421
422
			$sql = $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE `option_name` LIKE %s", $key );
423
424
			$result = $wpdb->query( $sql );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
425
426
			do_action( 'gravityview_log_debug', 'GravityView_Cache[delete] Deleting cache for form #' . $form_id, array(
427
				$sql,
428
				sprintf( 'Deleted results: %d', $result )
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
429
			) );
430
		}
431
432
	}
433
434
	/**
435
	 * Schedule expired transient cleanup twice a day.
436
	 *
437
	 * Can be overruled by the `gravityview_cleanup_transients` filter (returns boolean)
438
	 *
439
	 * @return void
440
	 */
441
	public function schedule_transient_cleanup() {
442
443
		/**
444
		 * @filter `gravityview_cleanup_transients` Override GravityView cleanup of transients by setting this to false
445
		 * @param boolean $cleanup Whether to run the GravityView auto-cleanup of transients. Default: `true`
446
		 */
447
		$cleanup = apply_filters( 'gravityview_cleanup_transients', true );
448
449
		if ( ! $cleanup ) {
450
			return;
451
		}
452
453
		if ( ! wp_next_scheduled( 'gravityview-expired-transients' ) ) {
454
			wp_schedule_event( time(), 'daily', 'gravityview-expired-transients' );
455
		}
456
	}
457
458
	/**
459
	 * Delete expired transients.
460
	 *
461
	 * The code is copied from the Delete Expired Transients, with slight modifications to track # of results and to get the blog ID dynamically
462
	 *
463
	 * @see https://wordpress.org/plugins/delete-expired-transients/ Plugin where the code was taken from
464
	 * @see  DelxtransCleaners::clearBlogExpired()
465
	 * @return void
466
	 */
467
	public function delete_expired_transients() {
468
		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...
469
470
		// Added this line, which isn't in the plugin
471
		$blog_id = get_current_blog_id();
472
473
		$num_results = 0;
474
475
		// get current PHP time, offset by a minute to avoid clashes with other tasks
476
		$threshold = time() - 60;
477
478
		// get table name for options on specified blog
479
		$table = $wpdb->get_blog_prefix( $blog_id ) . 'options';
480
481
		// delete expired transients, using the paired timeout record to find them
482
		$sql = "
483
			delete from t1, t2
484
			using $table t1
485
			join $table t2 on t2.option_name = replace(t1.option_name, '_timeout', '')
486
			where (t1.option_name like '\_transient\_timeout\_%' or t1.option_name like '\_site\_transient\_timeout\_%')
487
			and t1.option_value < '$threshold'
488
		";
489
490
		$num_results = $wpdb->query( $sql );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
491
492
		// delete orphaned transient expirations
493
		// also delete NextGEN Gallery 2.x display cache timeout aliases
494
		$sql = "
495
			delete from $table
496
			where (
497
				   option_name like '\_transient\_timeout\_%'
498
				or option_name like '\_site\_transient\_timeout\_%'
499
				or option_name like 'displayed\_galleries\_%'
500
				or option_name like 'displayed\_gallery\_rendering\_%'
501
			)
502
			and option_value < '$threshold'
503
		";
504
505
		$num_results += $wpdb->query( $sql );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
506
507
		do_action( 'gravityview_log_debug', 'GravityView_Cache[delete_expired_transients] Deleted ' . $num_results . ' expired transient records from the database' );
508
	}
509
510
	/**
511
	 * Check whether to use cached results, if available
512
	 *
513
	 * If the user can edit posts, they are able to override whether to cache results by adding `cache` or `nocache` to the URL requested.
514
	 *
515
	 * @return boolean True: use cache; False: don't use cache
516
	 */
517
	public function use_cache() {
518
519
		$use_cache = true;
520
521
		if ( GVCommon::has_cap( 'edit_gravityviews' ) ) {
522
523
			if ( isset( $_GET['cache'] ) || isset( $_GET['nocache'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
524
525
				do_action( 'gravityview_log_debug', 'GravityView_Cache[use_cache] Not using cache: ?cache or ?nocache is in the URL' );
526
527
				$use_cache = false;
528
			}
529
530
		}
531
532
		// Has the form been flagged as having changed items in it?
533
		if ( $this->in_blacklist() || ! $use_cache ) {
534
535
			// Delete caches for all items with form IDs XYZ
536
			$this->delete( $this->form_ids );
537
538
			// Remove the form from
539
			$this->blacklist_remove( $this->form_ids );
540
541
		}
542
543
		/**
544
		 * @filter `gravityview_use_cache` Modify whether to use the cache or not
545
		 * @param[out,in]  boolean $use_cache Previous setting
546
		 * @param[out] GravityView_Cache $this The GravityView_Cache object
547
		 */
548
		$use_cache = apply_filters( 'gravityview_use_cache', $use_cache, $this );
549
550
		return (boolean) $use_cache;
551
	}
552
553
}
554
555
new GravityView_Cache;
556