Completed
Pull Request — master (#868)
by Zack
06:16
created

GravityView_Cache::set_key()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 15
ccs 0
cts 6
cp 0
crap 6
rs 9.4285
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 6 and the first side effect is on line 554.

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 2
	public function entry_updated( $form, $lead_id ) {
131
132 2
		do_action( 'gravityview_log_debug', 'GravityView_Cache[entry_updated] adding form ' . $form['id'] . ' to blacklist because entry #' . $lead_id . ' was updated' );
133
134 2
		$this->blacklist_add( $form['id'] );
135 2
	}
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 2
	public function entry_added( $entry, $form ) {
163 2
		if ( is_wp_error( $entry ) ) {
164
			return;
165
		}
166
167 2
		do_action( 'gravityview_log_debug', 'GravityView_Cache[entry_added] adding form ' . $form['id'] . ' to blacklist because entry #' . $entry['id'] . ' was added' );
168
169 2
		$this->blacklist_add( $form['id'] );
170 2
	}
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 2
	public function blacklist_add( $form_ids ) {
234
235 2
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
236
237 2
		$form_ids = is_array( $form_ids ) ? $form_ids : array( $form_ids );
238
239 2
		do_action( 'gravityview_log_debug', 'GravityView_Cache[blacklist_add] Adding form IDs to cache blacklist', array(
240 2
			'$form_ids'  => $form_ids,
241 2
			'$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 2
		$blacklist = array_merge( (array) $blacklist, $form_ids );
246
247
		// Don't duplicate
248 2
		$blacklist = array_unique( $blacklist );
249
250 2
		return update_option( self::BLACKLIST_OPTION_NAME, $blacklist );
251
252
	}
253
254
	/**
255
	 * Remove Form IDs from blacklist
256
	 *
257
	 * @param  int|array $form_ids Form IDs to add
258
	 *
259
	 * @return boolean           Whether the removal was successful
260
	 */
261
	public function blacklist_remove( $form_ids ) {
262
263
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
264
265
		$updated_list = array_diff( $blacklist, (array) $form_ids );
266
267
		do_action( 'gravityview_log_debug', 'GravityView_Cache[blacklist_remove] Removing form IDs from cache blacklist', array(
268
			'$form_ids'     => $form_ids,
269
			'$blacklist'    => $blacklist,
270
			'$updated_list' => $updated_list
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
271
		) );
272
273
		return update_option( self::BLACKLIST_OPTION_NAME, $updated_list );
274
	}
275
276
277
	/**
278
	 * Is a form ID in the cache blacklist
279
	 *
280
	 * @param  int|array $form_ids Form IDs to check if in blacklist
281
	 *
282
	 * @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...
283
	 */
284 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...
285
286 1
		$blacklist = get_option( self::BLACKLIST_OPTION_NAME, array() );
287
288
		// Use object var if exists
289 1
		$form_ids = is_null( $form_ids ) ? $this->form_ids : $form_ids;
290
291 1
		if ( empty( $form_ids ) ) {
292
293
			do_action( 'gravityview_log_debug', 'GravityView_Cache[in_blacklist] Did not add form to blacklist; empty form ID', $form_ids );
294
295
			return false;
296
		}
297
298 1
		foreach ( (array) $form_ids as $form_id ) {
299
300 1
			if ( in_array( $form_id, $blacklist ) ) {
301
302 1
				do_action( 'gravityview_log_debug', 'GravityView_Cache[in_blacklist] Form #' . esc_attr( $form_id ) . ' is in the cache blacklist' );
303
304 1
				return true;
305
			}
306
		}
307
308 1
		return false;
309
	}
310
311
312
	/**
313
	 * Get transient result
314
	 *
315
	 * @param  string $key Transient key to fetch
316
	 *
317
	 * @return mixed      False: Not using cache or cache was a WP_Error object; NULL: no results found; Mixed: cache value
318
	 */
319
	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...
320
321
		$key = is_null( $key ) ? $this->key : $key;
322
323
		if ( ! $this->use_cache() ) {
324
325
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Not using cached results because of GravityView_Cache->use_cache() results' );
326
327
			return false;
328
		}
329
330
		do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Fetching request with transient key ' . $key );
331
332
		$result = get_transient( $key );
333
334
		if ( is_wp_error( $result ) ) {
335
336
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Fetching request resulted in error:', $result );
337
338
			return false;
339
340
		} elseif ( $result ) {
341
342
			do_action( 'gravityview_log_debug', 'GravityView_Cache[get] Cached results found for  transient key ' . $key );
343
344
			return $result;
345
		}
346
347
		do_action( 'gravityview_log_debug', 'GravityView_Cache[get] No cached results found for  transient key ' . $key );
348
349
		return NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
350
351
	}
352
353
	/**
354
	 * Cache content as a transient.
355
	 *
356
	 * Cache time defaults to 1 week
357
	 *
358
	 * @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...
359
	 * @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...
360
	 */
361
	public function set( $content, $filter_name = '' ) {
362
363
		// Don't cache empty results
364
		if ( ! empty( $content ) ) {
365
366
			/**
367
			 * @filter `gravityview_cache_time_{$filter_name}` Modify the cache time for a type of cache
368
			 * @param int $time_in_seconds Default: `DAY_IN_SECONDS`
369
			 */
370
			$cache_time = (int) apply_filters( 'gravityview_cache_time_' . $filter_name, DAY_IN_SECONDS );
371
372
			do_action( 'gravityview_log_debug', 'GravityView_Cache[set] Setting cache with transient key ' . $this->key . ' for ' . $cache_time . ' seconds' );
373
374
			return set_transient( $this->key, $content, $cache_time );
375
376
		}
377
378
		do_action( 'gravityview_log_debug', 'GravityView_Cache[set] Cache not set; content is empty' );
379
380
		return false;
381
382
	}
383
384
	/**
385
	 * Delete cached transients based on form IDs
386
	 *
387
	 * @todo Use REGEX to match forms when array of form IDs is passed, instead of using a simple LIKE
388
	 * @todo  Rate limit deleting to prevent abuse
389
	 *
390
	 * @param  int|array $form_ids Form IDs to delete
391
	 *
392
	 * @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...
393
	 */
394
	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...
395
		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...
396
397
		// Use object var if exists
398
		$form_ids = is_null( $form_ids ) ? $this->form_ids : $form_ids;
399
400
		if ( empty( $form_ids ) ) {
401
			do_action( 'gravityview_log_debug', 'GravityView_Cache[delete] Did not delete cache; empty form IDs' );
402
403
			return;
404
		}
405
406
		foreach ( (array) $form_ids as $form_id ) {
407
408
			$key = $this->get_cache_key_prefix( $form_id );
409
410
			// WordPress 4.0+
411
			if ( is_callable( array( $wpdb, 'esc_like' ) ) ) {
412
				$key = $wpdb->esc_like( $key );
413
			} else {
414
				$key = like_escape( $key );
415
			}
416
417
			$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...
418
419
			$sql = $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE `option_name` LIKE %s", $key );
420
421
			$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...
422
423
			do_action( 'gravityview_log_debug', 'GravityView_Cache[delete] Deleting cache for form #' . $form_id, array(
424
				$sql,
425
				sprintf( 'Deleted results: %d', $result )
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
426
			) );
427
		}
428
429
	}
430
431
	/**
432
	 * Schedule expired transient cleanup twice a day.
433
	 *
434
	 * Can be overruled by the `gravityview_cleanup_transients` filter (returns boolean)
435
	 *
436
	 * @return void
437
	 */
438
	public function schedule_transient_cleanup() {
439
440
		/**
441
		 * @filter `gravityview_cleanup_transients` Override GravityView cleanup of transients by setting this to false
442
		 * @param boolean $cleanup Whether to run the GravityView auto-cleanup of transients. Default: `true`
443
		 */
444
		$cleanup = apply_filters( 'gravityview_cleanup_transients', true );
445
446
		if ( ! $cleanup ) {
447
			return;
448
		}
449
450
		if ( ! wp_next_scheduled( 'gravityview-expired-transients' ) ) {
451
			wp_schedule_event( time(), 'daily', 'gravityview-expired-transients' );
452
		}
453
	}
454
455
	/**
456
	 * Delete expired transients.
457
	 *
458
	 * The code is copied from the Delete Expired Transients, with slight modifications to track # of results and to get the blog ID dynamically
459
	 *
460
	 * @see https://wordpress.org/plugins/delete-expired-transients/ Plugin where the code was taken from
461
	 * @see  DelxtransCleaners::clearBlogExpired()
462
	 * @return void
463
	 */
464
	public function delete_expired_transients() {
465
		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...
466
467
		// Added this line, which isn't in the plugin
468
		$blog_id = get_current_blog_id();
469
470
		$num_results = 0;
471
472
		// get current PHP time, offset by a minute to avoid clashes with other tasks
473
		$threshold = time() - 60;
474
475
		// get table name for options on specified blog
476
		$table = $wpdb->get_blog_prefix( $blog_id ) . 'options';
477
478
		// delete expired transients, using the paired timeout record to find them
479
		$sql = "
480
			delete from t1, t2
481
			using $table t1
482
			join $table t2 on t2.option_name = replace(t1.option_name, '_timeout', '')
483
			where (t1.option_name like '\_transient\_timeout\_%' or t1.option_name like '\_site\_transient\_timeout\_%')
484
			and t1.option_value < '$threshold'
485
		";
486
487
		$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...
488
489
		// delete orphaned transient expirations
490
		// also delete NextGEN Gallery 2.x display cache timeout aliases
491
		$sql = "
492
			delete from $table
493
			where (
494
				   option_name like '\_transient\_timeout\_%'
495
				or option_name like '\_site\_transient\_timeout\_%'
496
				or option_name like 'displayed\_galleries\_%'
497
				or option_name like 'displayed\_gallery\_rendering\_%'
498
			)
499
			and option_value < '$threshold'
500
		";
501
502
		$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...
503
504
		do_action( 'gravityview_log_debug', 'GravityView_Cache[delete_expired_transients] Deleted ' . $num_results . ' expired transient records from the database' );
505
	}
506
507
	/**
508
	 * Check whether to use cached results, if available
509
	 *
510
	 * If the user can edit posts, they are able to override whether to cache results by adding `cache` or `nocache` to the URL requested.
511
	 *
512
	 * @return boolean True: use cache; False: don't use cache
513
	 */
514
	public function use_cache() {
515
516
		$use_cache = true;
517
518
		if ( GVCommon::has_cap( 'edit_gravityviews' ) ) {
519
520
			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...
521
522
				do_action( 'gravityview_log_debug', 'GravityView_Cache[use_cache] Not using cache: ?cache or ?nocache is in the URL' );
523
524
				$use_cache = false;
525
			}
526
527
		}
528
529
		// Has the form been flagged as having changed items in it?
530
		if ( $this->in_blacklist() ) {
531
532
			// Delete caches for all items with form IDs XYZ
533
			$this->delete( $this->form_ids );
534
535
			// Remove the form from
536
			$this->blacklist_remove( $this->form_ids );
537
538
		}
539
540
		// Check the blacklist
541
542
		/**
543
		 * @filter `gravityview_use_cache` Modify whether to use the cache or not
544
		 * @param[out,in]  boolean $use_cache Previous setting
545
		 * @param[out] GravityView_Cache $this The GravityView_Cache object
546
		 */
547
		$use_cache = apply_filters( 'gravityview_use_cache', $use_cache, $this );
548
549
		return (boolean) $use_cache;
550
	}
551
552
}
553
554
new GravityView_Cache;
555