class-utilities.php
28.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
<?php
/**
* Useful utilities.
*
* @link https://wordpress.org/plugins/broken-link-checker/
* @since 2.0.0
*
* @author WPMUDEV (https://wpmudev.com)
* @package WPMUDEV_BLC\Core
*
* @copyright (c) 2022, Incsub (http://incsub.com)
*/
namespace WPMUDEV_BLC\Core\Utils;
// If this file is called directly, abort.
defined( 'WPINC' ) || die;
use WPMUDEV_BLC\Core\Traits\Dashboard_API;
use DateTime;
use DateTimeZone;
use WPMUDEV_Dashboard;
use WPMUDEV_Dashboard_Api;
use function array_keys;
use function array_values;
use function call_user_func;
use function date;
use function dirname;
use function error_log;
use function fclose;
use function file_exists;
use function fopen;
use function is_callable;
use function is_dir;
use function is_int;
use function is_multisite;
use function is_null;
use function mkdir;
use function path_join;
use function round;
use function wp_normalize_path;
/**
* Class WPMUDEV_BLC
*
* @package WPMUDEV_BLC\Core
*/
final class Utilities {
use Dashboard_API;
/**
* Array that holds variable values that can be re-used in several classes.
*
* @since 2.0.0
* @var array $value_provider
*/
public static $value_provider = array();
/**
* Checks if current request is on multisite for the network administrative interface.
*
* @since 2.0.0
* @return bool
*/
public static function is_network_admin() {
if ( ! is_multisite() ) {
return false;
}
/**
* Filter to change network admin flag.
*
* @since 2.0.0
*
* @param bool Is network.
*/
return apply_filters( 'wpmudev_blc_is_network_admin', is_network_admin() || self::is_ajax_network_admin() );
}
/**
* Check if network admin.
*
* The is_network_admin() check does not work in AJAX calls.
*
* @since 2.0.0
*
* @return bool
*/
public static function is_ajax_network_admin() {
if ( ! is_multisite() ) {
return false;
}
return defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_SERVER['HTTP_REFERER'] ) && preg_match( '#^' . network_admin_url() . '#i', wp_unslash( $_SERVER['HTTP_REFERER'] ) );
}
/**
* Checks if current request is on a subsite admin of a multisite installation. If we are on main site or on
* network admin, it returns false.
*
* @since 2.0.0
* @return bool
*/
public static function is_subsite() {
if ( ! is_multisite() ) {
return false;
}
/**
* Filter to change subsite admin flag.
*
* @since 2.0.0
*
* @param bool Is subsite.
*/
return apply_filters(
'wpmudev_blc_is_subsite',
! ( self::is_network_admin() || is_main_site() )
);
}
/**
* Gives the subsite id based on url.
*
* @return int|null
*/
public static function subsite_id_from_url( string $url = '' ) {
if ( empty( $url ) || ! is_multisite() ) {
return null;
}
$url_parts = wp_parse_url( $url );
$domain = $url_parts['host'] ?? null;
$path = null;
if ( defined( 'SUBDOMAIN_INSTALL' ) ) {
if ( SUBDOMAIN_INSTALL ) {
$path = '/';
} else {
$path = $url_parts['path'] ?? null;
}
}
if ( ! empty( $domain ) && ! empty( $path ) ) {
return get_blog_id_from_url( $domain, $path );
}
return null;
}
/**
* Checks if subsite id is valid.
* @param int|null $id
*
* @return false|void
*/
public static function valid_subsite_id( int $id = null ) {
if ( empty( $id ) || ! is_multisite() ) {
return false;
}
return in_array( $id, get_sites( array( 'fields' => "ids" ) ) );
}
/**
* Checks if given url belongs to author and returns author WP_User object else false.
*
* @since 2.1.0
*
* @param string $url
*
* @return WP_User|bool
*/
public static function is_author_url( string $url = '' ) {
$site_url = site_url();
if ( substr( $url, 0, strlen( $site_url ) ) !== $site_url ) {
return false;
}
global $wp_rewrite;
$parsed_url = wp_parse_url( $url );
$user = null;
// Check url when it has plain permalink structure.
if ( ! empty( $parsed_url['query'] ) ) {
$parsed_query = array();
parse_str( $parsed_url['query'], $parsed_query );
if ( ! empty( $parsed_query[ $wp_rewrite->author_base ] ) ) {
$user_key = is_numeric( $parsed_query[ $wp_rewrite->author_base ] ) ? 'id' : 'login';
$user = get_user_by( $user_key, sanitize_user( $parsed_query[ $wp_rewrite->author_base ] ) );
}
} else if ( ! empty( $parsed_url['path'] ) ) {
// Check url with pretty permalink structure.
$path = trim( $parsed_url['path'], '/\\' );
$author_base = "{$wp_rewrite->author_base}/";
$user_name = sanitize_user( str_replace( $author_base, '', $path ) );
$user = get_user_by( 'login', $user_name );
}
return $user;
}
/**
* Generate random unique id. Useful for creating element ids in scripts
*
* @since 2.0.0
*
* @param string $prefix Optional. A prefix.
*
* @return string Generate unique id.
*/
public static function get_unique_id( $prefix = null ): string {
if ( is_null( $prefix ) ) {
$prefix = uniqid() . '_';
}
return wp_unique_id( $prefix );
}
/**
* Checks if WPMU DEV Dashboard plugin is installed.
*
* @since 2.0.0
*
* @return bool
*/
public static function dash_plugin_installed() {
return apply_filters(
'wpmudev_blc_is_dash_installed',
file_exists( WP_PLUGIN_DIR . '/wpmudev-updates/update-notifications.php' )
);
}
/**
* Checks if WPMU DEV Dashboard plugin is active.
*
* @since 2.0.0
*
* @return bool
*/
public static function dash_plugin_active() {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$is_active = is_multisite() ?
is_plugin_active_for_network( 'wpmudev-updates/update-notifications.php' ) :
is_plugin_active( 'wpmudev-updates/update-notifications.php' );
return apply_filters( 'wpmudev_blc_is_dash_active', $is_active );
}
/**
* Returns a boolean. True if site is connected to hub or false if not.
*
* @return bool
*/
public static function is_site_connected() {
return self::site_connected();
}
/**
* Returns a boolean. True if site is connected to hub or false if not.
*
* @return bool
*/
public static function membership_expired() {
return 'expired' === self::get_membership_type();
}
/**
* Check if user is active member.
*
* @since 2.0.0
*
* @return bool
*/
public static function is_member() {
$is_member = false;
if ( class_exists( '\WPMUDEV_Dashboard' ) ) {
if ( method_exists( '\WPMUDEV_Dashboard_Api', 'get_membership_projects' ) && method_exists( '\WPMUDEV_Dashboard_Api', 'get_membership_type' ) ) {
$type = WPMUDEV_Dashboard::$api->get_membership_type();
$is_member = ! empty( $type );
if ( ! $is_member && function_exists( 'is_wpmudev_member' ) ) {
$is_member = is_wpmudev_member();
}
}
}
return apply_filters( 'wpmudev_blc_is_member', $is_member );
}
/**
* Returns the hub's start scan url.
*
* @return string
*/
public static function hub_scan_url() {
$url = null;
if ( self::get_dashboard_api() instanceof WPMUDEV_Dashboard_Api ) {
$site_id = self::get_site_id();
$url = apply_filters( 'wpmudev_blc_hub_scan_url', self::hub_home_url() . "?start-scan=1" );
}
return $url;
}
/**
* Returns the hub's url.
*
* @return string
*/
public static function hub_home_url() {
$url = null;
if ( self::get_dashboard_api() instanceof WPMUDEV_Dashboard_Api ) {
$site_id = self::get_site_id();
$url = apply_filters( 'wpmudev_blc_hub_home_url', untrailingslashit( self::wpmudev_base_url() . "hub2/site/{$site_id}/blc" ) );
}
return $url;
}
/**
* Returns WPMUDEV API Server URL
*
* @return string
*/
public static function wpmudev_base_url() {
$api_server_url = defined( 'WPMUDEV_CUSTOM_API_SERVER' ) && WPMUDEV_CUSTOM_API_SERVER
? trailingslashit( WPMUDEV_CUSTOM_API_SERVER )
: 'https://wpmudev.com/';
return $api_server_url;
}
/**
* Returns the hub's signup url.
*
* @return string
*/
public static function hub_signup_url() {
return apply_filters( 'wpmudev_blc_hub_signup_url', self::wpmudev_base_url() . 'register/?signup=blc&blc_url=' . site_url() );
}
/**
* Returns the hub's connect url.
*
* @return string
*/
public static function hub_connect_url() {
return apply_filters( 'wpmudev_blc_hub_connect_url', self::hub_base_url() . 'connect/choose-method/' );
}
/**
* Returns the signup url.
* If Dashboard plugin is active the signup url returned will be the Dashboard signup page. Else Hub signup page.
*
* @return string
*/
public static function signup_url() {
if ( self::get_dashboard_api() instanceof WPMUDEV_Dashboard_Api ) {
return add_query_arg( array(
'page' => 'wpmudev',
), is_multisite() ? network_admin_url() : get_admin_url() );
}
return self::hub_signup_url();
}
/**
* Returns the hub's url.
*
* @return string
*/
public static function hub_base_url() {
return apply_filters( 'wpmudev_blc_hub_base_url', self::wpmudev_base_url() . 'hub2/' );
}
/**
* Returns the hub's account url.
*
* @return string
*/
public static function hub_account_url() {
return apply_filters( 'wpmudev_blc_hub_account_url', self::hub_base_url() . 'account/' );
}
/**
* Returns the hub's start scan page url.
*
* @return string|null
*/
public static function hub_api_scan_url() {
$url = null;
if ( self::get_dashboard_api() instanceof WPMUDEV_Dashboard_Api ) {
$url = add_query_arg(
array(
'domain' => untrailingslashit( self::schemaless_url() ),
'site_id' => self::site_id()
),
self::wpmudev_base_url() . "api/blc/v1/scan"
);
}
return apply_filters( 'wpmudev_blc_api_scan_url', $url );
}
/**
* Returns url without schema (^http(s)?://).
*
* @param string $url .
*
* @return mixed
*/
public static function schemaless_url( string $url = '' ) {
if ( empty( $url ) ) {
$url = site_url();
}
$parsed_url = wp_parse_url( $url );
$host = $parsed_url['host'];
$path = $parsed_url['path'] ?? '';
// Path includes port if it exists in url.
return apply_filters( 'wpmudev_blc_schemaless_url', $host . $path, $url );
}
/**
* Returns the site id from hub.
*
* @return int
*/
public static function site_id() {
return apply_filters( 'wpmudev_blc_site_id', intval( self::get_site_id() ) );
}
/**
* Returns the hub's start scan page url.
*
* @return string|null
*/
public static function hub_api_sync_url() {
$url = null;
if ( self::get_dashboard_api() instanceof WPMUDEV_Dashboard_Api ) {
$url = add_query_arg(
array(
'domain' => untrailingslashit( self::schemaless_url() ),
'site_id' => self::site_id()
),
self::wpmudev_base_url() . "api/blc/v1/result"
);
}
return apply_filters( 'result_api_sync_url', $url );
}
/**
* Returns the hub url to send edit link results when edit link queue gets completed.
*
* @return string
*/
public static function hub_edit_link_completed() {
return apply_filters( 'hub_edit_link_completed', self::wpmudev_base_url() . "api/blc/v1/edit-link-completed" );
}
public static function make_link_relative( string $url = '' ) {
$site_url = site_url();
$site_url_parts = wp_parse_url( $site_url );
$url_parts = wp_parse_url( $url );
if ( ! empty( $url_parts['host'] ) && $site_url_parts['host'] !== $url_parts['host'] ) {
return $url;
}
// Check if missing url scheme.
// It is not unusual to have urls starting with two slashes.
// Relative urls starting with 2 slashes replace everything from the hostname onward.
if ( substr( $url, 0, 2 ) === "//" ) {
$url = wp_parse_url( $site_url, PHP_URL_SCHEME ) . ':' . $url;
}
// If string is internal (starts with same url) we need to get the relative url.
$link_substring = substr( $url, 0, strlen( $site_url ) );
if ( strcasecmp( $link_substring, $site_url ) == 0 ) {
return wp_make_link_relative( $url );
}
return $url;
}
/**
* Returns true if given screen(s) is the current admin screen.
*
* @since 2.0.0
*
* @param string|array $screen .
* @param bool $strict .
*
* @return bool
*/
public static function is_admin_screen( $screen = null, $strict = false ) {
if ( is_null( $screen ) || ! is_callable( '\get_current_screen' ) || ! isset( get_current_screen()->id ) ) {
return false;
}
if ( $strict ) {
return is_array( $screen ) ?
in_array( get_current_screen()->id, $screen, true ) :
get_current_screen()->id === $screen;
}
return is_array( $screen ) ?
! empty(
array_filter(
$screen,
function ( $page ) {
return strpos( get_current_screen()->id, $page ) !== false;
}
)
) : strpos( get_current_screen()->id, $screen ) !== false;
}
/**
* Returns site time zone string as done in WP settings ( Not like `wp_timezone_string()` )
*
* @since 2.0.0
*
* @param bool $plain .
*
* @return string
*/
public static function get_timezone_string( bool $plain = true ) {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Remove old Etc mappings. Fallback to gmt_offset.
if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
$tzstring = '';
}
if ( empty( $tzstring ) ) {
// Create a UTC+- zone if no timezone string exists.
if ( $plain ) {
$tzstring = $current_offset < 0 ? $current_offset : "+{$current_offset}";
} else {
$tzstring = $current_offset < 0 ? "UTC{$current_offset}" : "UTC+{$current_offset}";
}
}
return $tzstring;
}
/**
* Returns array with hour list 0...23. Taken from Snapshot4.
*
* @return array
*/
public static function get_hour_list() {
$dt = new DateTime();
$dt->setTimezone( new DateTimeZone( 'UTC' ) );
$dt->setTimestamp( 0 );
$result = array();
$time_format = self::get_time_format();
foreach ( range( 0, 23 ) as $hour ) {
$dt->setTime( $hour, 0, 0 );
$key = $dt->format( 'H:i' );
$value = $dt->format( $time_format );
$result[ $key ] = $value;
}
return $result;
}
/**
* Returns time format
*
* @return string
*/
public static function get_time_format() {
$time_format = get_option( 'time_format' );
$supported_formats = array(
'g:i a',
'g:i A',
'g:i:s a',
'g:i:s A',
'g:i,',
'H:i',
);
if ( ! in_array( $time_format, $supported_formats, true ) ) {
$time_format = 'H:i'; // Fallback to default format.
}
return $time_format;
}
/**
* Returns an array with weekdays.
*
* @since 2.0.0
* @return array
*/
public static function get_week_days() {
global $wp_locale;
$week_days = array();
for ( $day_index = 0; $day_index <= 6; $day_index ++ ) {
$week_days[] = array(
'key' => $day_index,
'value' => $wp_locale->get_weekday( $day_index ),
);
}
return $week_days;
}
/**
* Returns the value of a given key from a query string.
*
* @param string $query_string .
* @param string $key .
*
* @return mixed
*/
public static function get_query_var( string $query_string = '', string $key = '' ) {
if ( '' === $query_string || '' === $key ) {
return false;
}
$query_vars = array();
wp_parse_str( wp_parse_url( $query_string, PHP_URL_QUERY ), $query_vars );
return $query_vars[ $key ] ?? false;
}
/**
* Returns user avatar by user id.
*
* @param int $id .
* @param array $args .
*
* @return array|bool|string|null
*/
public static function avatar_by_id( int $id = 0, array $args = array() ) {
return self::avatar_data( $id, 'id', $args );
}
/**
* Retruns avatar dat.
*
* @param string $input .
* @param string $input_type .
* @param array $args .
*
* @return bool|null|array|string
*/
public static function avatar_data( string $input = '', string $input_type = 'id', array $args = array() ) {
$response = null;
switch ( $input_type ) {
case 'id':
$input = intval( $input );
break;
case 'email':
$input = filter_var( $input, FILTER_VALIDATE_EMAIL );
break;
}
$args = wp_parse_args(
$args,
array(
'size' => 96,
'height' => null,
'width' => null,
'default' => get_option( 'avatar_default', 'mystery' ),
'force_default' => false,
'rating' => get_option( 'avatar_rating' ),
'scheme' => null,
'processed_args' => null, // If used, should be a reference.
'extra_attr' => '',
'return' => 'raw', // Allowed values, array raw, bool found_avatar, string url.
)
);
$avatar_data = get_avatar_data( $input, $args );
switch ( $args['return'] ) {
case 'raw':
$response = $avatar_data;
break;
case 'found_avatar':
$response = isset( $avatar_data['found_avatar'] ) && (bool) $avatar_data['found_avatar'];
break;
case 'url':
$response = isset( $avatar_data['url'] ) ? esc_html( $avatar_data['url'] ) : false;
break;
}
return $response;
}
/**
* Returns avatar by a given email address.
*
* @param string $email .
* @param array $args .
*
* @return array|bool|string|null
*/
public static function avatar_by_email( string $email = '', array $args = array() ) {
return self::avatar_data( $email, 'email', $args );
}
/**
* Returns user's role titles
*
* @param int $user_id The user's id to get roles for.
*
* @return array
*/
public static function user_role_names( int $user_id = 0 ) {
if ( ! function_exists( 'get_editable_roles' ) ) {
require_once ABSPATH . 'wp-admin/includes/user.php';
}
$editable_roles = get_editable_roles();
return array_map(
function ( $item ) use ( $editable_roles ) {
return isset( $editable_roles[ $item ] ) ? $editable_roles[ $item ]['name'] : $item;
},
get_userdata( $user_id )->roles
);
}
/**
* Returns names of user roles
*
* @param array $capabilities Optional. An array with capabilities. Fetch roles per capability.
*
* @return array
*/
public static function roles_names( array $capabilities = array() ) {
if ( ! function_exists( 'get_editable_roles' ) ) {
require_once ABSPATH . 'wp-admin/includes/user.php';
}
$roles = get_editable_roles();
if ( ! empty( $capabilities ) ) {
$roles = array_filter(
$roles,
function ( $role ) use ( $capabilities ) {
foreach ( $capabilities as $capability ) {
if ( array_key_exists( $capability, $role['capabilities'] ) ) {
return true;
}
}
return false;
}
);
}
return wp_list_pluck( $roles, 'name' );
}
/**
* Converts an int number of seconds to hours, minutes and seconds format.
*
* @param float $seconds A float holding number of seconds.
*
* @return string
*/
public static function normalize_seconds_format( float $seconds = 0 ) {
if ( 0 >= $seconds ) {
return $seconds;
}
$seconds = round( $seconds );
$hours_str = '';
if ( $seconds >= HOUR_IN_SECONDS ) {
$hours_str = sprintf(
_n(
'%d h ',
'%d h ',
gmdate( 'H', $seconds ),
'broken-link-checker'
),
gmdate( 'H', $seconds )
);
}
$minutes_str = sprintf(
_n(
'%d min ',
'%d min ',
gmdate( 'i', $seconds ),
'broken-link-checker'
),
gmdate( 'i', $seconds )
);
$seconds_str = ( $seconds % MINUTE_IN_SECONDS ) > 0 ? sprintf(
_n(
'%d s ',
'%d s ',
gmdate( 's', $seconds ),
'broken-link-checker'
),
gmdate( 's', $seconds )
) : '';
return $hours_str . $minutes_str . $seconds_str;
}
/**
* Formats a timestamp into a date and time string based on site format.
*
* @param int $timestamp The timestamp to format.
*
* @return string|null
*/
public static function timestamp_to_formatted_date( int $timestamp = null, bool $gmt_to_local = false ) {
$timezone = null;
if ( ! $gmt_to_local ) {
$timezone = new DateTimeZone( 'UTC' );
}
return self::format_date( $timestamp, null, $timezone );
}
/**
* Format a time/date
*
* @param integer $timestamp Timestamp.
* @param string|null $format Date/time format.
* @param DateTimeZone|null $timezone Timezone.
*
* @return string
* @todo Rename method to be datetime specific.
*
*/
public static function format_date( $timestamp, $format = null, $timezone = null ) {
if ( is_null( $format ) ) {
$format = self::get_format();
}
if ( is_null( $timezone ) ) {
$timezone = self::get_timezone();
}
$dt = new DateTime();
$dt->setTimestamp( $timestamp );
$dt->setTimezone( $timezone );
return $dt->format( $format );
}
/**
* Returns datetime format
*
* @return string
* @todo Rename method to be datetime specific.
*
*/
public static function get_format() {
$format = self::get_date_format();
$format .= _x( ' ', 'date time sep', 'broken-link-checker' );
$format .= self::get_time_format();
return $format;
}
/**
* Returns date format
*
* @return string
*/
public static function get_date_format() {
return get_option( 'date_format' );
}
/**
* Returns user's timezone
*
* @return DateTimeZone
*/
public static function get_timezone() {
return wp_timezone();
}
/**
* Converts a timestamp from UTC to site's local timezone.
*
* @param int|null $timestamp
*
* @return false|int
*/
public static function timestamp_from_UTC( int $timestamp = null ) {
$timestamp = is_null( $timestamp ) ? time() : $timestamp;
$timestamp = strlen( $timestamp ) === 13 ? $timestamp / 1000 : $timestamp;
$date_time = DateTime::createFromFormat( 'U', $timestamp, new DateTimeZone('UTC') );
$date_time->setTimezone( new DateTimeZone( wp_timezone_string() ) );
return strtotime( $date_time->format('Y-m-d H:i:s') );
}
/**
* Converts microtime to date.
*
* @param int|float $microtime Microtime. Int when sent from API, float from PHP.
* @param string $form Output form. Accepted values 'full_date', 'date', 'day', 'month', 'year', 'time'.
* @param bool $gmt_to_local Convert from GMT to site local timezone. By default, it's false.
*
* @return string|null
*/
public static function microtime_to_date( $microtime = 0, string $form = 'full_date', bool $gmt_to_local = false
) {
if ( ! in_array( $form, array( 'full_date', 'date', 'day', 'month', 'year', 'time' ), true ) ) {
return null;
}
$microtime = ! is_float( $microtime ) ? ( strlen( $microtime ) === 13 ? $microtime / 1000 : $microtime ) : $microtime;
$date_time = null;
if ( strlen( $microtime ) === 10 ) {
$date_time = DateTime::createFromFormat( 'U', $microtime );
} elseif ( strlen( $microtime ) === 13 ) {
$date_time = DateTime::createFromFormat( 'U.u', $microtime );
} else {
return null;
}
$date_format = get_option( 'date_format' );
$time_format = get_option( 'time_format' );
$output = null;
if ( $gmt_to_local ) {
$date_time->setTimezone( new DateTimeZone( wp_timezone_string() ) );
}
switch ( $form ) {
case 'full_date':
$output = $date_time->format( "{$date_format} {$time_format}" );
break;
case 'date':
$output = $date_time->format( $date_format );
break;
case 'day':
$output = $date_time->format( 'd' );
break;
case 'month':
$output = $date_time->format( 'm' );
break;
case 'year':
$output = $date_time->format( 'Y' );
break;
case 'time':
$output = $date_time->format( $time_format );
break;
}
return $output;
}
/**
* Calculates the diff of microtime.
*
* @param int|float|null $micro_start .
* @param int|float|null $micro_end .
* @param string $format .
*
* @return false|float|int|mixed|null
*/
public static function microtimediff( $micro_start = null, $micro_end = null, string $format = 'SEC' ) {
if ( is_null( $micro_start ) ) {
return false;
}
if ( is_null( $micro_end ) ) {
/*
* Multiplying with 1000 so php microtime matches format sent from api.
*/
$micro_end = intval( round( microtime( true ) * 1000 ) );
}
/**
* From APIs the microtime is usually a float.
* The previous condition, if reached, will give an integer, so there is no risk of multiplying by 1000 twice.
*/
$micro_start = is_float( $micro_start ) ? round( $micro_start * 1000 ) : $micro_start;
$micro_end = is_float( $micro_end ) ? round( $micro_end * 1000 ) : $micro_end;
/*
* Microtime has 13 digits as sent from api side.
*/
if ( strlen( $micro_start ) !== 13 || strlen( $micro_end ) !== 13 ) {
return false;
}
$diff = number_format( $micro_end - $micro_start, 2, '.', '' );
switch ( $format ) {
case 'MIN':
$diff = $diff / 1000 / MINUTE_IN_SECONDS;
break;
case 'SEC':
$diff = $diff / 1000;
break;
default:
case 'MICRO':
break;
}
return $diff;
}
/**
* Returns true if plain permalinks iare used.
*
* @return bool
*/
public static function plain_permalinks_mode() {
return empty( get_option( 'permalink_structure' ) );
}
/**
* Checks if site is hosted on localhost.
*
* @return bool
*/
public static function is_localhost() {
return ! wp_doing_cron() &&
isset( $_SERVER['REMOTE_ADDR'] ) &&
in_array( $_SERVER['REMOTE_ADDR'], array( '127.0.0.1', '::1' ), true ) &&
! ( defined( 'WPMUDEV_DEVELOPMENT_MODE' ) && WPMUDEV_DEVELOPMENT_MODE );
}
/**
* Returns an array with all the callbacks for a cron's hook.
*
* @param string $hook .
*
* @return array
*/
public static function get_scheduled_event_callbacks( string $hook = '' ) {
return self::get_hook_callbacks( $hook );
}
/**
* Returns hook callbacks. Taken from WP Crontrol plugin.
*
* @param string $hook .
*
* @return array
*/
public static function get_hook_callbacks( string $hook = '' ) {
global $wp_filter;
$actions = array();
if ( isset( $wp_filter[ $hook ] ) ) {
// See http://core.trac.wordpress.org/ticket/17817.
$action = $wp_filter[ $hook ];
foreach ( $action as $priority => $callbacks ) {
foreach ( $callbacks as $callback ) {
$actions[] = array(
'priority' => $priority,
'callback' => $callback,
);
}
}
}
return $actions;
}
/**
* Returns replaced value based on array keys and callbacks/values from a given mapped array.
*
* @param string $content The string that contains the content we need to replace the mapped values.
* @param array $map An array mapping keys and values/callbacks.
* @param string $context An optional string holding a context. Used in filter to help in specificity.
* @param array $keys Optional. An array of keys to map in given mapped array. If empty all $map's array keys will be used.
*
* @return string
*/
public static function replace_mapped_values( string $content = '', array $map = array(), string $context = null, array $keys = array() ) {
if ( empty( $map ) ) {
return $content;
}
if ( empty( $keys ) ) {
$keys = array_keys( $map );
}
$mapped_values = array_fill_keys( $keys, null );
foreach ( $keys as $key ) {
$mapped_values[ $key ] = self::get_mapped_value( $map[ $key ], $context );
}
return str_replace( array_keys( $mapped_values ), array_values( $mapped_values ), $content );
}
/**
* Returns replaced value based on array keys and callbacks/values from a given mapped array.
*
* @param mixed $input An array mapping keys and values/callbacks.
* @param string $context An optional string holding a context. Used in filter to help in specificity.
*/
public static function get_mapped_value( $input = null, string $context = null ) {
if ( is_null( $input ) ) {
return null;
}
return apply_filters(
'wpmudev_blc_replace_mapped_value',
is_callable( $input ) ? call_user_func( $input ) : $input,
$input,
$context
);
}
/**
* Verifies is input code is a valid http response code.
*
* @param int $code The code to verify.
*
* @return bool
*/
public static function valid_http_response_code( int $code = 0 ) {
// HTTP Response codes should be between 100 and 599: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.
return is_int( $code ) && $code >= 100 && $code <= 599;
}
/**
* Logs messages in either `wp-content/debug.log` by default or to a given file path. Requires `WP_DEBUG_LOG` to be set to true.
*
* @param string $message The message to be logged.
* @param string $file Optional. Log file path. If not set `wp-content/debug.log` will be used. File path has to be relative to WP_CONTENT_DIR.
*
* @return void
*/
public static function log( string $message = '', string $file_path = '' ) {
if ( ! defined( 'WPMUDEV_BLC_LOG' ) || ! WPMUDEV_BLC_LOG ) {
return;
}
$month = date( 'm' );
$year = date( 'Y' );
$default_log_file = "/blc-logs/debug-{$year}-{$month}.log";
if ( empty( $file_path ) ) {
$file_path = $default_log_file;
}
$dt_string = date( self::get_date_format() . ' ' . self::get_time_format() );
$file_path = wp_normalize_path( path_join( WP_CONTENT_DIR, ltrim( $file_path, '/' ) ) );
if ( ! is_dir( dirname( $file_path ) ) ) {
mkdir( dirname( $file_path ), 0755, true );
}
if ( ! file_exists( $file_path ) ) {
$new_file = fopen( $file_path, 'w' );
if ( ! $new_file ) {
return;
}
fclose( $new_file );
}
error_log( "[{$dt_string}] $message \n", 3, $file_path );
}
/**
* Provides a flag that determines if plugin should go through links more extensively.
*
* @param $param
*
* @return bool
*/
public static function process_extensive( $param = null ) {
return apply_filters( 'wpmudev_blc_process_extensive', false, $param );
}
}