Jake Vanderwerf
8 days ago 90f5c3069f23f63036ab0178ff9ab69effcfb2ea
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
<?php
namespace JVBase\managers;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class Cache
{
    private string $group;
    private int $ttl;
 
    private static array $instances = [];
    private bool $hasRedis;
    private bool $varyByAuth = false;
    private bool $varyByUser = false;
 
    private array $index=[];
    private ?string $target = null;
 
    private function __construct(string $group, ?string $target = null, int $ttl = WEEK_IN_SECONDS)
    {
        if (!is_null($target) && empty($this->index)) {
            $this->target = null;
            $this->index = get_option(BASE."cache_{$target}_index",[]);
        }
        $this->group = $group;
        $this->ttl   = $ttl;
        $this->logGroup();
        $this->hasRedis = (bool)wp_using_ext_object_cache();
    }
 
    protected function logGroup():void
    {
        $changed = false;
        $groups = get_option(BASE."cache_groups", []);
        if (!array_key_exists($this->group, $groups)) {
            $groups[$this->group] = [
                'auth'  => $this->varyByAuth,
                'user'  => $this->varyByUser,
                'target'=> $this->target,
                'ttl'   => $this->ttl,
            ];
            $changed = true;
        }
 
        if ($groups[$this->group]['auth'] && !$this->varyByAuth) {
            error_log('[Cache]Group '.$this->group.' previously defined as varying by auth, but is not set. Setting it now.');
            $this->auth();
        }
        if ($groups[$this->group]['user'] && !$this->varyByUser) {
            error_log('[Cache]Group '.$this->group.' previously defined as varying by user, but is not set. Setting it now.');
            $this->user();
        }
        if (is_null($this->target) && !is_null($groups[$this->group]['target'])) {
            error_log('[Cache]Group '.$this->group. ' previously defined with target '.$groups[$this->group]['target'].'... Setting it now.');
            $this->target = $groups[$this->group]['target'];
        } elseif ($this->target !== $groups[$this->group]['target']) {
            error_log('[Cache]WARNING Group previously defined with target '.$groups[$this->group]['target'].' - but is currently defined with '.$this->target. '. You may want to look into this.');
        }
 
        if ($this->ttl !== $groups[$this->group]['ttl']) {
            error_log('[Cache]Group '. $this->group. ' previously defined with ttl '.$groups[$this->group]['ttl']. ' - but is currently defined with '. $this->ttl);
            $groups[$this->group]['ttl'] = $this->ttl;
            $changed = true;
        }
 
        if ($this->varyByAuth && !$groups[$this->group]['auth']) {
            $groups[$this->group]['auth'] = true;
            $changed = true;
        }
        if ($this->varyByUser && !$groups[$this->group]['user']) {
            $groups[$this->group]['user'] = true;
            $changed = true;
        }
        if ($this->target !== $groups[$this->group]['target']) {
            $groups[$this->group]['target'] = $this->target;
            $changed = true;
        }
 
        if ($changed) {
            update_option(BASE."cache_groups", $groups, false);
        }
    }
 
    public static function registerHooks(): void
    {
        // Post updates (all post types including core)
        add_action('save_post', [self::class, 'onPostChange'], 10, 2);
        add_action('delete_post', [self::class, 'onPostDelete']);
 
        // Post meta updates, now handled via Meta.php?
//      add_action('updated_post_meta', [self::class, 'onPostMetaChange'], 10, 2);
//      add_action('added_post_meta', [self::class, 'onPostMetaChange'], 10, 2);
//      add_action('deleted_post_meta', [self::class, 'onPostMetaDelete'], 10, 2);
 
        // Term updates (all taxonomies)
        add_action('edited_term', [self::class, 'onTermChange'], 10, 3);
        add_action('create_term', [self::class, 'onTermChange'], 10, 3);
        add_action('delete_term', [self::class, 'onTermDelete'], 10, 3);
 
        // Term meta updates
//      add_action('updated_term_meta', [self::class, 'onTermMetaChange'], 10, 2);
//      add_action('added_term_meta', [self::class, 'onTermMetaChange'], 10, 2);
//      add_action('deleted_term_meta', [self::class, 'onTermMetaDelete'], 10, 2);
 
        // User updates
        add_action('profile_update', [self::class, 'onUserChange'], 10, 2);
        add_action('user_register', [self::class, 'onUserChange'], 10, 1);
        add_action('deleted_user', [self::class, 'onUserDelete']);
 
        // User meta updates
//      add_action('updated_user_meta', [self::class, 'onUserMetaChange'], 10, 2);
//      add_action('added_user_meta', [self::class, 'onUserMetaChange'], 10, 2);
//      add_action('deleted_user_meta', [self::class, 'onUserMetaDelete'], 10, 2);
    }
 
    public function auth(): static
    {
        $this->varyByAuth = true;
        return $this;
    }
 
    public function user(): static
    {
        $this->varyByUser = true;
        return $this;
    }
 
    private function resolveKey(int|string $key): string
    {
        if ($this->varyByUser) {
            return $key . ':u' . get_current_user_id();
        }
        if ($this->varyByAuth) {
            return $key . ':' . (is_user_logged_in() ? 'auth' : 'guest');
        }
        return (string) $key;
    }
 
    public static function for(string $group, ?string $target = null, int $ttl = HOUR_IN_SECONDS): self
    {
        $group = sanitize_key($group);
 
        if (!isset(self::$instances[$group])) {
            self::$instances[$group] = new self($group, $target, $ttl);
        }
 
        return self::$instances[$group];
    }
 
    /**
     * To help facilitate cache flushing on object updates, we track the keys that are used for a particular id
     * Generally, $this->target will either be 'post', 'user', 'term', or 'custom'
     * @param int $ID
     * @param string $key
     * @return void
     */
    protected function trackID(int $ID, string $key):void
    {
        if (is_null($this->target)) {
            return;
        }
        if (!array_key_exists($ID, $this->index[$this->target])) {
            $this->index[$ID] = [];
        }
        if (!array_key_exists($this->group, $this->index[$ID])) {
            $this->index[$ID][$this->group] = [];
        }
        if (!in_array($key, $this->index[$ID][$this->group])) {
            $this->index[$this->target][$ID][$this->group][] = $key;
            update_option(BASE."cache_{$this->target}_index", $this->index, false);
        }
    }
 
    /* ---------------------------------------------------------------------
     * Core operations
     * ------------------------------------------------------------------- */
 
    public function remember(int|string|array $key, callable $callback, ?int $ttl = null): mixed
    {
        $key = $this->generateKey($key);
 
        $value = $this->get($key);
 
        if ($value !== false) {
            return $value;
        }
 
        $value = $callback();
 
        if ($value !== null && $value !== false) {
            $this->set($key, $value, $ttl);
        }
 
        return $value;
    }
    protected function transientKey(string $key):string
    {
        return BASE."{$this->group}_{$key}";
    }
 
    public function get(int|string|array $key): mixed
    {
        $key = $this->generateKey($key, false);
 
        $value = $this->hasRedis ?
            wp_cache_get($key, $this->group) :
            get_transient($this->transientKey($key));
 
        return $value['value']??false;
    }
    public function getTimestamp(int|string|array $key): mixed
    {
        $key = $this->generateKey($key, false);
 
        $value = $this->hasRedis ?
            wp_cache_get($key, $this->group) :
            get_transient($this->transientKey($key));
        return $value['modified']??false;
    }
 
    public function set(int|string|array $key, mixed $value, ?int $ttl = null): void
    {
        $key = $this->generateKey($key);
        $ttl = $ttl??$this->ttl;
        $store = [
            'value' => $value,
            'modified'  => time()
        ];
        if ($this->hasRedis) {
            wp_cache_set($key, $store, $this->group, $ttl);
        } else {
            set_transient($this->transientKey($key), $store, $ttl);
        }
    }
 
    public function forget(int|string|array $key): void
    {
        $key = $this->generateKey($key);
        if ($this->hasRedis) {
            wp_cache_delete($key, $this->group);
        } else {
            delete_transient($this->transientKey($key));
        }
 
    }
 
    public function flush(): void
    {
        if ($this->hasRedis) {
            if (function_exists('wp_cache_flush_group')) {
                wp_cache_flush_group($this->group);
            } else {
                wp_cache_flush();
            }
        } else {
            $this->clearGroupTransients();
        }
    }
 
    public static function clearPost(int $ID):void
    {
        $index = get_option(BASE."cache_post_index", []);
        if (!array_key_exists($ID, $index)) {
            return;
        }
        foreach ($index[$ID] as $group => $keys) {
            $cache = self::for($group, 'post');
            foreach ($keys as $key) {
                $cache->forget($key);
            }
        }
    }
    public static function clearUser(int $ID):void
    {
        $index = get_option(BASE."cache_user_index", []);
        if (!array_key_exists($ID, $index)) {
            return;
        }
        foreach ($index[$ID] as $group => $keys) {
            $cache = self::for($group, 'user');
            foreach ($keys as $key) {
                $cache->forget($key);
            }
        }
    }
    public static function clearTerm(int $ID):void
    {
        $index = get_option(BASE."cache_term_index", []);
        if (!array_key_exists($ID, $index)) {
            return;
        }
        foreach ($index[$ID] as $group => $keys) {
            $cache = self::for($group, 'term');
            foreach ($keys as $key) {
                $cache->forget($key);
            }
        }
    }
 
 
    public static function invalidateGroup(string $group): void
    {
        self::for($group)->flush();
    }
 
 
    /****************************************************
     * TRANSIENT HELPER
     ****************************************************/
    private function clearGroupTransients(): void
    {
        global $wpdb;
 
        $pattern = '_transient_' .BASE. $this->group . '%';
        $timeout_pattern = '_transient_timeout_' . BASE . $this->group . '%';
 
        // Remove LIMIT to avoid table locks, add retry for deadlocks
        $attempts = 0;
        $max_attempts = 3;
 
        while ($attempts < $max_attempts) {
            $result = $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM $wpdb->options
                 WHERE option_name LIKE %s OR option_name LIKE %s",
                    $pattern,
                    $timeout_pattern
                )
            );
 
            // Success or non-deadlock error
            if ($result !== false || !str_contains($wpdb->last_error, 'Deadlock')) {
                break;
            }
 
            $attempts++;
            if ($attempts < $max_attempts) {
                usleep(50000); // Wait 50ms before retry
            }
        }
    }
    /****************************************************
     * HOOKS
     ****************************************************/
    /****************************************************
     * HOOKS - Posts
     ****************************************************/
    public static function onPostChange(int $postId, \WP_Post $post): void
    {
        if (wp_is_post_revision($postId) || wp_is_post_autosave($postId)) {
            return;
        }
 
//      error_log('[Clearing cache for post change: '.$postId.']');
        self::clearPost($postId);
    }
 
    public static function onPostDelete(int $postId): void
    {
//      error_log('[Clearing cache for post delete: '.$postId.']');
        self::clearPost($postId);
    }
 
//  public static function onPostMetaChange(int $metaId, int $objectId): void
//  {
////        error_log('[Clearing cache for post meta change: '.$objectId.']');
//      self::invalidateItem('post', $objectId);
//  }
//
//  public static function onPostMetaDelete(array $metaIds, int $objectId): void
//  {
////        error_log('[Clearing cache for post meta delete: '.$objectId.']');
//      self::invalidateItem('post', $objectId);
//  }
 
    /****************************************************
     * HOOKS - Terms
     ****************************************************/
    public static function onTermChange(int $termId, int $ttId, string $taxonomy): void
    {
        error_log('[Clearing cache for term change: '.$termId.']');
        self::clearTerm($termId);
    }
 
    public static function onTermDelete(int $termId): void
    {
//      error_log('[Clearing cache for term delete: '.$termId.']');
        self::clearTerm($termId);
    }
 
    public static function onTermMetaChange(int $metaId, int $objectId): void
    {
//      error_log('[Clearing cache for term meta change: '.$objectId.']');
        self::clearTerm($objectId);
    }
 
    public static function onTermMetaDelete(array $metaIds, int $objectId): void
    {
//      error_log('[Clearing cache for term meta delete: '.$objectId.']');
        self::clearTerm($objectId);
    }
 
    /****************************************************
     * HOOKS - Users
     ****************************************************/
    public static function onUserChange(int $userId): void
    {
//      error_log('[Clearing cache for user change: '.$userId.']');
        self::clearUser($userId);
    }
 
    public static function onUserDelete(int $userId): void
    {
//      error_log('[Clearing cache for user delete: '.$userId.']');
        self::clearUser($userId);
    }
 
    public static function onUserMetaChange(int $metaId, int $objectId): void
    {
//      error_log('[Clearing cache for user meta change: '.$objectId.']');
        self::clearUser($objectId);
    }
 
    public static function onUserMetaDelete(array $metaIds, int $objectId): void
    {
//      error_log('[Clearing cache for user meta delete: '.$objectId.']');
        self::clearUser($objectId);
    }
    /***************************************************
     * UTILITY
     **************************************************/
    /**
     * Generate a cache key from parameters
     * Useful for caching based on multiple variables
     *
     * @param int|string|array $key Key-value pairs that uniquely identify this cache entry
     * @return string MD5 hash of sorted parameters
     */
    public function generateKey(int|string|array $key, bool $trackIt = true): string
    {
        $trackID = false;
        $ID = false;
 
        if (!is_null($this->target) && is_int($key)) {
            //Likely an item id. Store it for reference
            $trackID = true;
            $ID = $key;
        }
        if (is_array($key)) {
            ksort($key);
            if (!is_null($this->target) && array_key_exists('id', $key)) {
                $trackID = true;
                $ID = $key['id'];
            }
            $key = md5(serialize($key));
        }
 
        $key = $this->resolveKey($key);
        if ($trackIt && !is_null($this->target) && $ID && $trackID) {
            $this->trackID($ID, $key);
        }
        return $key;
    }
 
    /**
     * Nuclear option: Flush ALL registered cache groups
     * Use for debugging or after major updates
     *
     * @return int Number of groups flushed
     */
    public static function flushAll(): int
    {
        $groups = get_option(BASE."cache_groups", []);
        $count = 0;
        foreach ($groups as $group => $conf) {
            $cache = Cache::for($group, $conf['target']??null, $conf['ttl']);
            $cache->flush();
            $count ++ ;
 
            usleep(50000); // Wait 50ms before retry
        }
        return $count;
    }
 
    /**
     * Get all cache groups
     *
     * @return array
     */
    public static function getAllGroups(): array
    {
        return get_option(BASE."cache_groups", []);
    }
}