-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathfancybox.php
More file actions
1271 lines (1072 loc) · 41.9 KB
/
Copy pathfancybox.php
File metadata and controls
1271 lines (1072 loc) · 41.9 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
/**
* Plugin Name: FancyBox for WordPress
* Plugin URI: https://wordpress.org/plugins/fancybox-for-wordpress/
* Description: Integrates <a href="http://fancyapps.com/fancybox/3/">FancyBox 3</a> into WordPress.
* Version: 3.4.1
* Author: Colorlib
* Author URI: https://colorlib.com/wp/
* Tested up to: 7.0
* Requires at least: 5.6
* License: GPLv3 or later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
* Requires PHP: 7.4
* Text Domain: fancybox-for-wordpress
* Domain Path: /languages
*
* Copyright 2008-2016 Janis Skarnelis https://twitter.com/moskis/
* Copyright 2016-2026 Colorlib support@colorlib.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
defined( 'ABSPATH' ) || exit;
/**
* Plugin Init
*/
// Constants
define( 'FBFW_VERSION', '3.4.1' );
define( 'FBFW_PATH', plugin_dir_path( __FILE__ ) );
define( 'FBFW_URL', plugin_dir_url( __FILE__ ) );
define( 'FBFW_PLUGIN_BASE', plugin_basename( __FILE__ ) );
define( 'FBFW_PREVIOUS_PLUGIN_VERSION', '3.0.14' );
define( 'FBFW_FILE_', __FILE__ );
define( 'FBFW_SLUG', 'fancybox-for-wordpress' );
// Historically declared unprefixed, which collides with any other plugin doing the
// same. Kept for backwards compatibility, but never redefined if someone won the race.
if ( ! defined( 'PLUGIN_NAME' ) ) {
define( 'PLUGIN_NAME', FBFW_SLUG );
}
include 'class-fancybox-review.php';
/**
* Describes every option: its default and how it must be normalized.
*
* This single table drives the defaults, the save-time sanitizer and the read-time
* normalizer, so a value can never reach the page in a shape the output code did
* not expect.
*
* Types:
* - toggle : stored as 'on' or '' (any legacy truthy value normalizes to 'on')
* - color : #rgb / #rrggbb, falls back to the default when invalid
* - int : absint, clamped to 'max'
* - float : clamped between 'min' and 'max'
* - choice : must be one of 'choices'
* - js : raw JavaScript supplied by an administrator
*
* @since 3.4.0
*
* @return array<string, array<string, mixed>>
*/
function mfbfw_option_schema() {
static $schema = null;
if ( null !== $schema ) {
return $schema;
}
$schema = array(
// Appearance.
'border' => array( 'type' => 'toggle', 'default' => '' ),
'borderColor' => array( 'type' => 'color', 'default' => '#BBBBBB' ),
'paddingColor' => array( 'type' => 'color', 'default' => '#FFFFFF' ),
'padding' => array( 'type' => 'int', 'default' => 10, 'max' => 200 ),
'overlayShow' => array( 'type' => 'toggle', 'default' => 'on' ),
'overlayColor' => array( 'type' => 'color', 'default' => '#666666' ),
'overlayOpacity' => array( 'type' => 'float', 'default' => 0.3, 'min' => 0, 'max' => 1 ),
'titleShow' => array( 'type' => 'toggle', 'default' => 'on' ),
'captionShow' => array( 'type' => 'toggle', 'default' => '' ),
'titlePosition' => array( 'type' => 'choice', 'default' => 'inside', 'choices' => array( 'inside', 'over', 'float', 'outside' ) ),
'titleColor' => array( 'type' => 'color', 'default' => '#333333' ),
'showNavArrows' => array( 'type' => 'toggle', 'default' => 'on' ),
'disableOnMobile' => array( 'type' => 'toggle', 'default' => '' ),
'titleSize' => array( 'type' => 'int', 'default' => 14, 'max' => 200 ),
'showCloseButton' => array( 'type' => 'toggle', 'default' => '' ),
'showToolbar' => array( 'type' => 'toggle', 'default' => 'on' ),
// Animations.
'zoomOpacity' => array( 'type' => 'toggle', 'default' => 'on' ),
'zoomSpeedIn' => array( 'type' => 'int', 'default' => 500, 'max' => 10000 ),
'zoomSpeedChange' => array( 'type' => 'int', 'default' => 300, 'max' => 10000 ),
'transitionIn' => array( 'type' => 'choice', 'default' => 'fade', 'choices' => array( 'fade', 'zoom', 'zoom-in-out', 'none' ) ),
'transitionEffect' => array( 'type' => 'choice', 'default' => 'fade', 'choices' => array( 'false', 'fade', 'slide', 'circular', 'tube', 'zoom-in-out', 'rotate' ) ),
// Behaviour.
'hideOnOverlayClick' => array( 'type' => 'toggle', 'default' => 'on' ),
'hideOnContentClick' => array( 'type' => 'toggle', 'default' => '' ),
'zoomOnClick' => array( 'type' => 'toggle', 'default' => '' ),
'enableEscapeButton' => array( 'type' => 'toggle', 'default' => 'on' ),
'cyclic' => array( 'type' => 'toggle', 'default' => '' ),
'mouseWheel' => array( 'type' => 'toggle', 'default' => '' ),
'disableWoocommercePages' => array( 'type' => 'toggle', 'default' => '' ),
'disableWoocommerceProducts' => array( 'type' => 'toggle', 'default' => '' ),
'exclude_pdf' => array( 'type' => 'toggle', 'default' => '' ),
// Gallery type.
'galleryType' => array( 'type' => 'choice', 'default' => 'all', 'choices' => array( 'all', 'post', 'none', 'single_gutenberg_block', 'custom' ) ),
'customExpression' => array( 'type' => 'js', 'default' => 'jQuery(thumbnails).attr("data-fancybox","gallery").getTitle();' ),
// Misc.
'autoDimensions' => array( 'type' => 'toggle', 'default' => 'on' ),
'frameWidth' => array( 'type' => 'int', 'default' => 560, 'max' => 10000 ),
'frameHeight' => array( 'type' => 'int', 'default' => 340, 'max' => 10000 ),
'loadAtFooter' => array( 'type' => 'toggle', 'default' => '' ),
'callbackEnable' => array( 'type' => 'toggle', 'default' => '' ),
'callbackOnStart' => array( 'type' => 'js', 'default' => 'function() { alert("Start!"); }' ),
'callbackOnCancel' => array( 'type' => 'js', 'default' => 'function() { alert("Cancel!"); }' ),
'callbackOnComplete' => array( 'type' => 'js', 'default' => 'function() { alert("Complete!"); }' ),
'callbackOnCleanup' => array( 'type' => 'js', 'default' => 'function() { alert("CleanUp!"); }' ),
'callbackOnClose' => array( 'type' => 'js', 'default' => 'function() { alert("Close!"); }' ),
'nojQuery' => array( 'type' => 'toggle', 'default' => '' ),
'extraCallsEnable' => array( 'type' => 'toggle', 'default' => '' ),
'extraCallsData' => array( 'type' => 'js', 'default' => '' ),
'uninstall' => array( 'type' => 'toggle', 'default' => '' ),
/*
* Regenerated on every request by mfbfw_title_copy_js(); the stored value is
* ignored. Kept in the schema so upgrades from <3.4.0 do not lose the row.
*/
'copyTitleFunction' => array( 'type' => 'js', 'default' => '' ),
/*
* Legacy keys from the FancyBox 1.x era. They have no UI any more, but sites
* upgraded from those versions still carry them and their CSS is still
* honoured, so they must survive sanitization.
*/
'borderRadius' => array( 'type' => 'int', 'default' => null, 'max' => 200, 'optional' => true ),
'borderRadiusInner' => array( 'type' => 'int', 'default' => null, 'max' => 200, 'optional' => true ),
'shadowSize' => array( 'type' => 'int', 'default' => null, 'max' => 200, 'optional' => true ),
'shadowOffset' => array( 'type' => 'int', 'default' => null, 'max' => 200, 'optional' => true ),
'shadowOpacity' => array( 'type' => 'float', 'default' => null, 'min' => 0, 'max' => 1, 'optional' => true ),
'easing' => array( 'type' => 'toggle', 'default' => null, 'optional' => true ),
'wheel' => array( 'type' => 'toggle', 'default' => null, 'optional' => true ),
);
return $schema;
}
/**
* Store default settings in an array
*/
function mfbfw_defaults() {
$defaults = array();
foreach ( mfbfw_option_schema() as $key => $spec ) {
if ( ! empty( $spec['optional'] ) ) {
continue;
}
$defaults[ $key ] = $spec['default'];
}
// Historically stored as ints; keep them strings so a strict-comparing theme
// that predates 3.4.0 keeps working.
foreach ( array( 'padding', 'titleSize', 'zoomSpeedIn', 'zoomSpeedChange', 'frameWidth', 'frameHeight' ) as $key ) {
$defaults[ $key ] = (string) $defaults[ $key ];
}
$defaults['overlayOpacity'] = '0.3';
return $defaults;
}
/**
* Validate a hex colour without depending on load order of wp-admin includes.
*
* @since 3.4.0
*
* @param mixed $color Raw value.
* @param string $fallback Returned when $color is not a valid hex colour.
* @return string
*/
function mfbfw_sanitize_hex_color( $color, $fallback = '' ) {
if ( ! is_scalar( $color ) ) {
return $fallback;
}
$color = trim( (string) $color );
if ( '' === $color ) {
return $fallback;
}
if ( '#' !== $color[0] ) {
$color = '#' . $color;
}
return preg_match( '/^#([A-Fa-f0-9]{3}){1,2}$/', $color ) ? $color : $fallback;
}
/**
* Normalize a checkbox-style option to 'on' or ''.
*
* Older versions stored arbitrary truthy values here (hideOnOverlayClick held a
* whole JavaScript function), so anything non-empty counts as enabled.
*
* @since 3.4.0
*
* @param mixed $value Raw value.
* @return string
*/
function mfbfw_normalize_toggle( $value ) {
if ( is_string( $value ) ) {
$value = trim( $value );
if ( '' === $value || '0' === $value || 'off' === $value || 'false' === $value ) {
return '';
}
return 'on';
}
return $value ? 'on' : '';
}
/**
* Coerce one raw option value into the shape its schema entry promises.
*
* @since 3.4.0
*
* @param mixed $value Raw value.
* @param array $spec Schema entry.
* @return mixed
*/
function mfbfw_normalize_value( $value, array $spec ) {
switch ( $spec['type'] ) {
case 'toggle':
return mfbfw_normalize_toggle( $value );
case 'color':
return mfbfw_sanitize_hex_color( $value, (string) $spec['default'] );
case 'int':
// Falling back to the default rather than to absint()'s 0 keeps a garbled
// value from silently disabling animations or collapsing the padding.
$value = is_numeric( $value ) ? absint( $value ) : (int) $spec['default'];
if ( isset( $spec['max'] ) ) {
$value = min( $value, (int) $spec['max'] );
}
return $value;
case 'float':
$value = is_numeric( $value ) ? (float) $value : (float) $spec['default'];
if ( isset( $spec['min'] ) ) {
$value = max( $value, (float) $spec['min'] );
}
if ( isset( $spec['max'] ) ) {
$value = min( $value, (float) $spec['max'] );
}
return $value;
case 'choice':
return in_array( $value, $spec['choices'], true ) ? $value : $spec['default'];
case 'js':
return is_scalar( $value ) ? wp_strip_all_tags( (string) $value ) : '';
}
return $value;
}
/**
* Return a complete, normalized settings array.
*
* Every consumer goes through here, so output code can rely on every key existing
* and holding a value of the expected type. Previously the raw option was used
* directly, which produced a wall of "undefined array key" warnings on PHP 8 (and a
* fatal when the row was not an array at all).
*
* @since 3.4.0
*
* @param mixed $raw Optional raw settings to normalize instead of reading the option.
* @return array
*/
function mfbfw_get_settings( $raw = null ) {
static $cache = null;
$use_cache = ( null === $raw );
if ( $use_cache && null !== $cache ) {
return $cache;
}
if ( null === $raw ) {
$raw = get_option( 'mfbfw' );
}
// A corrupted row (empty string, bool, serialized scalar) used to fatal here.
if ( ! is_array( $raw ) ) {
$raw = array();
}
$schema = mfbfw_option_schema();
$settings = array();
foreach ( $schema as $key => $spec ) {
if ( array_key_exists( $key, $raw ) ) {
$settings[ $key ] = mfbfw_normalize_value( $raw[ $key ], $spec );
} elseif ( empty( $spec['optional'] ) ) {
$settings[ $key ] = $spec['default'];
}
}
// Preserve unknown keys so third-party code that stashes data here keeps working.
foreach ( $raw as $key => $value ) {
if ( ! isset( $schema[ $key ] ) ) {
$settings[ $key ] = $value;
}
}
/**
* Filters the resolved FancyBox settings.
*
* @since 3.4.0
*
* @param array $settings Normalized settings.
*/
$settings = apply_filters( 'mfbfw_settings', $settings );
if ( $use_cache ) {
$cache = $settings;
}
return $settings;
}
/**
* Whether a checkbox-style option is enabled.
*
* @since 3.4.0
*
* @param string $key Option key.
* @param array|null $settings Optional settings array.
* @return bool
*/
function mfbfw_is_on( $key, $settings = null ) {
if ( ! is_array( $settings ) ) {
$settings = mfbfw_get_settings();
}
return isset( $settings[ $key ] ) && '' !== $settings[ $key ] && $settings[ $key ];
}
// Populate the historical globals. Third-party code reads $mfbfw directly, so it
// stays available - but it now always holds a complete array.
$mfbfw = mfbfw_get_settings();
$mfbfw_version = get_option( 'mfbfw_active_version' );
/**
* Create or migrate the stored settings.
*
* Runs on plugins_loaded rather than at include time so the write happens once WordPress
* is fully bootstrapped, and on the front end as well as in wp-admin. The old
* admin-only guard meant a site whose first request after an update was a front-end
* hit ran the whole page render against a settings array missing every new key.
*
* @since 3.4.0
*/
function mfbfw_maybe_upgrade_settings() {
$stored = get_option( 'mfbfw' );
$version = get_option( 'mfbfw_active_version' );
if ( ! is_array( $stored ) ) {
update_option( 'mfbfw', mfbfw_defaults() );
update_option( 'mfbfw_active_version', FBFW_VERSION );
return;
}
if ( $version && version_compare( $version, FBFW_VERSION, '>=' ) ) {
return;
}
// Existing values win; only genuinely new keys pick up a default.
update_option( 'mfbfw', $stored + mfbfw_defaults() );
update_option( 'mfbfw_active_version', FBFW_VERSION );
}
add_action( 'plugins_loaded', 'mfbfw_maybe_upgrade_settings' );
/**
* If requested, when plugin is deactivated, remove settings
*/
function mfbfw_deactivate() {
if ( mfbfw_is_on( 'uninstall' ) ) {
delete_option( 'mfbfw' );
delete_option( 'mfbfw_active_version' );
delete_option( 'mfbfw-rate-time' );
}
}
register_deactivation_hook( __FILE__, 'mfbfw_deactivate' );
/**
* Whether the lightbox should run for the current request.
*
* @since 3.4.0
*
* @return bool
*/
function mfbfw_is_enabled() {
$enabled = true;
if ( mfbfw_is_on( 'disableOnMobile' ) && wp_is_mobile() ) {
$enabled = false;
}
$woocommerce = fancy_check_if_woocommerce();
if ( 'product' === $woocommerce && mfbfw_is_on( 'disableWoocommerceProducts' ) ) {
$enabled = false;
}
if ( 'shop_page' === $woocommerce && mfbfw_is_on( 'disableWoocommercePages' ) ) {
$enabled = false;
}
/**
* Filters whether FancyBox loads on the current request.
*
* @since 3.4.0
*
* @param bool $enabled Whether to load.
*/
return (bool) apply_filters( 'mfbfw_is_enabled', $enabled );
}
/**
* Path suffix for minified assets, unless SCRIPT_DEBUG asks for readable sources.
*
* @since 3.4.0
*
* @return string
*/
function mfbfw_asset_suffix() {
return ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
}
/**
* Load FancyBox JS with jQuery and
*/
function mfbfw_enqueue_scripts() {
if ( ! mfbfw_is_enabled() ) {
return;
}
$settings = mfbfw_get_settings();
$footer = mfbfw_is_on( 'loadAtFooter', $settings );
$suffix = mfbfw_asset_suffix();
// Troubleshooting switch: skip the jQuery dependency when it is loaded elsewhere.
$deps = mfbfw_is_on( 'nojQuery', $settings ) ? array( 'fbfw-purify' ) : array( 'jquery', 'fbfw-purify' );
wp_register_script( 'fbfw-purify', FBFW_URL . 'assets/js/purify' . $suffix . '.js', array(), FBFW_VERSION, $footer );
wp_register_script( 'fancybox-for-wp', FBFW_URL . 'assets/js/jquery.fancybox' . $suffix . '.js', $deps, FBFW_VERSION, $footer );
wp_enqueue_script( 'fancybox-for-wp' );
wp_register_style( 'fancybox-for-wp', FBFW_URL . 'assets/css/fancybox' . $suffix . '.css', array(), FBFW_VERSION );
wp_enqueue_style( 'fancybox-for-wp' );
}
add_action( 'wp_enqueue_scripts', 'mfbfw_enqueue_scripts' );
/**
* Build the inline stylesheet from the stored settings.
*
* Every interpolated value has already been through the schema normalizer, so
* colours are known-good hex and sizes are integers. That closes the CSS injection
* that `esc_html()` did not - it only blocks `<`, so a value like
* `blue}body{display:none}` used to escape its own declaration block.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return string
*/
function mfbfw_build_css( array $s ) {
$padding_color = $s['paddingColor'];
$title_color = $s['titleColor'];
$position = $s['titlePosition'];
$title_inside = ( 'inside' === $position );
$rules = array();
$rules[] = '.fancybox-slide--image .fancybox-content{background-color:' . $padding_color . '}';
if ( 'inside' === $position || 'over' === $position ) {
$rules[] = 'div.fancybox-caption{display:none !important;}';
}
$rules[] = 'img.fancybox-image{border-width:' . $s['padding'] . 'px;border-color:' . $padding_color . ';border-style:solid;}';
if ( mfbfw_is_on( 'overlayShow', $s ) ) {
$rules[] = 'div.fancybox-bg{background-color:' . mfbfw_hex_to_rgba( $s['overlayColor'], $s['overlayOpacity'] ) . ';opacity:1 !important;}';
} else {
$rules[] = 'div.fancybox-bg{background:transparent !important;}';
}
$rules[] = 'div.fancybox-content{border-color:' . $padding_color . '}';
if ( $title_inside ) {
$rules[] = 'div#fancybox-title{background-color:' . $padding_color . '}';
$rules[] = 'div#fancybox-title-inside{color:' . $title_color . '}';
}
$rules[] = 'div.fancybox-content{background-color:' . $padding_color
. ( mfbfw_is_on( 'border', $s ) ? ';border:1px solid ' . $s['borderColor'] : '' ) . '}';
// Legacy FancyBox 1.x keys, still honoured for sites that carry them.
if ( isset( $s['borderRadius'] ) ) {
$rules[] = 'div.fancybox-content{border-radius:' . (int) $s['borderRadius'] . 'px}';
}
if ( isset( $s['borderRadiusInner'] ) ) {
$rules[] = 'img#fancybox-img{border-radius:' . (int) $s['borderRadiusInner'] . 'px}';
}
if ( isset( $s['shadowSize'], $s['shadowOffset'], $s['shadowOpacity'] ) ) {
$rules[] = 'div.fancybox-content{box-shadow:0 ' . (int) $s['shadowOffset'] . 'px ' . (int) $s['shadowSize']
. 'px rgba(0,0,0,' . (float) $s['shadowOpacity'] . ')}';
}
if ( mfbfw_is_on( 'titleShow', $s ) ) {
$rules[] = 'div.fancybox-caption p.caption-title{display:inline-block}';
} else {
$rules[] = 'div.fancybox-custom-caption p.caption-title{display:none}div.fancybox-caption{display:none;}';
}
/*
* With titlePosition inside/over the visible caption is the .fancybox-custom-caption
* that afterLoad appends into .fancybox-content, while div.fancybox-caption is
* hidden. Styling only the latter meant the Title size setting had no effect at
* all in the two positions that are actually used. See issue #87.
*/
$rules[] = 'div.fancybox-caption p.caption-title,div.fancybox-content p.caption-title{font-size:' . $s['titleSize'] . 'px}';
$rules[] = 'div.fancybox-caption p.caption-title{color:' . ( $title_inside ? $title_color : '#fff' ) . '}';
$rules[] = 'div.fancybox-caption{color:' . $title_color . '}';
if ( $title_inside ) {
$rules[] = 'div.fancybox-caption p.caption-title{background:#fff;width:auto;padding:10px 30px;}'
. 'div.fancybox-content p.caption-title{color:' . $title_color . ';margin:0;padding:5px 0;}';
} elseif ( 'float' === $position ) {
$rules[] = 'div.fancybox-caption p.caption-title{background:#fff;color:#000;padding:10px 30px;width:auto;}';
} else {
$rules[] = 'div.fancybox-caption{position:relative;max-width:50%;margin:0 auto;min-width:480px;padding:15px;}'
. 'div.fancybox-caption p.caption-title{position:relative;left:0;right:0;margin:0 auto;top:0;color:#fff;}';
}
if ( mfbfw_is_on( 'showCloseButton', $s ) ) {
$rules[] = 'body.fancybox-active .fancybox-container .fancybox-stage .fancybox-content .fancybox-close-small{display:block;}';
}
return implode( "\n\t", $rules );
}
/**
* JavaScript that copies image titles (and block captions) onto their parent link.
*
* The stored `copyTitleFunction` option has been ignored since 3.2.6 - it was
* unconditionally overwritten before use - so it is generated here instead of
* pretending to be configurable.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return string
*/
function mfbfw_title_copy_js( array $s ) {
/*
* The collected text goes to data-fbfw-title, not to the link's title attribute.
* Writing it to title made the browser show a native tooltip on every thumbnail
* hover - text the visitor never asked for and could not dismiss. See issue #84.
* A title the author set themselves is left alone and still used as a fallback.
*/
if ( mfbfw_is_on( 'captionShow', $s ) ) {
return <<<'JS'
jQuery("a[data-fancybox]").each(function () {
var $link = jQuery(this);
if ($link.attr("data-fbfw-title") !== undefined) { return; }
var title = $link.children("img").attr("title");
if (title) { $link.attr("data-fbfw-title", title); }
});
JS;
}
return <<<'JS'
jQuery("a[data-fancybox]").each(function () {
var $link = jQuery(this);
if ($link.attr("data-fbfw-title") !== undefined) { return; }
var title = $link.children("img").attr("title") || '';
var figCaptionHtml = $link.next("figcaption").html() || '';
var processedCaption = figCaptionHtml;
if (figCaptionHtml.length && typeof DOMPurify === 'function') {
processedCaption = DOMPurify.sanitize(figCaptionHtml, {USE_PROFILES: {html: true}});
} else if (figCaptionHtml.length) {
processedCaption = jQuery("<div>").text(figCaptionHtml).html();
}
var newTitle = title;
if (processedCaption.length) {
newTitle = title.length ? title + " " + processedCaption : processedCaption;
}
if (newTitle.length) { $link.attr("data-fbfw-title", newTitle); }
});
JS;
}
/**
* The `caption` callback handed to FancyBox.
*
* Keeps the DOMPurify path introduced in 3.3.7: markup is sanitized when DOMPurify
* is present and hard-escaped through jQuery's text() when it is not.
*
* @since 3.4.0
*
* @return string
*/
function mfbfw_caption_js() {
return <<<'JS'
function (instance, item) {
var $link = jQuery(this);
// data-fbfw-title is what getTitle() collects; a hand-written title attribute
// still works as a fallback for anyone relying on the old behaviour.
var title = $link.attr("data-fbfw-title");
if (title === undefined) { title = $link.attr("title"); }
if (title === undefined && $link.context) { title = $link.context.title; }
title = title || '';
var caption = $link.data('caption') || '';
if (item.type === 'image' && title.length) {
caption = (caption.length ? caption + '<br />' : '') + '<p class="caption-title">' + jQuery("<div>").text(title).html() + '</p>';
}
if (typeof DOMPurify === "function" && caption.length) {
return DOMPurify.sanitize(caption, {USE_PROFILES: {html: true}});
}
return jQuery("<div>").text(caption).html();
}
JS;
}
/**
* The `afterLoad` callback, which paints the caption inside or over the image.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return string
*/
function mfbfw_after_load_js( array $s ) {
$position = $s['titlePosition'];
if ( 'inside' !== $position && 'over' !== $position ) {
return 'function () {}';
}
$style = ( 'inside' === $position )
? 'position:absolute;left:0;right:0;color:#000;margin:0 auto;bottom:0;text-align:center;background-color:' . $s['paddingColor'] . ';'
: 'position:absolute;left:0;right:0;color:#000;padding-top:10px;bottom:0;margin:0 auto;text-align:center;';
$class = ( 'inside' === $position ) ? 'fancybox-custom-caption inside-caption' : 'fancybox-custom-caption';
return sprintf(
<<<'JS'
function (instance, current) {
var captionContent = current.opts.caption || '';
var sanitized = '';
if (typeof DOMPurify === 'function' && captionContent.length) {
sanitized = DOMPurify.sanitize(captionContent, {USE_PROFILES: {html: true}});
} else if (captionContent.length) {
sanitized = jQuery("<div>").text(captionContent).html();
}
if (sanitized.length) {
current.$content.append(jQuery('<div class="%1$s" style="%2$s"></div>').html(sanitized));
}
}
JS,
esc_js( $class ),
esc_js( $style )
);
}
/**
* The selector that decides which links become lightbox links.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return string
*/
function mfbfw_thumbnail_selector_js( array $s ) {
$extensions = mfbfw_is_on( 'exclude_pdf', $s )
? 'jpe?g|png|gif|mp4|webp|bmp'
: 'jpe?g|png|gif|mp4|webp|bmp|pdf';
return sprintf(
'jQuery("a:has(img)").not(".nolightbox").not(".envira-gallery-link").not(".ngg-simplelightbox").filter(function () {'
. ' return /\.(%s)(\?[^/]*)*$/i.test(jQuery(this).attr("href")); })',
$extensions
);
}
/**
* The JavaScript that tags links with their gallery grouping.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return string
*/
function mfbfw_gallery_js( array $s ) {
switch ( $s['galleryType'] ) {
case 'post':
return <<<'JS'
if (fbfwIsSingular) {
thumbnails.addClass("fancyboxforwp").attr("data-fancybox", "gallery").getTitle();
iframeLinks.attr({"data-fancybox": "gallery"}).getTitle();
} else {
var posts = jQuery(".post");
posts.each(function () {
var idx = posts.index(this);
jQuery(this).find(thumbnails).addClass("fancyboxforwp").attr("data-fancybox", "gallery" + idx).attr("rel", "fancybox" + idx).getTitle();
jQuery(this).find(iframeLinks).attr({"data-fancybox": "gallery" + idx}).attr("rel", "fancybox" + idx).getTitle();
});
}
JS;
case 'none':
return <<<'JS'
thumbnails.each(function () {
var rel = jQuery(this).attr("rel");
var imgTitle = jQuery(this).children("img").attr("title");
jQuery(this).addClass("fancyboxforwp").attr("data-fancybox", rel);
if (imgTitle) { jQuery(this).attr("data-fbfw-title", imgTitle); }
});
iframeLinks.each(function () {
var rel = jQuery(this).attr("rel");
var imgTitle = jQuery(this).children("img").attr("title");
jQuery(this).attr({"data-fancybox": rel});
if (imgTitle) { jQuery(this).attr("data-fbfw-title", imgTitle); }
});
JS;
case 'single_gutenberg_block':
/*
* WordPress 5.9 moved the gallery block from `ul.wp-block-gallery` to
* `figure.wp-block-gallery.has-nested-images`, so the old element-qualified
* selectors matched nothing on any modern install. The fallback branch also
* tested a jQuery object for truthiness, which is always true.
*/
return <<<'JS'
var galleryBlocks = jQuery(".wp-block-gallery");
if (!galleryBlocks.length) {
galleryBlocks = jQuery(".blocks-gallery-grid");
}
galleryBlocks.each(function () {
var idx = galleryBlocks.index(this);
jQuery(this).find(thumbnails).addClass("fancyboxforwp").attr("data-fancybox", "gallery" + idx).attr("rel", "fancybox" + idx).getTitle();
jQuery(this).find(iframeLinks).attr({"data-fancybox": "gallery" + idx}).attr("rel", "fancybox" + idx).getTitle();
});
JS;
case 'custom':
return "\t/* Custom Expression */\n\t" . html_entity_decode( $s['customExpression'] );
case 'all':
default:
return <<<'JS'
thumbnails.addClass("fancyboxforwp").attr("data-fancybox", "gallery").getTitle();
iframeLinks.attr({"data-fancybox": "gallery"}).getTitle();
JS;
}
}
/**
* Assemble the option object passed to fancyboxforwp().
*
* Scalar options are JSON encoded rather than hand-interpolated. Previously
* `animationDuration` was written unquoted straight from the option value, so any
* value that skipped the sanitizer became executable JavaScript.
*
* @since 3.4.0
*
* @param array $s Normalized settings.
* @return array{json: string, functions: array<string, string>}
*/
function mfbfw_build_options( array $s ) {
$scalar = array(
'loop' => mfbfw_is_on( 'cyclic', $s ),
'smallBtn' => mfbfw_is_on( 'showCloseButton', $s ),
'zoomOpacity' => mfbfw_is_on( 'zoomOpacity', $s ) ? 'auto' : false,
'animationEffect' => $s['transitionIn'],
'animationDuration' => (int) $s['zoomSpeedIn'],
'transitionEffect' => $s['transitionEffect'],
'transitionDuration' => (int) $s['zoomSpeedChange'],
'overlayShow' => mfbfw_is_on( 'overlayShow', $s ),
'overlayOpacity' => (float) $s['overlayOpacity'],
'titleShow' => mfbfw_is_on( 'titleShow', $s ),
'titlePosition' => $s['titlePosition'],
'keyboard' => mfbfw_is_on( 'enableEscapeButton', $s ),
'showCloseButton' => mfbfw_is_on( 'showCloseButton', $s ),
'arrows' => mfbfw_is_on( 'showNavArrows', $s ),
'clickContent' => mfbfw_is_on( 'hideOnContentClick', $s ) ? 'close' : false,
'clickSlide' => mfbfw_is_on( 'hideOnOverlayClick', $s ) ? 'close' : false,
'wheel' => mfbfw_is_on( 'mouseWheel', $s ),
'toolbar' => mfbfw_is_on( 'showToolbar', $s ),
'preventCaptionOverlap' => true,
);
if ( ! mfbfw_is_on( 'autoDimensions', $s ) ) {
$scalar['width'] = (int) $s['frameWidth'];
$scalar['height'] = (int) $s['frameHeight'];
}
$mobile_content = mfbfw_is_on( 'hideOnContentClick', $s ) ? '"close"' : '"toggleControls"';
$mobile_slide = mfbfw_is_on( 'hideOnOverlayClick', $s ) ? '"close"' : '"toggleControls"';
$callbacks_on = mfbfw_is_on( 'callbackEnable', $s );
$callback = static function ( $key ) use ( $s, $callbacks_on ) {
if ( $callbacks_on && ! empty( $s[ $key ] ) ) {
return html_entity_decode( $s[ $key ] );
}
return 'function () {}';
};
if ( $callbacks_on && ! empty( $s['callbackOnComplete'] ) ) {
$after_show = html_entity_decode( $s['callbackOnComplete'] );
} elseif ( mfbfw_is_on( 'zoomOnClick', $s ) ) {
/*
* Namespaced and rebound each time, otherwise every slide stacked another
* click handler on the same image element.
*
* Releasing a pan also fires a click, which zoomed the image straight back
* out mid-drag. Compare the press and release coordinates and treat anything
* that moved more than a few pixels as a drag, not a click. See issue #105.
*/
$after_show = <<<'JS'
function (instance) {
var startX = 0, startY = 0;
jQuery(".fancybox-image")
.off(".fbfwZoom")
.on("pointerdown.fbfwZoom mousedown.fbfwZoom", function (e) {
startX = e.clientX; startY = e.clientY;
})
.on("click.fbfwZoom", function (e) {
if (Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5) { return; }
instance.isScaledDown() ? instance.scaleToActual() : instance.scaleToFit();
});
}
JS;
} else {
$after_show = 'function () {}';
}
$functions = array(
'mobile' => sprintf(
'{ clickContent: function (current) { return current.type === "image" ? %s : false; },'
. ' clickSlide: function (current) { return current.type === "image" ? %s : "close"; } }',
$mobile_content,
$mobile_slide
),
'onInit' => $callback( 'callbackOnStart' ),
'onDeactivate' => $callback( 'callbackOnCancel' ),
'beforeClose' => $callback( 'callbackOnCleanup' ),
'afterShow' => $after_show,
'afterClose' => $callback( 'callbackOnClose' ),
'caption' => mfbfw_caption_js(),
'afterLoad' => mfbfw_after_load_js( $s ),
);
return array(
'json' => wp_json_encode( $scalar ),
'functions' => $functions,
);
}
/**
* Print inline styles and load FancyBox with the selected settings
*/
function mfbfw_init() {
if ( ! mfbfw_is_enabled() ) {
return;
}
global $mfbfw;
$s = mfbfw_get_settings( is_array( $mfbfw ) ? $mfbfw : null );
$options = mfbfw_build_options( $s );
$assignments = '';
foreach ( $options['functions'] as $name => $body ) {
$assignments .= sprintf( "\t\tfbfwOptions.%s = %s;\n", $name, $body );
}
/*
* When disableOnMobile is on, the server-side check in mfbfw_enqueue_scripts()
* already skipped the assets - but a full-page cache can serve a desktop-rendered
* page to a phone, so the guard is repeated in the browser.
*/
$mobile_guard = mfbfw_is_on( 'disableOnMobile', $s )
? "\t\tif (window.matchMedia && window.matchMedia('(max-width: 767px)').matches) { return; }\n"
: '';
$extra_calls = ( mfbfw_is_on( 'extraCallsEnable', $s ) && ! empty( $s['extraCallsData'] ) )
? "\t\t/* Extra Calls */\n\t\t" . html_entity_decode( $s['extraCallsData'] ) . "\n"
: '';
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS and JS are
// assembled from schema-normalized values above; see mfbfw_build_css()/mfbfw_build_options().
?>
<!-- Fancybox for WordPress v<?php echo esc_html( FBFW_VERSION ); ?> -->
<style type="text/css">
<?php echo mfbfw_build_css( $s ); ?>
</style>
<script type="text/javascript">
(function () {
if (typeof window.jQuery === 'undefined') { return; }
jQuery(function () {
<?php echo $mobile_guard; ?>
var fbfwIsSingular = <?php echo is_singular() ? 'true' : 'false'; ?>;
// Copy the title of every IMG tag onto its parent A so FancyBox can show it.
jQuery.fn.getTitle = function () {
<?php echo mfbfw_title_copy_js( $s ); ?>
return this;
};
var fbfwOptions = <?php echo $options['json']; ?>;
<?php echo $assignments; ?>
// A dialog needs an accessible name; FancyBox 3 ships role="dialog" with
// none, which fails WCAG 4.1.2 for screen reader users. See issue #104.
jQuery(document).on('onInit.fb', function (e, instance) {
if (instance && instance.$refs && instance.$refs.container) {
instance.$refs.container.attr({
'aria-modal': 'true',
'aria-label': <?php echo wp_json_encode( __( 'Image lightbox', 'fancybox-for-wordpress' ) ); ?>
});
}
});
function fbfwBind() {
var thumbnails = <?php echo mfbfw_thumbnail_selector_js( $s ); ?>;
// Anything that is not an image, video or PDF opens in an iframe.
var iframeLinks = jQuery('.fancyboxforwp').filter(function () {
return !/\.(jpe?g|png|gif|mp4|webp|bmp|pdf)(\?[^/]*)*$/i.test(jQuery(this).attr('href'));
}).filter(function () {
return !/vimeo|youtube/i.test(jQuery(this).attr('href'));
});
iframeLinks.attr({"data-type": "iframe"}).getTitle();
<?php echo mfbfw_gallery_js( $s ); ?>
// Re-applied rather than delegated: FancyBox's global [data-fancybox]
// handler would open new links with default options, ignoring every