-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject-cache.php
More file actions
1507 lines (1314 loc) · 41.5 KB
/
object-cache.php
File metadata and controls
1507 lines (1314 loc) · 41.5 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Originally created by Pantheon as https://github.com/pantheon-systems/wp-redis
* Modified by Tarosky INC.
*/
if ( ! defined( 'WP_CACHE_KEY_SALT' ) ) {
define( 'WP_CACHE_KEY_SALT', '' );
}
/**
* Adds data to the cache, if the cache key doesn't already exist.
*
* @since 2.0.0
*
* @see WP_Object_Cache::add()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The cache key to use for retrieval later.
* @param mixed $data The data to add to the cache.
* @param string $group Optional. The group to add the cache to. Enables the same key
* to be used across groups. Default empty.
* @param int $expire Optional. When the cache data should expire, in seconds.
* Default 0 (no expiration).
* @return bool True on success, false if cache key and group already exist.
*/
function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->add( $key, $data, $group, (int) $expire );
}
/**
* Closes the cache.
*
* This function has ceased to do anything since WordPress 2.5. The
* functionality was removed along with the rest of the persistent cache.
*
* This does not mean that plugins can't implement this function when they need
* to make sure that the cache is cleaned up after WordPress no longer needs it.
*
* @since 2.0.0
*
* @return true Always returns true.
*/
function wp_cache_close() {
return true;
}
/**
* Decrements numeric cache item's value.
*
* @since 3.3.0
*
* @see WP_Object_Cache::decr()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The cache key to decrement.
* @param int $offset Optional. The amount by which to decrement the item's value. Default 1.
* @param string $group Optional. The group the key is in. Default empty.
* @return int|false The item's new value on success, false on failure.
*/
function wp_cache_decr( $key, $offset = 1, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->decr( $key, $offset, $group );
}
/**
* Removes the cache contents matching key and group.
*
* @since 2.0.0
*
* @see WP_Object_Cache::delete()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key What the contents in the cache are called.
* @param string $group Optional. Where the cache contents are grouped. Default empty.
* @return bool True on successful removal, false on failure.
*/
function wp_cache_delete( $key, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->delete( $key, $group );
}
/**
* Removes all cache items.
*
* @since 2.0.0
*
* @see WP_Object_Cache::flush()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @return bool True on success, false on failure.
*/
function wp_cache_flush() {
global $wp_object_cache;
return $wp_object_cache->flush();
}
/**
* Retrieves the cache contents from the cache by key and group.
*
* @since 2.0.0
*
* @see WP_Object_Cache::get()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The key under which the cache contents are stored.
* @param string $group Optional. Where the cache contents are grouped. Default empty.
* @param bool $force Optional. Whether to force an update of the local cache
* from the persistent cache. Default false.
* @param bool $found Optional. Whether the key was found in the cache (passed by reference).
* Disambiguates a return of false, a storable value. Default null.
* @return mixed|false The cache contents on success, false on failure to retrieve contents.
*/
function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
global $wp_object_cache;
return $wp_object_cache->get( $key, $group, $force, $found );
}
/**
* Retrieves multiple values from the cache in one call.
*
* @since 5.5.0
*
* @see WP_Object_Cache::get_multiple()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param array $keys Array of keys under which the cache contents are stored.
* @param string $group Optional. Where the cache contents are grouped. Default empty.
* @param bool $force Optional. Whether to force an update of the local cache
* from the persistent cache. Default false.
* @return array Array of values organized into groups.
*/
function wp_cache_get_multiple( $keys, $group = '', $force = false ) {
global $wp_object_cache;
return $wp_object_cache->get_multiple( $keys, $group, $force );
}
/**
* Increment numeric cache item's value
*
* @since 3.3.0
*
* @see WP_Object_Cache::incr()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The key for the cache contents that should be incremented.
* @param int $offset Optional. The amount by which to increment the item's value. Default 1.
* @param string $group Optional. The group the key is in. Default empty.
* @return int|false The item's new value on success, false on failure.
*/
function wp_cache_incr( $key, $offset = 1, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->incr( $key, $offset, $group );
}
/**
* Sets up Object Cache Global and assigns it.
*
* @since 2.0.0
*
* @global WP_Object_Cache $wp_object_cache
*/
function wp_cache_init() {
$GLOBALS['wp_object_cache'] = new WP_Object_Cache();
}
/**
* Replaces the contents of the cache with new data.
*
* @since 2.0.0
*
* @see WP_Object_Cache::replace()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The key for the cache data that should be replaced.
* @param mixed $data The new data to store in the cache.
* @param string $group Optional. The group for the cache data that should be replaced.
* Default empty.
* @param int $expire Optional. When to expire the cache contents, in seconds.
* Default 0 (no expiration).
* @return bool False if original value does not exist, true if contents were replaced
*/
function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->replace( $key, $data, $group, (int) $expire );
}
/**
* Saves the data to the cache.
*
* Differs from wp_cache_add() and wp_cache_replace() in that it will always write data.
*
* @since 2.0.0
*
* @see WP_Object_Cache::set()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int|string $key The cache key to use for retrieval later.
* @param mixed $data The contents to store in the cache.
* @param string $group Optional. Where to group the cache contents. Enables the same key
* to be used across groups. Default empty.
* @param int $expire Optional. When to expire the cache contents, in seconds.
* Default 0 (no expiration).
* @return bool True on success, false on failure.
*/
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}
/**
* Switches the internal blog ID.
*
* This changes the blog id used to create keys in blog specific groups.
*
* @since 3.5.0
*
* @see WP_Object_Cache::switch_to_blog()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param int $blog_id Site ID.
*/
function wp_cache_switch_to_blog( $blog_id ) {
global $wp_object_cache;
$wp_object_cache->switch_to_blog( $blog_id );
}
/**
* Adds a group or set of groups to the list of global groups.
*
* @since 2.6.0
*
* @see WP_Object_Cache::add_global_groups()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param string|string[] $groups A group or an array of groups to add.
*/
function wp_cache_add_global_groups( $groups ) {
global $wp_object_cache;
$wp_object_cache->add_global_groups( $groups );
}
/**
* Adds a group or set of groups to the list of non-persistent groups.
*
* @since 2.6.0
*
* @see WP_Object_Cache::add_non_persistent_groups()
* @global WP_Object_Cache $wp_object_cache Object cache global instance.
*
* @param string|string[] $groups A group or an array of groups to add.
*/
function wp_cache_add_non_persistent_groups( $groups ) {
global $wp_object_cache;
$wp_object_cache->add_non_persistent_groups( $groups );
}
/**
* Reset internal cache keys and structures.
*
* If the cache back end uses global blog or site IDs as part of its cache keys,
* this function instructs the back end to reset those keys and perform any cleanup
* since blog or site IDs have changed since cache init.
*
* This function is deprecated. Use wp_cache_switch_to_blog() instead of this
* function when preparing the cache for a blog switch. For clearing the cache
* during unit tests, consider using wp_cache_init(). wp_cache_init() is not
* recommended outside of unit tests as the performance penalty for using it is
* high.
*
* @since 2.6.0
* @deprecated 3.5.0 wp_cache_switch_to_blog()
*/
function wp_cache_reset() {
_deprecated_function( __FUNCTION__, '3.5.0', 'wp_cache_switch_to_blog()' );
}
/**
* Retrieve multiple values from cache.
*
* Gets multiple values from cache, including across multiple groups
*
* Usage: array( 'group0' => array( 'key0', 'key1', 'key2', ), 'group1' => array( 'key0' ) )
*
* Mirrors discussion on Trac: https://core.trac.wordpress.org/ticket/20875#comment:33
*
* @param array $groups Array of groups and keys to retrieve
* @param bool $force Optional. Whether to force an update of the local cache
* from the persistent cache. Default false.
*
* @global WP_Object_Cache $wp_object_cache
*
* @return bool|array
* Array of cached values, in format:
* ['group0' => ['key0' => 'value0', 'key1' => 'value1', 'key2' => 'value2'], 'group1' => ['key0' => 'value0']]
* Values not found in cache will be missing along with the corresponding keys.
*/
function wp_cache_tarosky_get_multiple( $groups, $force = false ) {
global $wp_object_cache;
return $wp_object_cache->normalized_get_multiple( $groups, $force );
}
if ( ! defined( 'WP_CACHE_VERSION_KEY_SALT' ) ) {
define( 'WP_CACHE_VERSION_KEY_SALT', 'version:' );
}
class WP_Object_Cache_RedisCallException extends Exception {
protected $method;
protected $args;
public static function create( $method, $args, $previous ) {
$arg_str = var_export( $args, true );
$e = new self(
sprintf(
'Redis call failed: method: %s, args: %s, previous: %s',
$method,
mb_strimwidth( $arg_str, 0, 1024, '...' ) . '[' . mb_strlen( $arg_str ) . ' chars]',
$previous->getMessage()
),
$previous->getCode(),
$previous
);
$e->method = $method;
$e->args = $args;
return $e;
}
public function getMethod() {
return $this->method;
}
public function getArgs() {
return $this->args;
}
}
class WP_Object_Cache { // phpcs:ignore
/**
* Holds the cached objects
*/
public $cache = array();
/**
* The amount of times a request was made to Redis
*/
public $redis_calls = array();
/**
* List of global groups
*/
public $global_groups = array();
/**
* List of non-persistent groups
*/
public $non_persistent_groups = array();
/**
* The blog prefix to prepend to keys in non-global groups.
*/
public $blog_prefix;
/**
* Whether or not Redis is connected
*/
public $is_redis_connected = false;
/**
* Whether or not the object cache thinks Redis needs a flush
*/
public $do_redis_failback_flush = false;
/**
* The last triggered error
*/
public $last_triggered_error = '';
/**
* Redis client
*/
public $redis;
public $host;
public $port;
public $timeout;
public $retry_interval;
public $max_retries;
private $multisite;
private $global_prefix;
/**
* Sets the list of global groups.
*
* @param array $groups List of groups that are global.
*/
public function add_global_groups( $groups ) {
$groups = (array) $groups;
$groups = array_fill_keys( $groups, true );
$this->global_groups = array_merge( $this->global_groups, $groups );
}
/**
* Sets the list of non-persistent groups.
*
* @param array $groups List of groups that are non-persistent.
*/
public function add_non_persistent_groups( $groups ) {
$groups = (array) $groups;
$groups = array_fill_keys( $groups, true );
$this->non_persistent_groups = array_merge( $this->non_persistent_groups, $groups );
}
/**
* Switch the interal blog id.
*
* This changes the blog id used to create keys in blog specific groups.
*
* @param int $blog_id Blog ID
*/
public function switch_to_blog( $blog_id ) {
$blog_id = (int) $blog_id;
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
}
/**
* Check whether there's a value in the internal object cache.
*
* @param string $key
* @param string $group
* @return boolean
*/
private function isset_internal( $key, $group ) {
$key = $this->key( $key, $group );
return array_key_exists( $key, $this->cache );
}
/**
* Get a value from the internal object cache
*
* @param string $key
* @param string $group
* @return mixed
*/
private function get_internal( $key, $group ) {
$value = null;
$key = $this->key( $key, $group );
if ( array_key_exists( $key, $this->cache ) ) {
$value = $this->cache[ $key ];
}
if ( is_object( $value ) ) {
return clone $value;
}
return $value;
}
/**
* Set a value to the internal object cache
*
* @param string $key
* @param string $group
* @param mixed $value
*/
private function set_internal( $key, $group, $value ) {
$key = $this->key( $key, $group );
$this->cache[ $key ] = $value;
}
/**
* Unset a value from the internal object cache
*
* @param string $key
* @param string $group
*/
private function unset_internal( $key, $group ) {
$key = $this->key( $key, $group );
if ( array_key_exists( $key, $this->cache ) ) {
unset( $this->cache[ $key ] );
}
}
/**
* Does this group use persistent storage?
*
* @param string $group Cache group.
* @return bool true if the group is persistent, false if not.
*/
private function should_persist( $group ) {
return empty( $this->non_persistent_groups[ $group ] );
}
/**
* Wrapper method for connecting to Redis, which lets us retry the connection
*/
private function connect_redis() {
try {
$this->redis = $this->prepare_client_connection();
} catch ( Exception $e ) {
$this->exception_handler( $e );
$this->is_redis_connected = false;
return false;
}
$this->is_redis_connected = $this->redis->isConnected();
return $this->is_redis_connected;
}
/**
* Check the error message and return true if the call is retriable.
*
* @param string $error Message to compare
* @return bool whether $error is retriable
*/
public function is_retriable_error_message( $error ) {
$retriable_error_messages = array(
'socket error on read socket',
'Connection closed',
'Redis server went away',
);
foreach ( $retriable_error_messages as $msg ) {
if ( strpos( $error, $msg ) !== false ) {
return true;
}
}
return false;
}
/**
* Handles exceptions by triggering a php error.
*
* @param Exception $exception
* @return null
*/
protected function exception_handler( $exception ) {
try {
$this->last_triggered_error = 'WP Redis: ' . $exception->getMessage() . ": \n" . $exception->getTraceAsString();
// Be friendly to developers debugging production servers by triggering an error
// @codingStandardsIgnoreStart
trigger_error($this->last_triggered_error, E_USER_WARNING);
// @codingStandardsIgnoreEnd
} catch ( PHPUnit_Framework_Error_Warning $e ) {
// PHPUnit throws an Exception when `trigger_error()` is called.
// To ensure our tests (which expect Exceptions to be caught) continue to run,
// we catch the PHPUnit exception and inspect the RedisException message
}
}
/**
* Whether or not wakeup flush is enabled
*
* @return bool
*/
private function is_redis_failback_flush_enabled() {
if ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) {
return false;
} elseif ( defined( 'WP_REDIS_DISABLE_FAILBACK_FLUSH' ) && WP_REDIS_DISABLE_FAILBACK_FLUSH ) {
return false;
}
return true;
}
private static $lua_scripts = array(
'decr-by-nover' => array(),
'incr-by-nover' => array(),
'set' => array(),
);
public static function initialize() {
foreach ( self::$lua_scripts as $name => &$value ) {
$script = file_get_contents( TAROSKY_WP_REDIS_PATCH_LUA_DIR . "/$name.lua" );
$sha1 = sha1( $script );
$value = array(
'script' => $script,
'hash' => $sha1,
);
}
}
public function is_connected() {
return $this->call_redis( 'isConnected' );
}
private static function debug( $message, ...$params ) {
if ( defined( 'TAROSKY_WP_REDIS_PATCH_DEBUG' ) && TAROSKY_WP_REDIS_PATCH_DEBUG ) {
error_log( "[WP_Object_Cache debug]$message: " . var_export( $params, true ) );
}
}
private static function error( $message, ...$params ) {
error_log( "[WP_Object_Cache error]$message: " . var_export( $params, true ) );
error_log(
'[WP_Object_Cache error]stacktrace: ' .
var_export( debug_backtrace(), true ), // phpcs:ignore
);
}
public function ensureLua( $redis_client ) {
$files = array_values( self::$lua_scripts );
$hashes = array_map(function ( $s ) {
return $s['hash'];
}, $files);
$scripts = array_map(function ( $s ) {
return $s['script'];
}, $files);
$existences = $redis_client->script( 'exists', ...$hashes );
array_map(
function ( $script, $exists, $hash, $file ) use ( $redis_client ) {
if ( $exists ) {
return;
}
$res_hash = $redis_client->script( 'load', $script );
if ( $hash !== $res_hash ) {
self::error("SHA1 hashes don't match", array(
'name' => $file,
'calculated' => $hash,
'returned' => $res_hash,
));
$this->call_redis( 'close' );
}
self::debug( 'loaded a Lua script', $file );
return;
},
$scripts,
$existences,
$hashes,
$files,
);
}
private static function clone( $data ) {
return is_object( $data ) ? clone $data : $data;
}
/**
* Utility function to generate the redis key for a given key and group.
*
* @param string $key The cache key.
* @param string $group The cache group.
* @return string A properly prefixed redis cache key.
*/
public function key( $key = '', $group = 'default' ) {
if ( empty( $group ) ) {
$group = 'default';
}
if ( ! empty( $this->global_groups[ $group ] ) ) {
$prefix = $this->global_prefix;
} else {
$prefix = $this->blog_prefix;
}
if ( null === $prefix ) {
$prefix = '';
}
return WP_CACHE_KEY_SALT .
json_encode( array( strval( $prefix ), strval( $group ), strval( $key ) ) );
}
/**
* Constructs a PHPRedis client.
*
* @param array $client_parameters Parameters used to construct a Redis client.
* @return Redis Redis client.
*/
public function prepare_client_connection() {
$redis_client = defined( 'WP_CACHE_USE_RELAY' ) && constant( 'WP_CACHE_USE_RELAY' )
? new \Relay\Relay()
: new Redis();
$redis_client->connect(
$this->host, // host
$this->port, // port
$this->timeout / 1000, // timeout
null, // reserved
100, // retry_interval
$this->timeout / 1000, // read_timeout
);
$this->ensureLua( $redis_client );
return $redis_client;
}
private $versioned_redis_keys = array();
private $versions = array();
public static function encode_redis_string( $data ) {
return is_numeric( $data ) && intval( $data ) === $data
? $data
: igbinary_serialize( $data );
}
public static function decode_redis_get( $data ) {
if ( false === $data ) {
return array( false, false );
}
set_error_handler(function () use ( $data ) {
throw new Exception( "failed to unserialize: '$data'" );
}, E_WARNING);
try {
$result = is_numeric( $data ) ? intval( $data ) : igbinary_unserialize( $data );
} catch ( Exception $e ) {
self::error( 'decode failure', $e->getMessage() );
return array( false, false );
} finally {
restore_error_handler();
}
return array( $result, true );
}
public static function decode_redis_del( $result ) {
if ( ! is_numeric( $result ) ) {
return 0;
}
return intval( $result );
}
private function init_versioned_redis_keys() {
global $redis_server_versioning_keys;
foreach ( $redis_server_versioning_keys as $gkey => $group ) {
foreach ( array_keys( $group ) as $key ) {
$this->versioned_redis_keys[ $this->key( $key, $gkey ) ] = true;
}
}
}
private static function is_ignored( $key, $group ) {
// Ignoring works as if the corresponding cache weren't there.
global $redis_server_ignored_keys;
if ( ! $redis_server_ignored_keys ) {
$redis_server_ignored_keys = array();
}
$iks = $redis_server_ignored_keys;
return array_key_exists( $group, $iks ) &&
array_key_exists( $key, $iks[ $group ] ) &&
$iks[ $group ][ $key ];
}
/**
* Sets up object properties; PHP 5 style constructor
*
* @return null|WP_Object_Cache If cache is disabled, returns null.
*/
public function __construct() {
global $blog_id, $table_prefix, $wpdb, $redis_server;
$this->multisite = is_multisite();
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
$this->host = $redis_server['host'];
$this->port = $redis_server['port'];
$this->timeout = $redis_server['timeout'] ?? 0;
$this->retry_interval = $redis_server['retry_interval'] ?? 1000;
$this->max_retries = $redis_server['max_retries'] ?? 3;
$this->connect_redis();
if ( $this->is_redis_failback_flush_enabled() && ! empty( $wpdb ) ) {
if ( $this->multisite ) {
$table = $wpdb->sitemeta;
$col1 = 'meta_key';
$col2 = 'meta_value';
} else {
$table = $wpdb->options;
$col1 = 'option_name';
$col2 = 'option_value';
}
// @codingStandardsIgnoreStart
$this->do_redis_failback_flush = (bool) $wpdb->get_results("SELECT {$col2} FROM {$table} WHERE {$col1}='wp_redis_do_redis_failback_flush'");
// @codingStandardsIgnoreEnd
if ( $this->is_redis_connected && $this->do_redis_failback_flush ) {
$ret = $this->call_redis( 'flushdb' );
if ( $ret ) {
// @codingStandardsIgnoreStart
$wpdb->query("DELETE FROM {$table} WHERE {$col1}='wp_redis_do_redis_failback_flush'");
// @codingStandardsIgnoreEnd
$this->do_redis_failback_flush = false;
}
}
}
$this->global_prefix = ( $this->multisite || defined( 'CUSTOM_USER_TABLE' ) && defined( 'CUSTOM_USER_META_TABLE' ) ) ? '' : $table_prefix;
$this->init_versioned_redis_keys();
}
public function should_version( $redis_key ) {
return isset( $this->versioned_redis_keys[ $redis_key ] );
}
public function set_cache_version( $redis_key, $version ) {
$this->versions[ $redis_key ] = $version;
}
public function clear_cache_version( $redis_key ) {
unset( $this->versions[ $redis_key ] );
}
public function flush_cache_versions() {
$this->versions = array();
}
public function get_cache_version( $redis_key ) {
return isset( $this->versions[ $redis_key ] ) ? $this->versions[ $redis_key ] : null;
}
public function version_key( $key = '', $group = 'default' ) {
if ( empty( $group ) ) {
$group = 'default';
}
if ( ! empty( $this->global_groups[ $group ] ) ) {
$prefix = $this->global_prefix;
} else {
$prefix = $this->blog_prefix;
}
return WP_CACHE_VERSION_KEY_SALT .
json_encode( array( strval( $prefix ), strval( $group ), strval( $key ) ) );
}
public function generate_version() {
// Versions are expressed as UUID v4.
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
random_int( 0, 0xffff ),
random_int( 0, 0xffff ),
random_int( 0, 0xffff ),
random_int( 0, 0x0fff ) | 0x4000,
random_int( 0, 0x3fff ) | 0x8000,
random_int( 0, 0xffff ),
random_int( 0, 0xffff ),
random_int( 0, 0xffff ),
);
}
private function call_set( $key, $group, $params ) {
$redis_key = $params['key'];
if ( ! $this->should_version( $redis_key ) ) {
$ps = array( $redis_key, $params['value'] );
$opt = array();
if ( $params['nx'] ) {
$opt[] = 'nx';
}
if ( $params['xx'] ) {
$opt[] = 'xx';
}
if ( null !== $params['ex'] ) {
$opt['ex'] = $params['ex'];
}
if ( null !== $params['px'] ) {
$opt['px'] = $params['px'];
}
if ( $opt ) {
$ps[] = $opt;
}
return $this->call_redis( 'set', $ps );
}
$new_version = $this->generate_version();
$result = $this->call_redis(
'evalSha',
array(
self::$lua_scripts['set']['hash'],
array(
$redis_key,
$this->version_key( $key, $group ),
$this->get_cache_version( $redis_key ) ?? '',
$new_version,
$params['value'],
$params['ex'] ?? '',
$params['px'] ?? '',
var_export( $params['nx'], true ),
var_export( $params['xx'], true ),
var_export( $params['keepttl'], true ),
),
2,
)
);
if ( false === $result ) {
$this->clear_cache_version( $redis_key );
$this->unset_internal( $key, $group );
$this->debug( 'found inconsistent update during SET operation', $redis_key );
return false;
}
$this->set_cache_version( $redis_key, $new_version );
return $result;
}
/**
* Sets the data contents into the cache
*
* The cache contents is grouped by the $group parameter followed by the
* $key. This allows for duplicate ids in unique groups. Therefore, naming of
* the group should be used with care and should follow normal function
* naming guidelines outside of core WordPress usage.
*
* The $expire parameter is not used, because the cache will automatically
* expire for each time a page is accessed and PHP finishes. The method is
* more for cache plugins which use files.
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire TTL for the data, in seconds
* @return bool Always returns true
*/
public function set( $key, $data, $group = 'default', $expire = 0 ) {
if ( function_exists( 'wp_suspend_cache_addition' ) && wp_suspend_cache_addition() ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->is_ignored( $key, $group ) ) {
return true;
}
if ( ! $this->should_persist( $group ) ) {
$this->set_internal( $key, $group, self::clone( $data ) );
return true;
}
$set_params = $this->new_set_param(
$this->key( $key, $group ),
self::encode_redis_string( $data ),
);
if ( $expire ) {
$set_params['ex'] = $expire;
}
$succeeded = $this->call_set( $key, $group, $set_params );
if ( $succeeded ) {
$this->set_internal( $key, $group, self::clone( $data ) );
} else {
$this->unset_internal( $key, $group );
}
return $succeeded;
}
/**
* Replace the contents in the cache, if contents already exist
* @see WP_Object_Cache::set()
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire When to expire the cache contents
* @return bool False if not exists, true if contents were replaced
*/
public function replace( $key, $data, $group = 'default', $expire = 0 ) {
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->is_ignored( $key, $group ) ) {
return false;
}
if ( ! $this->should_persist( $group ) ) {
return false;
}
$set_params = $this->new_set_param(
$this->key( $key, $group ),
self::encode_redis_string( $data ),
);
$set_params['xx'] = true;