-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
_service-caching.php
1478 lines (1221 loc) · 41 KB
/
_service-caching.php
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
// =============================================================================
// ANY CACHE ACTIVE?
// =============================================================================
// List of known cache plugins
if ( ! defined( 'FICTIONEER_KNOWN_CACHE_PLUGINS' ) ) {
define(
'FICTIONEER_KNOWN_CACHE_PLUGINS',
array(
'w3-total-cache/w3-total-cache.php', // W3 Total Cache
'wp-super-cache/wp-cache.php', // WP Super Cache
'wp-rocket/wp-rocket.php', // WP Rocket
'litespeed-cache/litespeed-cache.php', // LiteSpeed Cache
'wp-fastest-cache/wpFastestCache.php', // WP Fastest Cache
'cache-enabler/cache-enabler.php', // Cache Enabler
'hummingbird-performance/wp-hummingbird.php', // Hummingbird – Optimize Speed, Enable Cache
'wp-optimize/wp-optimize.php', // WP-Optimize - Clean, Compress, Cache
'sg-cachepress/sg-cachepress.php', // SG Optimizer (SiteGround)
'breeze/breeze.php', // Breeze (by Cloudways)
'nitropack/nitropack.php' // NitroPack
)
);
}
function fictioneer_get_active_cache_plugins() {
static $plugin_names = array(
'w3-total-cache/w3-total-cache.php' => 'W3 Total Cache',
'wp-super-cache/wp-cache.php' => 'WP Super Cache',
'wp-rocket/wp-rocket.php' => 'WP Rocket',
'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
'cache-enabler/cache-enabler.php' => 'Cache Enabler',
'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
'wp-optimize/wp-optimize.php' => 'WP-Optimize',
'sg-cachepress/sg-cachepress.php' => 'SG Optimizer',
'breeze/breeze.php' => 'Breeze',
'nitropack/nitropack.php' => 'NitroPack'
);
$result = [];
foreach ( FICTIONEER_KNOWN_CACHE_PLUGINS as $plugin_slug ) {
if ( is_plugin_active( $plugin_slug ) && isset( $plugin_names[ $plugin_slug ] ) ) {
$result[] = $plugin_names[ $plugin_slug ];
}
}
return $result;
}
if ( ! function_exists( 'fictioneer_caching_active' ) ) {
/**
* Checks whether caching is active
*
* Checks for a number of known caching plugins or the cache
* compatibility option for anything not covered.
*
* @since 4.0.0
*
* @param string|null $context Context of the check. Currently unused.
*
* @return boolean Either true (active) or false (inactive or not installed).
*/
function fictioneer_caching_active( $context = null ) {
// Check early
if ( get_option( 'fictioneer_enable_cache_compatibility' ) ) {
return true;
}
// Check active plugins
$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
$active_cache_plugins = array_intersect( $active_plugins, FICTIONEER_KNOWN_CACHE_PLUGINS );
// Any cache plugins active?
return ! empty( $active_cache_plugins );
}
}
if ( ! function_exists( 'fictioneer_private_caching_active' ) ) {
/**
* Checks whether private caching is active
*
* Checks whether the user is logged in and the private cache
* compatibility mode is enabled. Public and private caching
* contradict each other, with public caching given priority.
*
* @since 5.0.0
*
* @return boolean Either true or false.
*/
function fictioneer_private_caching_active() {
return is_user_logged_in() &&
get_option( 'fictioneer_enable_private_cache_compatibility', false ) &&
! get_option( 'fictioneer_enable_public_cache_compatibility', false );
}
}
// Boolean: Partial caching enabled?
if ( ! defined( 'FICTIONEER_ENABLE_PARTIAL_CACHING' ) ) {
define(
'FICTIONEER_ENABLE_PARTIAL_CACHING',
get_option( 'fictioneer_enable_static_partials' ) &&
! is_customize_preview() &&
! fictioneer_caching_active( 'enable_partial_caching' )
);
}
// Boolean: Story card caching enabled?
if ( ! defined( 'FICTIONEER_ENABLE_STORY_CARD_CACHING' ) ) {
define(
'FICTIONEER_ENABLE_STORY_CARD_CACHING',
get_option( 'fictioneer_enable_story_card_caching' ) && ! is_customize_preview()
);
}
// =============================================================================
// ENABLE TRANSIENTS?
// =============================================================================
/**
* Whether to enable Transients for shortcodes
*
* @since 5.6.3
* @since 5.23.1 - Do not turn off with cache plugin.
* @since 5.25.0 - Refactored with option.
*
* @param string $shortcode The shortcode in question.
*
* @return boolean Either true or false.
*/
function fictioneer_enable_shortcode_transients( $shortcode = null ) {
global $pagenow;
if ( is_customize_preview() || is_admin() || $pagenow === 'post.php' ) {
return false;
}
$bool = FICTIONEER_SHORTCODE_TRANSIENT_EXPIRATION > -1 &&
! get_option( 'fictioneer_disable_shortcode_transients' );
return apply_filters( 'fictioneer_filter_enable_shortcode_transients', $bool, $shortcode );
}
/**
* Whether to enable Transients for story chapter lists
*
* Note: By default true unless there is a known cache plugin
* active or the Transients are turned off by option. They are
* always disabled in the Customizer preview.
*
* @since 5.25.0
*
* @param int $post_id Post ID of the story.
*
* @return boolean Either true or false.
*/
function fictioneer_enable_chapter_list_transients( $post_id ) {
if ( is_customize_preview() ) {
return false;
}
$bool = ! fictioneer_caching_active( 'story_chapter_list' ) &&
! get_option( 'fictioneer_disable_chapter_list_transients' );
return apply_filters( 'fictioneer_filter_enable_chapter_list_transients', $bool, $post_id );
}
/**
* Whether to enable Transients for menus
*
* @since 5.25.0
*
* @param string $location Location identifier of the menu. Possible locations are
* 'nav_menu', 'mobile_nav_menu', and 'footer_menu'.
*
* @return boolean Either true or false.
*/
function fictioneer_enable_menu_transients( $location ) {
if ( is_customize_preview() ) {
return false;
}
return apply_filters(
'fictioneer_filter_enable_menu_transients',
! get_option( 'fictioneer_disable_menu_transients' ),
$location
);
}
// =============================================================================
// PURGE CACHES
// =============================================================================
if ( ! function_exists( 'fictioneer_purge_all_caches' ) ) {
/**
* Trigger the "purge all" functions of known cache plugins
*
* @since 4.0.0
* @link https://docs.litespeedtech.com/lscache/lscwp/api/#purge
* @link https://docs.wp-rocket.me/article/494-how-to-clear-cache-via-cron-job#clear-cache
* @link https://wp-kama.com/plugin/wp-super-cache/function/wp_cache_clean_cache
*/
function fictioneer_purge_all_caches() {
// Object cache
wp_cache_flush();
// Hook for additional purges
do_action( 'fictioneer_cache_purge_all' );
// LiteSpeed Cache
if ( class_exists( '\LiteSpeed\Purge' ) ) {
do_action( 'litespeed_purge_all' );
}
// WP Rocket Cache
if ( function_exists( 'rocket_clean_domain' ) ) {
rocket_clean_domain();
}
// WP Super Cache
if ( function_exists( 'wp_cache_clean_cache' ) ) {
global $file_prefix;
wp_cache_clean_cache( $file_prefix, true );
}
// W3 Total Cache
if ( function_exists( 'w3tc_flush_all' ) ) {
w3tc_flush_all();
}
// Cache Enabler
if ( has_action( 'cache_enabler_clear_complete_cache' ) ) {
do_action( 'cache_enabler_clear_complete_cache' );
}
// Hummingbird
if ( has_action( 'wphb_clear_page_cache' ) ) {
do_action( 'wphb_clear_page_cache' );
}
// SG Optimizer
// Insufficient or hard-to-find documentation and if the
// developer cannot be bothered, neither can I.
// Breeze
if ( has_action( 'breeze_clear_all_cache' ) ) {
do_action( 'breeze_clear_all_cache' );
}
// WP Optimize
if ( class_exists( 'WP_Optimize' ) ) {
$wp_optimize = WP_Optimize();
if ( method_exists( $wp_optimize, 'get_page_cache' ) ) {
$wp_optimize->get_page_cache()->purge();
}
}
// W3 Fastest Cache
if ( function_exists( 'wpfc_clear_all_cache' ) ) {
wpfc_clear_all_cache();
}
// NitroPack
// Insufficient or hard-to-find documentation and if the
// developer cannot be bothered, neither can I.
// Cached HTML partials
fictioneer_clear_all_cached_partials();
// Cached story cards
if ( FICTIONEER_ENABLE_STORY_CARD_CACHING ) {
fictioneer_purge_story_card_cache();
}
}
}
if ( ! function_exists( 'fictioneer_purge_post_cache' ) ) {
/**
* Trigger the "purge post" functions of known cache plugins
*
* @since 4.7.0
* @link https://docs.litespeedtech.com/lscache/lscwp/api/#purge
* @link https://docs.wp-rocket.me/article/494-how-to-clear-cache-via-cron-job#clear-cache
* @link https://wp-kama.com/plugin/wp-super-cache/function/wpsc_delete_post_cache
*
* @param int $post_id Post ID.
*/
function fictioneer_purge_post_cache( $post_id ) {
// Setup
$post_id = fictioneer_validate_id( $post_id );
// Abort if...
if ( empty( $post_id ) ) {
return;
}
// Hook for additional purges
do_action( 'fictioneer_cache_purge_post', $post_id );
// WordPress Query Cache
clean_post_cache( $post_id );
// LiteSpeed Cache
if ( class_exists( '\LiteSpeed\Purge' ) ) {
do_action( 'litespeed_purge_post', $post_id );
}
// WP Rocket Cache
if ( function_exists( 'rocket_clean_post' ) ) {
rocket_clean_post( $post_id );
}
// WP Super Cache
if ( function_exists( 'wp_cache_post_change' ) ) {
wp_cache_post_change( $post_id );
}
// W3 Total Cache
if ( function_exists( 'w3tc_flush_post' ) ) {
w3tc_flush_post( $post_id );
}
// Cache Enabler
if ( has_action( 'cache_enabler_clear_page_cache_by_post' ) ) {
do_action( 'cache_enabler_clear_page_cache_by_post', $post_id );
}
// Hummingbird
if ( has_action( 'wphb_clear_page_cache' ) ) {
do_action( 'wphb_clear_page_cache', $post_id );
}
// SG Optimizer
// Insufficient or hard-to-find documentation and if the
// developer cannot be bothered, neither can I.
// Breeze
// Insufficient or hard-to-find documentation and if the
// developer cannot be bothered, neither can I.
// WP Optimize
if (
class_exists( 'WPO_Page_Cache' ) &&
method_exists( 'WPO_Page_Cache', 'delete_single_post_cache' )
) {
WPO_Page_Cache::delete_single_post_cache( $post_id );
}
// W3 Fastest Cache
if ( function_exists( 'wpfc_clear_post_cache_by_id' ) ) {
wpfc_clear_post_cache_by_id( $post_id );
}
// NitroPack
// Insufficient or hard-to-find documentation and if the
// developer cannot be bothered, neither can I.
// Cached HTML partial
if ( FICTIONEER_ENABLE_PARTIAL_CACHING ) {
fictioneer_clear_cached_content( $post_id );
}
// Cached story card
if ( FICTIONEER_ENABLE_STORY_CARD_CACHING ) {
fictioneer_delete_cached_story_card( $post_id );
}
}
}
// =============================================================================
// LITESPEED CACHE
// =============================================================================
if ( ! function_exists( 'fictioneer_litespeed_running' ) ) {
/**
* Checks whether LiteSpeed Cache plugin is active
*
* @since 4.0.0
*
* @return boolean Either true (active) or false (inactive or not installed)
*/
function fictioneer_litespeed_running() {
return in_array(
'litespeed-cache/litespeed-cache.php',
apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
);
}
}
// =============================================================================
// PURGE RELEVANT CACHE(S) ON POST SAVE
// =============================================================================
if ( ! function_exists( 'fictioneer_purge_template_caches' ) ) {
/**
* Purges all posts with the given template template
*
* @since 5.5.2
*
* @param string $template The page template (without `.php`)
*/
function fictioneer_purge_template_caches( $template ) {
// Setup (this should normally only yield one page or none)
$pages = get_posts(
array(
'post_type' => 'page',
'numberposts' => -1,
'fields' => 'ids',
'meta_key' => '_wp_page_template',
'meta_value' => "{$template}.php",
'update_post_meta_cache' => false, // Improve performance
'update_post_term_cache' => false, // Improve performance
'no_found_rows' => true // Improve performance
)
);
// Purge
if ( $pages ) {
foreach ( $pages as $page_id ) {
fictioneer_purge_post_cache( $page_id );
}
}
}
}
if ( ! function_exists( 'fictioneer_refresh_post_caches' ) ) {
/**
* Purges relevant caches when a post is updated
*
* "There are only two hard things in Computer Science: cache invalidation and
* naming things" -- Phil Karlton.
*
* @since 5.0.0
*
* @param int $post_id Updated post ID.
*/
function fictioneer_refresh_post_caches( $post_id ) {
// Prevent multi-fire
if ( fictioneer_multi_save_guard( $post_id ) ) {
return;
}
// Purge all?
if ( get_option( 'fictioneer_purge_all_caches' ) ) {
fictioneer_purge_all_caches();
return;
}
// Get type
$post_type = get_post_type( $post_id );
if ( ! $post_type ) {
return;
}
// Start system action: unset user
$current_user_id = get_current_user_id();
wp_set_current_user( 0 );
// Remove actions to prevent infinite loops and multi-fire
fictioneer_toggle_refresh_hooks( false );
fictioneer_toggle_transient_purge_hooks( false );
fictioneer_toggle_update_tracker_hooks( false );
// Purge updated post
fictioneer_purge_post_cache( $post_id );
// Purge front page (if any)
$font_page_id = intval( get_option( 'page_on_front' ) ?: -1 );
if ( $font_page_id != $post_id && $font_page_id > 0 ) {
fictioneer_purge_post_cache( $font_page_id );
}
// Purge associated list pages
if ( in_array( $post_type, ['fcn_chapter', 'fcn_story'] ) ) {
fictioneer_purge_template_caches( 'chapters' );
fictioneer_purge_template_caches( 'stories' );
}
if ( $post_type == 'fcn_recommendation' ) {
fictioneer_purge_template_caches( 'recommendations' );
}
// Purge parent story (if any)...
if ( $post_type == 'fcn_chapter' ) {
$story_id = fictioneer_get_chapter_story_id( $post_id );
if ( ! empty( $story_id ) ) {
$chapters = fictioneer_get_story_chapter_ids( $story_id );
delete_post_meta( $story_id, 'fictioneer_story_data_collection' );
delete_post_meta( $story_id, 'fictioneer_story_chapter_index_html' );
fictioneer_purge_post_cache( $story_id );
// ... and associated chapters
if ( ! empty( $chapters ) ) {
foreach ( $chapters as $chapter_id ) {
fictioneer_purge_post_cache( $chapter_id );
}
}
}
}
// Purge associated chapters
if ( $post_type == 'fcn_story' ) {
$chapters = fictioneer_get_story_chapter_ids( $post_id );
if ( ! empty( $chapters ) ) {
foreach ( $chapters as $chapter_id ) {
fictioneer_purge_post_cache( $chapter_id );
}
}
}
// Purge all collections (cheapest option)
if ( $post_type != 'page' ) {
fictioneer_purge_template_caches( 'collections' );
$collections = get_posts(
array(
'post_type' => 'fcn_collection',
'numberposts' => -1,
'fields' => 'ids',
'update_post_meta_cache' => false, // Improve performance
'update_post_term_cache' => false, // Improve performance
'no_found_rows' => true // Improve performance
)
);
foreach ( $collections as $collection_id ) {
fictioneer_purge_post_cache( $collection_id );
}
}
// Purge relationships
if ( FICTIONEER_RELATIONSHIP_PURGE_ASSIST ) {
$registry = fictioneer_get_relationship_registry();
// Always purge...
foreach ( $registry['always'] as $key => $entry ) {
delete_post_meta( $key, 'fictioneer_schema' );
fictioneer_purge_post_cache( $key );
}
// Direct relationships
if ( isset( $registry[ $post_id ] ) ) {
foreach ( $registry[ $post_id ] as $key => $entry ) {
delete_post_meta( $key, 'fictioneer_schema' );
fictioneer_purge_post_cache( $key );
}
}
// Purge post relationships
$relation = false;
switch ( $post_type ) {
case 'post':
$relation = 'ref_posts';
break;
case 'fcn_chapter':
$relation = 'ref_chapters';
break;
case 'fcn_story':
$relation = 'ref_stories';
break;
case 'fcn_recommendation':
$relation = 'ref_recommendations';
break;
}
if ( $relation ) {
foreach ( $registry[ $relation ] as $key => $entry ) {
delete_post_meta( $key, 'fictioneer_schema' );
fictioneer_purge_post_cache( $key );
}
}
}
// Restore actions
fictioneer_toggle_refresh_hooks();
fictioneer_toggle_transient_purge_hooks();
fictioneer_toggle_update_tracker_hooks();
// End system action: restore user
wp_set_current_user( $current_user_id );
}
}
/**
* Add or remove actions for `fictioneer_refresh_post_caches`
*
* @since 5.5.2
*
* @param boolean $add Optional. Whether to add or remove the action. Default true.
*/
function fictioneer_toggle_refresh_hooks( $add = true ) {
$hooks = ['save_post', 'untrash_post', 'trashed_post', 'delete_post'];
if ( $add ) {
foreach ( $hooks as $hook ) {
add_action( $hook, 'fictioneer_refresh_post_caches', 20 );
}
} else {
foreach ( $hooks as $hook ) {
remove_action( $hook, 'fictioneer_refresh_post_caches', 20 );
}
}
}
if ( FICTIONEER_CACHE_PURGE_ASSIST && fictioneer_caching_active( 'purge_assist' ) ) {
fictioneer_toggle_refresh_hooks();
}
// =============================================================================
// RELATIONSHIP REGISTRY
//
// The relationship directory array is not fail-safe. Technically, it can happen
// that while the registry is pulled for updating by one post, it is also pulled
// by another, causing the last to override the first without the first's data.
// However, this is unlikely and not the end of the world.
//
// A possible solution would be to create a new database table for registry
// updates which is processed by a worker occasionally. Cannot be bothered tho.
// =============================================================================
/**
* Returns relationship registry from options table
*
* @since 5.0.0
*
* @return array The balanced array.
*/
function fictioneer_get_relationship_registry() {
// Setup
$registry = get_option( 'fictioneer_relationship_registry', [] );
$registry = is_array( $registry ) ? $registry : [];
// Important nodes
$nodes = ['ref_posts', 'ref_chapters', 'ref_stories', 'ref_recommendations', 'always'];
foreach ( $nodes as $node ) {
if ( ! isset( $registry[ $node ] ) ) {
$registry[ $node ] = [];
}
if ( ! is_array( $registry[ $node ] ) ) {
$registry[ $node ] = [];
}
}
// Return
return $registry;
}
/**
* Saves relationship registry to options table
*
* @since 5.0.0
*
* @param array $registry Current registry to override the stored option.
*
* @return array True if the value was updated, false otherwise.
*/
function fictioneer_save_relationship_registry( $registry ) {
return update_option( 'fictioneer_relationship_registry', $registry );
}
/**
* Remove relationships on delete
*
* @since 5.0.0
*
* @param int $post_id The deleted post ID.
*/
function fictioneer_delete_relationship( $post_id ) {
// Setup
$registry = fictioneer_get_relationship_registry();
// Remove node (if set)
unset( $registry[ $post_id ] );
// Remove references (if any)
foreach ( $registry as $key => $entry ) {
unset( $registry[ $key ][ $post_id ] );
}
unset( $registry['ref_posts'][ $post_id ] );
unset( $registry['ref_chapters'][ $post_id ] );
unset( $registry['ref_stories'][ $post_id ] );
unset( $registry['ref_recommendations'][ $post_id ] );
unset( $registry['always'][ $post_id ] );
// Update database
fictioneer_save_relationship_registry( $registry );
}
if ( FICTIONEER_RELATIONSHIP_PURGE_ASSIST ) {
add_action( 'delete_post', 'fictioneer_delete_relationship', 100 );
}
// =============================================================================
// TRACK CHAPTER & STORY UPDATES
// =============================================================================
if ( ! function_exists( 'fictioneer_track_chapter_and_story_updates' ) ) {
/**
* Updates Transients and storage options when a story or chapter is updated
*
* Whenever a story or chapter is saved, trashed, restored, or permanently
* deleted, this function will update or purge respective Transients and
* storage options to reflect the current state of content. This is mainly
* used for caching purposes and there is no harm if these values vanish.
*
* @since 4.7.0
*
* @param int $post_id Updated post ID.
*/
function fictioneer_track_chapter_and_story_updates( $post_id ) {
// Prevent multi-fire
if ( fictioneer_multi_save_guard( $post_id ) ) {
return;
}
// Get story ID from post or parent story (if any)
$post_type = get_post_type( $post_id ); // Not all hooks get the $post object!
$story_id = $post_type == 'fcn_story' ? $post_id : fictioneer_get_chapter_story_id( $post_id );
// Delete cached statistics for stories
delete_transient( 'fictioneer_stories_statistics' );
delete_transient( 'fictioneer_stories_total_word_count' );
// If there is a story...
if ( ! empty( $story_id ) ) {
// Decides when cached story/chapter data need to be refreshed (only used for Follows)
// Beware: This is an option, not a Transient!
update_option( 'fictioneer_story_or_chapter_updated_timestamp', time() * 1000 );
// Clear meta caches
delete_post_meta( $story_id, 'fictioneer_story_data_collection' );
delete_post_meta( $story_id, 'fictioneer_story_chapter_index_html' );
// Delete cached query results
fictioneer_delete_transients_like( "fictioneer_query_{$story_id}" );
// Refresh cached HTML output
delete_transient( 'fictioneer_story_chapter_list_html_' . $story_id );
}
}
}
/**
* Add or remove actions for `fictioneer_toggle_update_tracker_hooks`
*
* @since 5.5.2
*
* @param boolean $add Optional. Whether to add or remove the action. Default true.
*/
function fictioneer_toggle_update_tracker_hooks( $add = true ) {
$hooks = ['save_post', 'untrash_post', 'trashed_post', 'delete_post'];
if ( $add ) {
foreach ( $hooks as $hook ) {
add_action( $hook, 'fictioneer_track_chapter_and_story_updates' );
}
} else {
foreach ( $hooks as $hook ) {
remove_action( $hook, 'fictioneer_track_chapter_and_story_updates' );
}
}
}
fictioneer_toggle_update_tracker_hooks();
/**
* Rebuild story data collection after purge
*
* Note: This is only triggered for one story to avoid rebuilding the
* collections of ALL stories at once in case of a complete purge.
*
* @since 5.23.1
*
* @param int $post_id Updated post ID.
* @param WP_Post $post The post object.
*/
function fictioneer_rebuild_story_data_collection( $post_id, $post ) {
// Prevent multi-fire and check type
if (
fictioneer_multi_save_guard( $post_id ) ||
! in_array( $post->post_type, ['fcn_story', 'fcn_chapter'] )
) {
return;
}
// Story or chapter?
if ( $post->post_type === 'fcn_chapter' ) {
$story_id = fictioneer_get_chapter_story_id( $post_id );
if ( $story_id ) {
fictioneer_get_story_data( $story_id );
}
} else {
fictioneer_get_story_data( $post_id );
}
// Prevent chain reaction
remove_action( 'save_post', 'fictioneer_rebuild_story_data_collection', 999 );
}
if ( FICTIONEER_ENABLE_STORY_DATA_META_CACHE ) {
add_action( 'save_post', 'fictioneer_rebuild_story_data_collection', 999, 2 );
}
// =============================================================================
// PURGE CACHE TRANSIENTS
// =============================================================================
/**
* Purge layout-related Transients
*
* @since 5.25.0
*/
function fictioneer_delete_layout_transients() {
fictioneer_purge_nav_menu_transients();
fictioneer_purge_story_card_cache();
fictioneer_delete_transients_like( 'fictioneer_shortcode' );
fictioneer_delete_transients_like( 'fictioneer_taxonomy_submenu_' );
delete_transient( 'fictioneer_dynamic_scripts_version' );
}
/**
* Purge Transients used for caching when posts are updated
*
* @since 5.4.9
* @since 5.23.0 - Refactored to purge all shortcode Transients.
*
* @param int $post_id Updated post ID.
*/
function fictioneer_purge_transients_after_update( $post_id ) {
// Prevent multi-fire
if ( fictioneer_multi_save_guard( $post_id ) ) {
return;
}
// Menus
fictioneer_purge_nav_menu_transients();
// Shortcodes...
fictioneer_delete_transients_like( 'fictioneer_shortcode' );
}
/**
* Add or remove actions for `fictioneer_purge_transients_after_update`
*
* @since 5.5.2
*
* @param boolean $add Optional. Whether to add or remove the action. Default true.
*/
function fictioneer_toggle_transient_purge_hooks( $add = true ) {
$hooks = ['save_post', 'untrash_post', 'trashed_post', 'delete_post'];
if ( $add ) {
foreach ( $hooks as $hook ) {
add_action( $hook, 'fictioneer_purge_transients_after_update' );
}
} else {
foreach ( $hooks as $hook ) {
remove_action( $hook, 'fictioneer_purge_transients_after_update' );
}
}
}
fictioneer_toggle_transient_purge_hooks();
/**
* Purge nav menu Transients
*
* @since 5.6.0
*/
function fictioneer_purge_nav_menu_transients() {
delete_transient( 'fictioneer_main_nav_menu_html' );
delete_transient( 'fictioneer_footer_menu_html' );
delete_transient( 'fictioneer_mobile_nav_menu_html' );
fictioneer_delete_transients_like( 'fictioneer_taxonomy_submenu_' );
}
add_action( 'wp_update_nav_menu', 'fictioneer_purge_nav_menu_transients' );
// =============================================================================
// PARTIAL CACHING (THEME)
// =============================================================================
/**
* Generate random salt for cache-related hashes
*
* Note: Saves the salt to the option 'fictioneer_cache_salt'.
*
* @since 5.18.3
*
* @return string The generated salt.
*/
function fictioneer_generate_cache_salt() {
$salt = bin2hex( random_bytes( 32 / 2 ) );
update_option( 'fictioneer_cache_salt', $salt );
return $salt;
}
/**
* Get salt for cache-related hashes
*
* Note: Regenerated if no salt exists.
*
* @since 5.18.3
*
* @return string The salt.
*/
function fictioneer_get_cache_salt() {
return get_option( 'fictioneer_cache_salt' ) ?: fictioneer_generate_cache_salt();
}
/**
* Get static HTML of cached template partial
*
* @since 5.18.3
* @see get_template_directory()
*
* @param string|null $dir Optional. Directory path to override the default.
*
* @return bool True if the directory exists or has been created, false on failure.
*/
function fictioneer_create_html_cache_directory( $dir = null ) {
// Setup
$default_dir = fictioneer_get_theme_cache_dir( 'create_html_cache_directory' ) . '/html/';
$dir = $dir ?? $default_dir;
$result = true;
// Create cache directories if missing
if ( ! is_dir( $dir ) ) {
$result = mkdir( $dir, 0755, true );
}
// Hide files from index
if ( $result && ! file_exists( $dir . '/index.php' ) ) {
file_put_contents( $dir . '/index.php', "<?php\n// Silence is golden.\n" );
}
if ( $result && ! file_exists( $default_dir . '/index.php' ) ) {
file_put_contents( $default_dir . '/index.php', "<?php\n// Silence is golden.\n" );
}
// Add .htaccess to limit access
if ( $result && ! file_exists( $dir . '/.htaccess' ) ) {
file_put_contents(
$dir . '/.htaccess',
"<Files *>\n Order Allow,Deny\n Deny from all\n</Files>\n"
);
}
if ( $result && ! file_exists( $default_dir . '/.htaccess' ) ) {
file_put_contents(
$default_dir . '/.htaccess',
"<Files *>\n Order Allow,Deny\n Deny from all\n</Files>\n"
);
}
// Success or failure
return $result;
}
/**
* Get static HTML of cached template partial
*