-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathHelpers.php
More file actions
978 lines (855 loc) · 28.2 KB
/
Helpers.php
File metadata and controls
978 lines (855 loc) · 28.2 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
<?php
namespace Classifai;
use Classifai\Features\Classification;
use Classifai\Features\Smart404;
use Classifai\Features\Smart404EPIntegration;
use Classifai\Providers\Provider;
use Classifai\Admin\UserProfile;
use Classifai\Providers\Watson\NLU;
use Classifai\Services\Service;
use Classifai\Services\ServicesManager;
use WP_Error;
/**
* Miscellaneous Helper functions to access different parts of the
* ClassifAI plugin.
*/
/**
* Returns the ClassifAI plugin's singleton instance
*
* @return Plugin
*/
function get_plugin() {
return Plugin::get_instance();
}
/**
* Overwrites the ClassifAI plugin's stored settings. Expected format is,
*
* [
* 'post_types' => [ <list of post type names> ]
* 'features' => [
* <feature_name> => <bool>
* <feature_threshold> => <int>
* ],
* 'credentials' => [
* 'watson_username' => <string>
* 'watson_password' => <string>
* ]
* ]
*
* @param array $settings The settings we're saving.
*/
function set_plugin_settings( array $settings ) {
update_option( 'classifai_settings', $settings );
}
/**
* Resets the plugin to factory defaults, keeping licensing information only.
*/
function reset_plugin_settings() {
$options = get_option( 'classifai_settings' );
if ( $options && isset( $options['registration'] ) ) {
// This is a legacy option set, so let's update it to the new format.
$new_settings = [
'valid_license' => $options['valid_license'],
'email' => isset( $options['registration']['email'] ) ? $options['registration']['email'] : '',
'license_key' => isset( $options['registration']['license_key'] ) ? $options['registration']['license_key'] : '',
];
update_option( 'classifai_settings', $new_settings );
}
$services = get_plugin()->services;
if ( ! isset( $services['service_manager'] ) || ! $services['service_manager']->service_classes ) {
return;
}
$service_classes = $services['service_manager']->service_classes;
foreach ( $service_classes as $service_class ) {
if ( ! $service_class instanceof Service || empty( $service_class->provider_classes ) ) {
continue;
}
foreach ( $service_class->provider_classes as $provider_class ) {
if ( ! $provider_class instanceof Provider || ! method_exists( $provider_class, 'reset_settings' ) ) {
continue;
}
$provider_class->reset_settings();
}
}
}
/**
* Get post types we want to show in the language processing settings
*
* @since 1.6.0
*
* @return array
*/
function get_post_types_for_language_settings(): array {
$post_types = get_post_types( [ 'public' => true ], 'objects' );
$post_types = array_filter( $post_types, 'is_post_type_viewable' );
// Remove the attachment post type
unset( $post_types['attachment'] );
/**
* Filter post types shown in language processing settings.
*
* @since 1.6.0
* @hook classifai_language_settings_post_types
*
* @param array $post_types Array of post types to show in language processing settings.
*
* @return array Array of post types.
*/
return apply_filters( 'classifai_language_settings_post_types', $post_types );
}
/**
* Get post types we want to show in the language processing settings
*
* @since 1.7.1
*
* @return array
*/
function get_post_statuses_for_language_settings(): array {
$post_statuses = get_all_post_statuses();
/**
* Filter post statuses shown in language processing settings.
*
* @since 1.7.1
* @hook classifai_language_settings_post_statuses
*
* @param array $post_statuses Array of post statuses to show in language processing settings.
*
* @return array Array of post statuses.
*/
return apply_filters( 'classifai_language_settings_post_statuses', $post_statuses );
}
/**
* Provides the max filesize for the Computer Vision service.
*
* @since 1.4.0
*
* @return int
*/
function computer_vision_max_filesize(): int {
/**
* Filters the Computer Vision maximum allowed filesize.
*
* @since 1.5.0
* @hook classifai_computer_vision_max_filesize
*
* @param int file_size The maximum allowed filesize for Computer Vision in bytes. Default `4 * MB_IN_BYTES`.
*
* @return int Filtered filesize in bytes.
*/
return apply_filters( 'classifai_computer_vision_max_filesize', 20 * MB_IN_BYTES ); // 20MB default.
}
/**
* Callback for sorting images by width plus height, descending.
*
* @since 1.5.0
*
* @param array $size_1 Associative array containing width and height values.
* @param array $size_2 Associative array containing width and height values.
* @return int Returns -1 if $size_1 is larger, 1 if $size_2 is larger, and 0 if they are equal.
*/
function sort_images_by_size_cb( array $size_1, array $size_2 ): int {
$size_1_total = $size_1['width'] + $size_1['height'];
$size_2_total = $size_2['width'] + $size_2['height'];
if ( $size_1_total === $size_2_total ) {
return 0;
}
return $size_1_total > $size_2_total ? -1 : 1;
}
/**
* Retrieves the URL of the largest version of an attachment image lower than a specified max size.
*
* @since 1.4.0
*
* @param string $full_image The path to the full-sized image source file.
* @param string $full_url The URL of the full-sized image.
* @param array $sizes Intermediate size data from attachment meta.
* @param int $max The maximum acceptable size.
* @return string|null The image URL, or null if no acceptable image found.
*/
function get_largest_acceptable_image_url( string $full_image, string $full_url, array $sizes, int $max = MB_IN_BYTES ) {
$file_size = @filesize( $full_image ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( $file_size && $max >= $file_size ) {
return $full_url;
}
usort( $sizes, __NAMESPACE__ . '\sort_images_by_size_cb' );
foreach ( $sizes as $size ) {
$sized_file = str_replace( basename( $full_image ), $size['file'], $full_image );
$file_size = @filesize( $sized_file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( $file_size && $max >= $file_size ) {
return str_replace( basename( $full_url ), $size['file'], $full_url );
}
}
return null;
}
/**
* Retrieves the URL of the largest image that matches filesize and dimensions.
*
* This will check that the filesize of an image matches our requirements and
* if so, will then check the dimensions match our requirements as well. If
* neither match, will move on to the next largest image size.
*
* @param string $full_image The path to the full-sized image source file.
* @param string $full_url The URL of the full-sized image.
* @param array $metadata Attachment metadata, including intermediate sizes.
* @param array $width Array of minimum and maximum width values. Default 0, 4200.
* @param array $height Array of minimum and maximum height values. Default 0, 4200.
* @param int $max_size The maximum acceptable filesize. Default 1MB.
* @return string|null The image URL, or null if no acceptable image found.
*/
function get_largest_size_and_dimensions_image_url( string $full_image, string $full_url, array $metadata, array $width = [ 0, 4200 ], array $height = [ 0, 4200 ], int $max_size = MB_IN_BYTES ) {
// Check if the full size image meets our filesize and dimension requirements
$file_size = @filesize( $full_image ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if (
( $file_size && $max_size >= $file_size )
&& ( $metadata['width'] >= $width[0] && $metadata['width'] <= $width[1] )
&& ( $metadata['height'] >= $height[0] && $metadata['height'] <= $height[1] )
) {
return $full_url;
}
// If the full size doesn't match, run the same checks on our resized images
if ( isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
usort( $metadata['sizes'], __NAMESPACE__ . '\sort_images_by_size_cb' );
foreach ( $metadata['sizes'] as $size ) {
$sized_file = str_replace( basename( $full_image ), $size['file'], $full_image );
$file_size = @filesize( $sized_file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if (
( $file_size && $max_size >= $file_size )
&& ( $size['width'] >= $width[0] && $size['width'] <= $width[1] )
&& ( $size['height'] >= $height[0] && $size['height'] <= $height[1] )
) {
return str_replace( basename( $full_url ), $size['file'], $full_url );
}
}
}
return null;
}
/**
* Allows returning modified image URL for a given attachment.
*
* @param int $post_id Post ID.
* @return mixed
*/
function get_modified_image_source_url( int $post_id ) {
/**
* Filter to modify image source URL in order to allow scanning images,
* stored on third party storages that cannot be used by
* helper function `get_largest_acceptable_image_url()` to determine `filesize()` locally.
*
* Default is null, return filtered string to allow classifying image on external source.
*
* @since 1.6.0
* @hook classifai_generate_image_alt_tags_source_url
*
* @param mixed $image_url New image path for given attachment ID.
* @param int $post_id The ID of the attachment to be used in classification.
*
* @return mixed NULL or filtered URl for given attachment id.
*/
return apply_filters( 'classifai_generate_image_alt_tags_source_url', null, $post_id );
}
/**
* Check if attachment is PDF document.
*
* @param int|\WP_Post $post Post object for the attachment being viewed.
* @return bool
*/
function attachment_is_pdf( $post ): bool {
$mime_type = get_post_mime_type( $post );
$matched_extensions = explode( '|', array_search( $mime_type, wp_get_mime_types(), true ) );
if ( in_array( 'pdf', $matched_extensions, true ) ) {
return true;
}
return false;
}
/**
* Get asset info from extracted asset files.
*
* @param string $slug Asset slug as defined in build/webpack configuration.
* @param string $attribute Optional attribute to get. Can be version or dependencies.
* @return string|array
*/
function get_asset_info( string $slug, ?string $attribute = null ) {
if ( file_exists( CLASSIFAI_PLUGIN_DIR . '/dist/' . $slug . '.asset.php' ) ) {
$asset = require CLASSIFAI_PLUGIN_DIR . '/dist/' . $slug . '.asset.php';
} else {
return null;
}
if ( ! empty( $attribute ) && isset( $asset[ $attribute ] ) ) {
return $asset[ $attribute ];
}
return $asset;
}
/**
* Get the list of registered services.
*
* @return array Array of services.
*/
function get_services_menu(): array {
$services = Plugin::$instance->services;
if ( empty( $services ) || empty( $services['service_manager'] ) || ! $services['service_manager'] instanceof ServicesManager ) {
return [];
}
/** @var ServicesManager $service_manager Instance of the services manager class. */
$service_manager = $services['service_manager'];
$services = [];
foreach ( $service_manager->service_classes as $service ) {
$services[ $service->get_menu_slug() ] = $service->get_display_name();
}
return $services;
}
/**
* Sanitizes and ensures an input variable is set.
*
* @param string $key $_GET or $_POST array key.
* @param boolean $is_get If the request is $_GET. Defaults to false.
* @param string $sanitize_callback Sanitize callback. Defaults to `sanitize_text_field`
* @return string|boolean Sanitized string or `false` as fallback.
*/
function clean_input( string $key = '', bool $is_get = false, string $sanitize_callback = 'sanitize_text_field' ) {
if ( ! is_callable( $sanitize_callback ) ) {
$sanitize_callback = 'sanitize_text_field';
}
if ( $is_get ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
return isset( $_GET[ $key ] ) ? call_user_func( $sanitize_callback, wp_unslash( $_GET[ $key ] ) ) : '';
} else {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
return isset( $_POST[ $key ] ) ? call_user_func( $sanitize_callback, wp_unslash( $_POST[ $key ] ) ) : '';
}
return false;
}
/**
* Find the provider class that a service belongs to.
*
* @param array $provider_classes Provider classes to look in.
* @param string $provider_id ID of the provider.
* @return Provider|WP_Error
*/
function find_provider_class( array $provider_classes = [], string $provider_id = '' ) {
$provider = '';
foreach ( $provider_classes as $provider_class ) {
if ( $provider_id === $provider_class::ID ) {
$provider = $provider_class;
}
}
if ( ! $provider ) {
return new WP_Error( 'provider_class_required', esc_html__( 'Provider class not found.', 'classifai' ) );
}
return $provider;
}
/**
* Get core and custom post statuses.
*
* @return array
*/
function get_all_post_statuses(): array {
$all_statuses = wp_list_pluck(
get_post_stati(
[],
'objects'
),
'label'
);
/*
* We unset the following because we want to limit the post
* statuses to the ones returned by `get_post_statuses()` and
* any custom post statuses registered using `register_post_status()`
*/
unset(
$all_statuses['future'],
$all_statuses['trash'],
$all_statuses['auto-draft'],
$all_statuses['inherit'],
$all_statuses['request-pending'],
$all_statuses['request-confirmed'],
$all_statuses['request-failed'],
$all_statuses['request-completed']
);
// Remove any HTML from the statuses.
$all_statuses = array_map( 'wp_strip_all_tags', $all_statuses );
/*
* There is a minor difference in the label for 'pending' status between
* `get_post_statuses()` and `get_post_stati()`.
*
* `get_post_stati()` has the label as `Pending` whereas
* `get_post_statuses()` has the label as `Pending Review`.
*
* So we normalise it here.
*/
if ( isset( $all_statuses['pending'] ) ) {
$all_statuses['pending'] = esc_html__( 'Pending Review', 'classifai' );
}
/**
* Hook to filter post statuses.
*
* @since 2.2.2
* @hook classifai_all_post_statuses
*
* @param array $all_statuses Array of post statuses.
*
* @return array Array of post statuses.
*/
return apply_filters( 'classifai_all_post_statuses', $all_statuses );
}
/**
* Check if the current user has permission to create and assign terms.
*
* @param string $tax Taxonomy name.
* @return bool|WP_Error
*/
function check_term_permissions( string $tax = '' ) {
$taxonomy = get_taxonomy( $tax );
if ( empty( $taxonomy ) || empty( $taxonomy->show_in_rest ) ) {
return new WP_Error( 'invalid_taxonomy', esc_html__( 'Taxonomy not found. Double check your settings.', 'classifai' ) );
}
$create_cap = is_taxonomy_hierarchical( $taxonomy->name ) ? $taxonomy->cap->edit_terms : $taxonomy->cap->assign_terms;
if ( ! current_user_can( $create_cap ) || ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return new WP_Error( 'rest_cannot_assign_term', esc_html__( 'Sorry, you are not allowed to create or assign to this taxonomy.', 'classifai' ) );
}
return true;
}
/**
* Renders a link to disable a specific feature.
*
* @since 2.5.0
*
* @param string $feature Feature key.
*/
function render_disable_feature_link( string $feature ) {
$user_profile = new UserProfile();
$allowed_features = $user_profile->get_allowed_features( get_current_user_id() );
$profile_url = get_edit_profile_url( get_current_user_id() ) . '#classifai-profile-features-section';
if ( ! empty( $allowed_features ) && isset( $allowed_features[ $feature ] ) ) {
?>
<a href="<?php echo esc_url( $profile_url ); ?>" target="_blank" rel="noopener noreferrer" class="classifai-disable-feature-link" aria-label="<?php esc_attr_e( 'Opt out of using this ClassifAI feature', 'classifai' ); ?>">
<?php esc_html_e( 'Disable this ClassifAI feature', 'classifai' ); ?>
</a>
<?php
}
}
/**
* Sanitize the prompt data.
* This is used for the repeater field.
*
* @since 2.4.0
*
* @param array $prompt_key Prompt key.
* @param array $new_settings Settings data.
* @return array Sanitized prompt data.
*/
function sanitize_prompts( $prompt_key = '', array $new_settings = [] ): array {
if ( isset( $new_settings[ $prompt_key ] ) && is_array( $new_settings[ $prompt_key ] ) ) {
$prompts = $new_settings[ $prompt_key ];
// Remove any prompts that don't have a title and prompt.
$prompts = array_filter(
$prompts,
function ( $prompt ) {
return ! empty( $prompt['title'] ) && ! empty( $prompt['prompt'] );
}
);
// Sanitize the prompts and make sure only one prompt is marked as default.
$has_default = false;
$prompts = array_map(
function ( $prompt ) use ( &$has_default ) {
$default = isset( $prompt['default'] ) && $prompt['default'] && ! $has_default;
if ( $default ) {
$has_default = true;
}
return array(
'title' => sanitize_text_field( $prompt['title'] ),
'prompt' => wp_kses_post( $prompt['prompt'] ),
'default' => absint( $default ),
'original' => absint( $prompt['original'] ),
);
},
$prompts
);
// If there is no default, use the first prompt.
if ( false === $has_default && ! empty( $prompts ) ) {
$prompts[0]['default'] = 1;
}
return $prompts;
}
return array();
}
/**
* Get the default prompt for use.
*
* @since 2.4.0
*
* @param array $prompts Prompt data.
* @return string|null Default prompt.
*/
function get_default_prompt( array $prompts ): ?string {
$default_prompt = null;
if ( ! empty( $prompts ) ) {
$prompt_data = array_filter(
$prompts,
function ( $prompt ) {
return isset( $prompt['default'] ) && $prompt['default'] && ! $prompt['original'];
}
);
if ( ! empty( $prompt_data ) ) {
$default_prompt = current( $prompt_data )['prompt'];
} elseif ( ! empty( $prompts[0]['prompt'] ) && ! $prompts[0]['original'] ) {
// If there is no default, use the first prompt, unless it's the original prompt.
$default_prompt = $prompts[0]['prompt'];
}
}
return $default_prompt;
}
/**
* Sanitisation callback for number of responses.
*
* @param string $key The key of the value we are sanitizing.
* @param array $new_settings The settings array.
* @param array $settings Current array.
* @return int
*/
function sanitize_number_of_responses_field( string $key, array $new_settings, array $settings ): int {
return absint( $new_settings[ $key ] ?? $settings[ $key ] ?? '' );
}
/**
* Returns a bool based on whether the specified classification feature is enabled.
*
* @param string $classify_by Feature to check.
* @return bool
*/
function get_classification_feature_enabled( string $classify_by ): bool {
$settings = ( new Classification() )->get_settings();
return ( ! empty( $settings[ $classify_by ] ) );
}
/**
* Returns the Taxonomy for the specified NLU feature.
*
* Returns defaults in config.php if options have not been configured.
*
* @param string $classify_by NLU feature name.
* @return string
*/
function get_classification_feature_taxonomy( string $classify_by = '' ): string {
$taxonomy = '';
$settings = ( new Classification() )->get_settings();
if ( ! empty( $settings[ $classify_by . '_taxonomy' ] ) ) {
$taxonomy = $settings[ $classify_by . '_taxonomy' ];
}
if ( NLU::ID !== $settings['provider'] ) {
$taxonomy = $classify_by;
}
if ( empty( $taxonomy ) ) {
$constant = 'WATSON_' . strtoupper( $classify_by ) . '_TAXONOMY';
if ( defined( $constant ) ) {
$taxonomy = constant( $constant );
}
}
/**
* Filter the Taxonomy for the specified NLU feature.
*
* @since 3.0.0
* @hook classifai_feature_classification_taxonomy_for_feature
*
* @param string $taxonomy The slug of the taxonomy to use.
* @param string $classify_by The NLU feature this taxonomy is for.
*
* @return string The filtered taxonomy slug.
*/
return apply_filters( 'classifai_feature_classification_taxonomy_for_feature', $taxonomy, $classify_by );
}
/**
* Get Classification mode.
*
* @since 2.5.0
*
* @return string
*/
function get_classification_mode(): string {
$feature = new Classification();
$settings = $feature->get_settings();
$value = $settings['classification_mode'] ?? '';
if ( $feature->is_feature_enabled() ) {
if ( empty( $value ) ) {
// existing users
// default: automatic_classification
return 'automatic_classification';
}
} else {
// new users
// default: manual_review
return 'manual_review';
}
return $value;
}
/**
* Determine if the legacy settings panel should be used.
*
* @since 3.2.0
*
* @return bool
*/
function should_use_legacy_settings_panel(): bool {
/**
* Filter to determine if the legacy settings panel should be used.
*
* @since 3.2.0
* @hook classifai_use_legacy_settings_panel
*
* @param bool $use_legacy_settings_panel Whether to use the legacy settings panel.
*
* @return bool Whether to use the legacy settings panel.
*/
return apply_filters( 'classifai_use_legacy_settings_panel', false );
}
/**
* Get all parts from the current URL.
*
* For instance, if the URL is `https://example.com/this/is/a/test/`,
* this function will return: `[ 'this', 'is', 'a', 'test' ]`.
*
* @return array
*/
function get_url_slugs(): array {
global $wp;
$parts = explode( '/', $wp->request );
return array_filter( $parts );
}
/**
* Get the last part from the current URL.
*
* For instance, if the URL is `https://example.com/this/is/a/test`,
* this function will return: 'test'.
*
* @return string
*/
function get_last_url_slug(): string {
$parts = get_url_slugs();
return trim( end( $parts ) );
}
/**
* Check if ElasticPress is installed.
*
* @return bool
*/
function is_elasticpress_installed(): bool {
return class_exists( '\\ElasticPress\\Feature' );
}
/**
* Get the Smart 404 results.
*
* @param array $args Arguments to pass to the search.
* @return array
*/
function get_smart_404_results( array $args = [] ): array {
// Run our query.
$results = ( new Smart404() )->exact_knn_search( get_last_url_slug(), $args );
// Ensure the query ran successfully.
if ( is_wp_error( $results ) ) {
return [];
}
// Convert the results to normal WP_Post objects.
$results = ( new Smart404EPIntegration() )->convert_es_results_to_post_objects( $results );
return $results;
}
/**
* Render the Smart 404 results.
*
* @param array $args Arguments to pass to the search.
*/
function render_smart_404_results( array $args = [] ) {
// Get the results.
$results = get_smart_404_results( $args );
// Handle situation where we don't have results.
if ( empty( $results ) ) {
return;
}
// Iterate through each result and render it.
echo '<ul>';
foreach ( $results as $result ) {
?>
<li>
<a href="<?php echo esc_url( get_permalink( $result->ID ) ); ?>">
<?php echo esc_html( $result->post_title ); ?>
</a>
<p>
<?php echo esc_html( $result->post_excerpt ); ?>
</p>
</li>
<?php
}
echo '</ul>';
}
/**
* Returns if a resource is of type attachment, URL or system path.
*
* @param int|string $resource_ref The ID of the attachment, or system or URL path
* to the audio file.
* @return bool|string The resource type. (attachment, url, path or false if none).
*/
function get_resource_type( $resource_ref ) {
if ( ! is_scalar( $resource_ref ) ) {
return false;
}
if ( is_numeric( $resource_ref ) ) {
return 'attachment';
}
if ( filter_var( $resource_ref, FILTER_VALIDATE_URL ) ) {
return 'url';
}
return 'path';
}
/**
* Returns true if attachment, false otherwise.
*
* @param string $resource_ref The ID of the attachment.
* @return bool
*/
function is_attachment( string $resource_ref ): bool {
return 'attachment' === get_resource_type( $resource_ref );
}
/**
* Returns true if the resource path is a URL, false otherwise.
*
* @param string $resource_ref The URL to the audio file.
* @return bool
*/
function is_remote_url( string $resource_ref ): bool {
return 'url' === get_resource_type( $resource_ref );
}
/**
* Returns true if the resource path is a system path, false otherwise.
*
* @param string $resource_ref The system file path to the audio file.
* @return bool
*/
function is_local_path( string $resource_ref ): bool {
return 'path' === get_resource_type( $resource_ref );
}
/**
* Safe generic HTTP wrapper compatible with WP VIP.
*
* - Use vip_safe_wp_remote_request() when available.
* - Fall back to wp_remote_request() on other scenarios.
* - Respect all call args (timeout, headers, method, etc).
*
* @since 3.6.0
*
* @param string $method HTTP method.
* @param string $url Request URL.
* @param array $args Request args.
* @return array|\WP_Error
*/
function safe_wp_remote_request( string $method, string $url, array $args = [] ) {
$method = strtoupper( $method );
$args['method'] = $method;
// Respect timeout if caller set.
$timeout = isset( $args['timeout'] ) ? (int) $args['timeout'] : 20;
// Ensure a clear UA but allow to override.
if ( empty( $args['headers']['User-Agent'] ) ) {
static $cached_user_agent = null;
if ( null === $cached_user_agent ) {
$version = defined( 'CLASSIFAI_VERSION' ) ? CLASSIFAI_VERSION : 'unknown';
$cached_user_agent = 'ClassifAI/' . $version;
}
$args['headers']['User-Agent'] = $cached_user_agent;
}
if ( function_exists( 'vip_safe_wp_remote_request' ) ) {
$fallback = '';
$threshold = 3;
$retry = 20;
return vip_safe_wp_remote_request( $url, $fallback, $threshold, min( max( 1, $timeout ), 20 ), $retry, $args );
}
$args = wp_parse_args(
$args,
[
'timeout' => $timeout,
]
);
return wp_remote_request( $url, $args ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.wp_remote_request_wp_remote_request
}
/**
* VIP-safe replacement for file_get_contents() supporting remote URLs.
*
* For http/https URLs, performs an HTTP GET via safe_wp_remote_get()/VIP wrapper
* and returns the raw body string on 2xx; returns false on error to mirror
* file_get_contents() semantics. For local paths, falls back to native
* file_get_contents(). This keeps calling code simple while staying VIP-safe.
*
* Important: This function intentionally does NOT return WP_Error to match the
* native signature; callers should check for strict false.
*
* @since 3.6.0
*
* @param string $file_path Path or URL.
* @param array $args Optional HTTP args (timeout, headers, etc.).
* @return string|false Raw contents on success; false on failure.
*/
function safe_file_get_contents( string $file_path, array $args = [] ) {
if ( is_remote_url( $file_path ) ) {
if ( function_exists( 'wpcom_vip_file_get_contents' ) ) {
$content = wpcom_vip_file_get_contents( $file_path );
if ( false !== $content ) {
return $content;
}
}
$response = safe_wp_remote_get( $file_path, $args );
if ( is_wp_error( $response ) ) {
return false;
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( $code < 200 || $code >= 300 ) {
return false;
}
return wp_remote_retrieve_body( $response );
}
// Local file path: fall back to native.
return @file_get_contents( $file_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, WordPress.PHP.NoSilencedErrors.Discouraged, WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown
}
/**
* Safe GET wrapper compatible with WP VIP.
*
* - Use vip_safe_wp_remote_get() when available.
* - Fall back to wp_remote_get() on other scenarios.
* - Respect all call args (timeout, headers, etc).
*
* @since 3.6.0
*
* @param string $url Request URL.
* @param array $args Request args.
* @return array|\WP_Error
*/
function safe_wp_remote_get( string $url, array $args = [] ) {
return safe_wp_remote_request( 'GET', $url, $args );
}
/**
* Safe POST wrapper compatible with WP VIP.
*
* - Use vip_safe_wp_remote_post() when available.
* - Fall back to wp_remote_post() on other scenarios.
* - Respect all call args (timeout, headers, etc).
*
* @since 3.6.0
*
* @param string $url Request URL.
* @param array $args Request args.
* @return array|\WP_Error
*/
function safe_wp_remote_post( string $url, array $args = [] ) {
return safe_wp_remote_request( 'POST', $url, $args );
}
/**
* Get the temperature for the request.
*
* We increase the base temperature proportionally
* to the number of results, ensuring it never exceeds 2.
*
* The goal here is to get more diverse results when
* we are requesting more results.
*
* @param float $temperature The temperature.
* @param int $results The number of results.
* @return float The temperature.
*/
function get_temperature( float $temperature, int $results = 1 ): float {
if ( 1 === $results ) {
return $temperature;
}
return (float) min( 2.0, $temperature + ( $results / 10 ) );
}