-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd-settings-links.php
1545 lines (1397 loc) · 52 KB
/
add-settings-links.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Add Settings Links
* Description: Adds direct links to the settings pages for all plugins that do not have one (including multisite/network admin support).
* Version: 1.7.3
* Author: Jazir5
* Text Domain: add-settings-links
* Domain Path: /languages
* Requires PHP: 7.4
*/
namespace ASL;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Transient keys and expiration constants for caching menu slugs and plugins (multisite-friendly).
*/
if ( ! defined( 'ASL_MENU_SLUGS_TRANSIENT' ) ) {
define( 'ASL_MENU_SLUGS_TRANSIENT', 'asl_cached_admin_menu_slugs' );
}
if ( ! defined( 'ASL_MENU_SLUGS_TRANSIENT_EXPIRATION' ) ) {
define( 'ASL_MENU_SLUGS_TRANSIENT_EXPIRATION', 12 * HOUR_IN_SECONDS );
}
if ( ! defined( 'ASL_CACHED_PLUGINS_TRANSIENT' ) ) {
define( 'ASL_CACHED_PLUGINS_TRANSIENT', 'asl_cached_plugins' );
}
if ( ! defined( 'ASL_CACHED_PLUGINS_TRANSIENT_EXPIRATION' ) ) {
define( 'ASL_CACHED_PLUGINS_TRANSIENT_EXPIRATION', DAY_IN_SECONDS );
}
if ( ! defined( 'ASL_PLUGIN_FILES_TRANSIENT_EXPIRATION' ) ) {
define( 'ASL_PLUGIN_FILES_TRANSIENT_EXPIRATION', 24 * HOUR_IN_SECONDS ); // Example: 24 hours
}
/**
* Enhanced Settings Detection Trait
*
* Provides improved methods for detecting WordPress plugin settings pages
* through multiple detection strategies.
*
* @requires get_transient_key(string): string
* @requires cache_admin_menu_slugs(): void
* @requires log_debug(string): void
*/
trait ASL_EnhancedSettingsDetection {
/**
* Common settings-related terms across multiple languages.
*/
protected static $settings_terms = array(
'en' => array( 'settings', 'options', 'preferences', 'configuration' ),
'de' => array( 'einstellungen', 'optionen', 'konfiguration' ),
'es' => array( 'ajustes', 'opciones', 'configuración' ),
'fr' => array( 'paramètres', 'options', 'configuration' ),
// Add more languages as needed
);
/**
* Provide a method for the trait to discover potential settings by scanning the cached admin menu.
* This method is called only if `method_exists($this, 'find_settings_in_admin_menu')` is true.
*
* @param string $plugin_dir e.g. "my-plugin"
* @param string $plugin_basename e.g. "my-plugin/my-plugin.php"
* @return string[] Potential admin URLs discovered from the WP menu, or empty array if none
*/
private function find_settings_in_admin_menu( string $plugin_dir, string $plugin_basename ): array {
$found_urls = array();
$transient_key = $this->get_transient_key( \ASL_MENU_SLUGS_TRANSIENT );
$cached_slugs = get_transient( $transient_key );
if ( ! is_array( $cached_slugs ) ) {
$cached_slugs = array();
}
// If empty, try caching now
if ( empty( $cached_slugs ) || ! is_array( $cached_slugs ) ) {
$this->cache_admin_menu_slugs();
$cached_slugs = get_transient( $transient_key );
}
if ( empty( $cached_slugs ) || ! is_array( $cached_slugs ) ) {
$this->log_debug( 'Cannot find potential settings slugs. Cache is empty or invalid (in find_settings_in_admin_menu).' );
return $found_urls;
}
// Generate potential slugs from the plugin’s folder + file naming
$potential_slugs = $this->generate_potential_slugs( $plugin_dir, $plugin_basename );
// Compare against cached admin menu slugs
foreach ( $cached_slugs as $item ) {
if ( isset( $item['slug'], $item['url'] ) && in_array( $item['slug'], $potential_slugs, true ) ) {
$this->log_debug( "Found potential admin menu URL for plugin '$plugin_basename': " . $item['url'] );
$found_urls[] = $item['url'];
}
}
return array_unique( $found_urls );
}
/**
* An "extended" approach to find potential settings URLs, combining multiple strategies.
*
* 1) If available, uses find_settings_in_admin_menu() from the main class to glean URLs from the cached WP admin menu.
* 2) Static file analysis of plugin files (regex searching for known patterns).
* 3) Option table analysis for plugin-specific settings.
* 4) Hook analysis for admin-related callbacks.
*
* @param string $plugin_dir Plugin directory name.
* @param string $plugin_basename Plugin basename.
* @return string[] Array of discovered URLs or an empty array if none found.
*/
private function extended_find_settings_url( string $plugin_dir, string $plugin_basename ): array {
$found_urls = array();
$menu_urls = array();
$file_urls = array();
$option_urls = array();
$hook_urls = array();
// 1. Use the main class’s method if it exists (e.g., scanning the cached WP admin menu).
if ( method_exists( $this, 'find_settings_in_admin_menu' ) ) {
$menu_urls = $this->find_settings_in_admin_menu( $plugin_dir, $plugin_basename );
if ( $menu_urls ) {
$found_urls = array_merge( $found_urls, $menu_urls );
}
}
// 2. Static file analysis (advanced).
$file_urls = $this->analyze_plugin_files( $plugin_basename );
if ( $file_urls ) {
$found_urls = array_merge( $found_urls, $file_urls );
}
// 3. Option table analysis.
$option_urls = $this->analyze_options_table( $plugin_dir, $plugin_basename );
if ( $option_urls ) {
$found_urls = array_merge( $found_urls, $option_urls );
}
// 4. Hook analysis.
$hook_urls = $this->analyze_registered_hooks( $plugin_dir );
if ( $hook_urls ) {
$found_urls = array_merge( $found_urls, $hook_urls );
}
return ! empty( $found_urls ) ? array_unique( $found_urls ) : array();
}
/**
* Analyze plugin files for potential settings pages.
*
* @param string $plugin_basename Plugin basename.
* @return array Array of discovered admin URLs.
*/
private function analyze_plugin_files( string $plugin_basename ): array {
$plugin_dir = WP_PLUGIN_DIR . '/' . dirname( $plugin_basename );
if ( ! is_dir( $plugin_dir ) ) {
return array();
}
$transient_key = $this->get_transient_key( 'asl_analyze_plugin_files_' . md5( $plugin_basename ) );
$cached_urls = get_transient( $transient_key );
if ( $cached_urls !== false ) {
$this->log_debug( 'Retrieved plugin file analysis from cache.' );
return $cached_urls;
}
$found_urls = array();
$files = $this->recursively_scan_directory( $plugin_dir, array( 'php' ) );
foreach ( $files as $file ) {
if ( empty( $file ) || stripos( $file, '/vendor/' ) !== false ) {
continue;
}
$content = @file_get_contents( $file );
if ( $content === false ) {
$this->log_debug( "Failed to read file: $file" );
continue;
}
// Look for common settings page registration patterns
$patterns = array(
'add_menu_page',
'add_options_page',
'add_submenu_page',
'register_setting',
'add_settings_section',
'settings_fields',
'options-general.php',
);
foreach ( $patterns as $pattern ) {
if ( stripos( $content, $pattern ) !== false ) { // Case-insensitive search
// Extract potential URLs using regex
if ( preg_match_all( '/[\'"]([^\'"]*(settings|options|config)[^\'"]*)[\'"]/', $content, $matches ) ) {
foreach ( $matches[1] as $match ) {
if ( $this->is_valid_admin_url( $match ) ) {
$found_urls[] = admin_url( $match );
}
}
}
break; // Stop checking other patterns once a match is found
}
}
}
$found_urls = array_unique( $found_urls );
set_transient( $transient_key, $found_urls, \ASL_PLUGIN_FILES_TRANSIENT_EXPIRATION );
$this->log_debug( 'Plugin file analysis cached.' );
return $found_urls;
}
/**
* Fallback method to find settings URLs using standard URL patterns.
*
* Combines checks for common patterns with multiple admin entry points and
* plugin-specific slug variations for more comprehensive fallback detection.
*
* @param mixed $classOrObject Class name or object.
* @param string $method Method name.
* @return array Array of discovered admin URLs.
*/
private function fallback_find_settings_url( $classOrObject, string $method ): array {
$found = array();
// --- Common URL Patterns and Admin Entry Points (Combined for iteration) ---
$common_patterns_entry_points = array(
'settings' => array( 'admin.php', 'options-general.php', 'settings.php' ),
'options' => array( 'admin.php', 'options-general.php', 'settings.php' ),
'configure' => array( 'admin.php', 'tools.php' ),
'config' => array( 'admin.php', 'tools.php' ),
'setup' => array( 'admin.php' ),
'admin' => array( 'admin.php' ),
'preferences' => array( 'admin.php', 'options-general.php' ),
'prefs' => array( 'admin.php', 'options-general.php' ),
'management' => array( 'admin.php' ),
'admin-panel' => array( 'admin.php' ),
'dashboard' => array( 'admin.php' ), // Dashboard - less common, but included
);
foreach ( $common_patterns_entry_points as $pattern => $entry_points ) {
foreach ( $entry_points as $entry_point ) {
$potential_url = $entry_point . '?page=' . sanitize_title_with_dashes( $pattern );
if ( $this->is_valid_admin_url( $potential_url ) ) {
$found[] = admin_url( $potential_url );
$this->log_debug( 'Fallback detected settings URL: ' . admin_url( $potential_url ) . ' (Pattern: ' . $pattern . ', Entry point: ' . $entry_point . ')' );
}
}
}
// --- Plugin-Specific Slug Variations ---
$plugin_slug_bases = array();
if ( is_string( $classOrObject ) ) {
$parts = explode( '\\', $classOrObject );
if ( isset( $parts[0] ) ) {
$plugin_slug_bases[] = sanitize_title_with_dashes( strtolower( $parts[0] ) );
}
} elseif ( is_object( $classOrObject ) ) {
$className = get_class( $classOrObject );
$parts = explode( '\\', $className );
if ( isset( $parts[0] ) ) {
$plugin_slug_bases[] = sanitize_title_with_dashes( strtolower( $parts[0] ) );
}
$plugin_slug_bases[] = sanitize_title_with_dashes( strtolower( str_replace( '_', '-', get_class( $classOrObject ) ) ) );
}
if ( ! empty( $plugin_slug_bases ) ) {
foreach ( $plugin_slug_bases as $plugin_base ) {
if ( empty( $plugin_base ) ) {
continue;
}
foreach ( static::$settings_terms as $lang => $terms ) {
foreach ( $terms as $term ) {
$plugin_specific_patterns = array(
"{$plugin_base}-{$term}",
"{$plugin_base}_{$term}",
"{$plugin_base}-" . sanitize_title_with_dashes( $term ),
sanitize_title_with_dashes( $plugin_base ) . '_' . sanitize_title_with_dashes( $term ),
);
foreach ( $plugin_specific_patterns as $plugin_pattern ) {
foreach ( array( 'admin.php', 'options-general.php', 'tools.php', 'settings.php' ) as $entry_point ) { // Re-iterate all entry points for plugin-specific patterns
$potential_url = $entry_point . '?page=' . $plugin_pattern;
if ( $this->is_valid_admin_url( $potential_url ) ) {
$found[] = admin_url( $potential_url );
$this->log_debug( 'Fallback detected settings URL (Plugin-Specific): ' . admin_url( $potential_url ) . ' (Pattern: ' . $plugin_pattern . ', Entry point: ' . $entry_point . ')' );
}
}
}
}
}
}
}
return array_unique( $found );
}
/**
* Analyze the WP options table for plugin-specific setting references.
*
* @param string $plugin_dir Plugin directory name.
* @param string $plugin_basename Plugin basename.
* @return array Array of discovered admin URLs.
*/
private function analyze_options_table( string $plugin_dir, string $plugin_basename ): array {
global $wpdb;
$found_urls = array();
// Possible prefixes based on plugin directory and basename
$possible_prefixes = array(
str_replace( '-', '_', sanitize_title( $plugin_dir ) ) . '_',
str_replace( '-', '_', sanitize_title( $plugin_basename ) ) . '_',
sanitize_title( $plugin_dir ) . '_',
sanitize_title( $plugin_basename ) . '_',
);
// Build the LIKE patterns
$like_patterns = array();
foreach ( $possible_prefixes as $prefix ) {
$like_patterns[] = $wpdb->esc_like( $prefix ) . '%';
}
if ( empty( $like_patterns ) ) {
return array();
}
// Construct the SQL query with dynamic placeholders
$placeholders = implode( ' OR option_name LIKE ', array_fill( 0, count( $like_patterns ), '%s' ) );
$query = "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE " . implode( ' OR option_name LIKE ', array_fill( 0, count( $like_patterns ), '%s' ) );
// Execute the query
$options = $wpdb->get_results(
$wpdb->prepare(
$query,
...$like_patterns
)
);
if ( $options ) {
// If plugin has registered options, guess potential settings pages from known patterns
$all_terms = array();
foreach ( self::$settings_terms as $langArr ) {
$all_terms = array_merge( $all_terms, $langArr );
}
$all_terms = array_unique( $all_terms );
// For each known settings word, guess a "page=" slug
foreach ( $all_terms as $pattern ) {
$potential_url = 'admin.php?page=' . $plugin_dir . '-' . $pattern;
if ( $this->is_valid_admin_url( $potential_url ) ) {
$found_urls[] = admin_url( $potential_url );
}
// Additionally, try using plugin basename
$potential_url_basename = 'admin.php?page=' . $plugin_basename . '-' . $pattern;
if ( $this->is_valid_admin_url( $potential_url_basename ) ) {
$found_urls[] = admin_url( $potential_url_basename );
}
}
}
return array_unique( $found_urls );
}
/**
* Analyze registered hooks for settings-related callbacks.
*
* @param string $plugin_dir Plugin directory name.
* @return array Array of discovered admin URLs.
*/
private function analyze_registered_hooks( string $plugin_dir ): array {
global $wp_filter;
$found_urls = array();
$settings_hooks = array(
'admin_menu',
'admin_init',
'network_admin_menu',
'options_page',
);
foreach ( $settings_hooks as $hook ) {
if ( ! isset( $wp_filter[ $hook ] ) ) {
continue;
}
$hook_callbacks = $wp_filter[ $hook ];
$callbacks = array();
// Handle WP_Hook instance (WordPress 4.7+)
if ( $hook_callbacks instanceof \WP_Hook ) {
$callbacks = $hook_callbacks->callbacks;
} else {
// Pre-WordPress 4.7 structure (array of priorities)
$callbacks = $hook_callbacks;
}
foreach ( $callbacks as $priority => $callbacks_at_priority ) {
foreach ( $callbacks_at_priority as $callback ) {
if ( is_array( $callback['function'] ) ) {
$classOrObject = $callback['function'][0];
$method = $callback['function'][1];
// Check if it belongs to this plugin
if ( is_object( $classOrObject ) ) {
$className = get_class( $classOrObject );
if ( stripos( $className, $plugin_dir ) !== false ) {
$found_urls = array_merge(
$found_urls,
$this->extract_urls_via_reflection( $classOrObject, $method )
);
}
} elseif ( is_string( $classOrObject ) && stripos( $classOrObject, $plugin_dir ) !== false ) {
// It's a static call
$found_urls = array_merge(
$found_urls,
$this->extract_urls_via_reflection( $classOrObject, $method, true )
);
}
}
}
}
}
return array_unique( $found_urls );
}
/**
* Use reflection to read file content for a given class method, searching for possible settings URLs.
*
* @param mixed $classOrObject Class name or object.
* @param string $method Method name.
* @param bool $isStatic Whether the method is static.
* @return array Array of discovered admin URLs.
*/
private function extract_urls_via_reflection( $classOrObject, string $method, bool $isStatic = false ): array {
$found = array();
$cache_key = 'asl_reflection_' . md5( $classOrObject . $method . ( $isStatic ? '_static' : '' ) );
$cached_urls = get_transient( $cache_key );
if ( $cached_urls !== false ) {
$this->log_debug( 'Retrieved reflection URLs from cache.' );
return $cached_urls;
}
// Improved regex patterns to capture various settings URL formats
$patterns = array(
'/[\'"](admin\.php\?page=([\w\-]+))[\'"]/',
'/[\'"](options-general\.php\?page=([\w\-]+))[\'"]/',
'/[\'"](tools\.php\?page=([\w\-]+))[\'"]/',
'/[\'"]([^\'"]*[\'"]\s*,\s*[\'"]([\w\-]+)[\'"])/',
);
foreach ( $patterns as $pattern ) {
if ( preg_match_all( $pattern, $content, $matches ) ) {
foreach ( $matches[1] as $index => $urlParam ) {
$potential_url = $urlParam;
if ( ! str_contains( $potential_url, '.php' ) ) {
$potential_url = 'admin.php?page=' . $potential_url;
}
if ( $this->is_valid_admin_url( $potential_url ) ) {
$found[] = admin_url( $potential_url );
}
}
}
}
try {
$reflection = $isStatic
? new \ReflectionMethod( $classOrObject, $method )
: new \ReflectionMethod( get_class( $classOrObject ), $method );
$file_path = $reflection->getFileName();
if ( ! $file_path || ! file_exists( $file_path ) || ! is_readable( $file_path ) ) {
$this->log_debug( "Cannot access the file for method {$method} in class " . get_class( $classOrObject ) );
return array();
}
$content = @file_get_contents( $file_path );
if ( $content === false ) {
$this->log_debug( "Failed to read the file: {$file_path} for method {$method} in class " . get_class( $classOrObject ) );
return array();
}
// Improved regex to target likely URL patterns more accurately
// This regex looks for URLs within quotes that include 'settings', 'options', or 'config' as a parameter value
if ( $content && preg_match_all( '/[\'"]admin\.php\?page=([\w\-]+)[\'"]/', $content, $matches ) ) {
foreach ( $matches[0] as $index => $full_match ) {
$page_param = $matches[1][ $index ];
$potential_url = 'admin.php?page=' . $page_param;
if ( $this->is_valid_admin_url( $potential_url ) ) {
$found[] = admin_url( $potential_url );
}
}
} else {
$this->log_debug( "No matching URLs found in the file: {$file_path} for method {$method}." );
// Utilize the fallback method
$fallback_urls = $this->fallback_find_settings_url( $classOrObject, $method );
if ( ! empty( $fallback_urls ) ) {
$found = array_merge( $found, $fallback_urls );
$this->log_debug( 'Fallback found URLs: ' . implode( ', ', $fallback_urls ) );
}
}
} catch ( \ReflectionException $e ) {
// Log the exception for debugging
$this->log_debug( 'ReflectionException: ' . $e->getMessage() );
return array();
} catch ( \Exception $e ) {
// Catch any other unexpected exceptions
$this->log_debug( 'Unexpected Exception in extract_urls_via_reflection: ' . $e->getMessage() );
return array();
}
$found = array_unique( $found );
if ( ! empty( $found ) ) {
set_transient( $cache_key, $found, \ASL_PLUGIN_FILES_TRANSIENT_EXPIRATION );
$this->log_debug( 'Reflection URLs cached.' );
} else {
$this->log_debug( 'No valid URLs found to cache in reflection.' );
}
return $found;
}
/**
* Recursively scan directory for files with specific extensions.
*
* @param string $dir Directory path.
* @param array $extensions Array of file extensions to include.
* @return array Array of file paths.
*/
private function recursively_scan_directory( string $dir, array $extensions ): array {
$files = array();
if ( ! class_exists( 'RecursiveIteratorIterator' ) || ! class_exists( 'RecursiveDirectoryIterator' ) ) {
return $files; // Not available in this PHP environment
}
try {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator( $dir, \RecursiveDirectoryIterator::SKIP_DOTS )
);
foreach ( $iterator as $file ) {
if ( in_array( strtolower( pathinfo( $file, PATHINFO_EXTENSION ) ), $extensions, true ) ) {
$files[] = $file->getPathname();
}
}
} catch ( \UnexpectedValueException $e ) {
// Directory read error
$this->log_debug( 'UnexpectedValueException: ' . $e->getMessage() );
}
return $files;
}
/**
* Validate if a given path could be a valid admin URL.
*
* @param string $path URL path.
* @return bool True if valid, false otherwise.
*/
private function is_valid_admin_url( string $path ): bool {
$allowed_pages = apply_filters(
'asl_allowed_admin_pages',
array(
'admin.php',
'options-general.php',
'tools.php',
'settings.php',
'options.php',
'edit.php',
)
);
// Parse the URL
$parsed = parse_url( $path );
if ( ! $parsed || ! isset( $parsed['path'] ) ) {
return false;
}
$page = basename( $parsed['path'] );
if ( ! in_array( $page, $allowed_pages, true ) ) {
return false;
}
// Ensure no disallowed characters
if ( preg_match( '/[<>"\'&]/', $path ) ) {
return false;
}
// Optionally, enforce specific query parameters
if ( isset( $parsed['query'] ) ) {
parse_str( $parsed['query'], $query_params );
if ( isset( $query_params['page'] ) ) {
// Validate the 'page' parameter format
if ( ! preg_match( '/^[\w\-]+$/', $query_params['page'] ) ) {
return false;
}
}
}
return true;
}
}
if ( ! class_exists( __NAMESPACE__ . '\\ASL_AddSettingsLinks' ) ) {
/**
* Class AddSettingsLinks
*
* Discovers potential “Settings” pages for installed plugins (for single-site or multisite “network” admin),
* allows manual overrides, and displays aggregated notices for any plugin missing a recognized settings link.
*/
class ASL_AddSettingsLinks {
use ASL_EnhancedSettingsDetection; // Incorporate the trait here
/**
* Plugin version.
*/
const VERSION = '1.7.3';
/**
* Singleton instance.
*
* @var self|null
*/
private static $instance = null;
/**
* List of plugin basenames that have no recognized settings page.
* We show them in one aggregated notice on relevant screens.
*
* @var string[]
*/
private $missing_settings = array();
/**
* Constructor: sets up WordPress hooks and filters for single-site + network usage.
*/
private function __construct() {
// 1. Load plugin text domain for translations.
add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) );
// 2. Conditionally cache admin menu slugs (single-site or network).
add_action( 'admin_menu', array( $this, 'maybe_cache_admin_menu_slugs' ), 9999 );
// 3. Dynamically add plugin action links filters for all plugins.
add_action( 'admin_init', array( $this, 'add_dynamic_plugin_action_links' ) );
// 4. Clear cached slugs whenever a plugin is activated/deactivated.
add_action( 'activated_plugin', array( $this, 'clear_cached_menu_slugs' ) );
add_action( 'deactivated_plugin', array( $this, 'clear_cached_menu_slugs' ) );
// 5. Invalidate cached slugs on plugin/theme updates/installs.
add_action( 'upgrader_process_complete', array( $this, 'dynamic_cache_invalidation' ), 10, 2 );
// 6. Register manual overrides on relevant admin screens.
add_action( 'admin_init', array( $this, 'maybe_register_settings' ) );
// 7. Add our plugin’s settings page under “Settings” (also works in network admin if you prefer).
add_action( 'admin_menu', array( $this, 'maybe_add_settings_page' ) );
// 8. Display an aggregated notice about missing settings pages (single-site + network).
add_action( 'admin_notices', array( $this, 'maybe_display_admin_notices' ) );
add_action( 'network_admin_notices', array( $this, 'maybe_display_admin_notices' ) );
// 9. Enqueue Admin Scripts and Styles
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
// 11. Handle AJAX requests for URL validation
add_action( 'wp_ajax_asl_validate_url', array( $this, 'ajax_validate_url' ) );
}
/**
* Retrieves the singleton instance.
*
* @return self
*/
public static function get_instance(): self {
if ( self::$instance === null ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Dynamically add plugin action links filters for all installed plugins.
*/
public function add_dynamic_plugin_action_links(): void {
if ( ! \function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$all_plugins = get_plugins();
foreach ( $all_plugins as $plugin_file => $plugin_data ) {
add_filter(
'plugin_action_links_' . $plugin_file,
function ( $links ) use ( $plugin_file, $plugin_data ) {
return $this->maybe_add_settings_links( $links, $plugin_file, $plugin_data );
},
20,
2
); // Set accepted arguments to 1
}
}
/**
* Loads the plugin's text domain for i18n.
*/
public function load_textdomain(): void {
load_plugin_textdomain(
'add-settings-links',
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages'
);
}
public function enqueue_admin_assets( string $hook ): void {
/**
* Enqueue admin assets with proper version and dependency handling
*/
$valid_hooks = array( 'settings_page_asl_settings', 'plugins.php' );
if ( ! in_array( $hook, $valid_hooks, true ) ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$plugin_version = self::VERSION; // Use the class constant for versioning
$min_suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
// Enqueue CSS
$css_file = "css/asl-admin{$min_suffix}.css";
$css_path = plugin_dir_path( __FILE__ ) . $css_file;
if ( file_exists( $css_path ) ) {
wp_enqueue_style(
'asl-admin-css',
plugin_dir_url( __FILE__ ) . $css_file,
array(),
$plugin_version
);
} else {
$this->log_debug( "CSS file {$css_file} not found." );
}
// Enqueue JavaScript
$js_file = "js/asl-admin{$min_suffix}.js";
$js_path = plugin_dir_path( __FILE__ ) . $js_file;
if ( file_exists( $js_path ) ) {
wp_enqueue_script(
'asl-admin-js',
plugin_dir_url( __FILE__ ) . $js_file,
array( 'jquery' ),
$plugin_version,
true
);
// Localize script for AJAX and dynamic data
wp_localize_script(
'asl-admin-js',
'ASL_Settings',
array(
'invalid_url_message' => __( 'One or more URLs are invalid. Please ensure correct formatting.', 'add-settings-links' ),
'error_validating_url' => __( 'Error validating URL.', 'add-settings-links' ),
'nonce' => wp_create_nonce( 'asl-admin-nonce' ),
'ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
} else {
$this->log_debug( "JavaScript file {$js_file} not found." );
}
}
/**
* Generate potential slugs based on plugin directory and basename.
*
* @param string $plugin_dir Plugin directory name.
* @param string $plugin_basename Plugin basename.
* @return string[] Array of potential slugs.
*/
private function generate_potential_slugs( string $plugin_dir, string $plugin_basename ): array {
$potential_slugs = array();
$plugin_dir_name = dirname( $plugin_basename );
if ( $plugin_dir_name === '.' ) {
$plugin_dir_name = basename( $plugin_basename, '.php' );
}
$variations = array(
$plugin_dir,
str_replace( '-', '_', $plugin_dir ),
$plugin_dir_name,
str_replace( '-', '_', $plugin_dir_name ),
);
foreach ( $variations as $base ) {
foreach ( static::$settings_terms as $lang => $terms ) {
foreach ( $terms as $term ) {
$potential_slugs[] = "$base-$term";
$potential_slugs[] = "{$base}_$term";
}
}
}
return array_unique( $potential_slugs );
}
/**
* Conditionally add the plugin's own settings page under "Settings".
*/
public function maybe_add_settings_page(): void {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
add_options_page(
__( 'Add Settings Links', 'add-settings-links' ),
__( 'Add Settings Links', 'add-settings-links' ),
'manage_options',
'asl_settings',
array( $this, 'render_settings_page' )
);
}
/**
* Checks whether the plugin should run certain logic on the current screen.
*
* @param array $valid_screens Array of valid screen IDs.
* @return bool True if should run, false otherwise.
*/
private function should_run_on_screen( array $valid_screens ): bool {
// Not in admin or network admin, or no get_current_screen => skip
if ( ( ! is_admin() && ! is_network_admin() ) || ! function_exists( 'get_current_screen' ) ) {
return false;
}
$screen = get_current_screen();
if ( ! $screen ) {
return false;
}
return in_array( $screen->id, $valid_screens, true );
}
/**
* Conditionally cache admin menu slugs if on relevant screens.
*/
public function maybe_cache_admin_menu_slugs(): void {
$valid_screens = array(
'plugins',
'plugins-network',
'settings_page_asl_settings',
'options-general',
'options-general-network',
);
if ( ! $this->should_run_on_screen( $valid_screens ) ) {
return;
}
$this->cache_admin_menu_slugs();
}
/**
* Actually caches admin menu slugs (top-level + submenu) in a transient.
*/
private function cache_admin_menu_slugs(): void {
$transient_key = $this->get_transient_key( \ASL_MENU_SLUGS_TRANSIENT );
if ( false !== get_transient( $transient_key ) ) {
$this->log_debug( 'Admin menu slugs are already cached. Skipping rebuild.' );
return;
}
global $menu, $submenu;
$all_slugs = array();
// Gather top-level items
if ( ! empty( $menu ) && is_array( $menu ) ) {
foreach ( $menu as $item ) {
if ( ! empty( $item[2] ) ) {
$slug = sanitize_text_field( $item[2] );
$parent = isset( $item[0] ) ? sanitize_text_field( $item[0] ) : '';
$url = $this->construct_menu_url( $slug );
$all_slugs[] = array(
'slug' => $slug,
'url' => $url,
'parent' => $parent,
);
$this->log_debug( "Caching top-level slug: $slug => $url" );
}
}
}
// Gather submenu items
if ( ! empty( $submenu ) && is_array( $submenu ) ) {
foreach ( $submenu as $parent_slug => $items ) {
foreach ( (array) $items as $item ) {
if ( ! empty( $item[2] ) ) {
$slug = sanitize_text_field( $item[2] );
$url = $this->construct_menu_url( $slug, $parent_slug );
$all_slugs[] = array(
'slug' => $slug,
'url' => $url,
'parent' => sanitize_text_field( $parent_slug ),
);
$this->log_debug( "Caching submenu slug: $slug => $url (parent: $parent_slug)" );
}
}
}
}
if ( ! empty( $all_slugs ) ) {
set_transient( $transient_key, $all_slugs, ASL_MENU_SLUGS_TRANSIENT_EXPIRATION );
$this->log_debug( 'Menu slugs have been cached successfully.' );
} else {
$this->log_debug( 'No admin menu slugs found to cache.' );
}
}
/**
* Helper to construct a full admin URL for a given slug (and optional parent slug).
*
* @param string $slug Menu slug.
* @param string $parent_slug Parent menu slug (if any).
* @return string Full admin URL.
*/
private function construct_menu_url( string $slug, string $parent_slug = '' ): string {
if ( empty( $parent_slug ) ) {
if ( strpos( $slug, '.php' ) !== false ) {
return admin_url( $slug );
}
return add_query_arg( 'page', $slug, admin_url( 'admin.php' ) );
}
if ( strpos( $parent_slug, '.php' ) !== false ) {
return add_query_arg( 'page', $slug, admin_url( $parent_slug ) );
}
return add_query_arg( 'page', $slug, admin_url( 'admin.php' ) );
}
/**
* Possibly add or skip plugin settings links on single-site or network plugins pages.
*
* @param array $links Array of existing plugin action links.
* @param string $plugin_file Plugin file path.
* @param array $plugin_data Plugin data array.
* @return array Modified array of plugin action links.
*/
public function maybe_add_settings_links( array $links, string $plugin_file, array $plugin_data ): array {
// Check if the plugin is itself
if ( $plugin_file === plugin_basename( __FILE__ ) ) {
// Define the settings URL for this plugin
$settings_url = admin_url( 'options-general.php?page=asl_settings' );
// Check if the settings link already exists
foreach ( $links as $link_html ) {
if ( strpos( $link_html, $settings_url ) !== false ) {
// Settings link already exists, do not add again
return $links;
}
}
// Prepend the settings link using the existing method
$links = $this->prepend_settings_link( $links, array( $settings_url ), $plugin_data['Name'] );
return $links;
}
if ( ! current_user_can( 'manage_options' ) ) {
return $links;
}
if ( $this->plugin_has_settings_link( $links ) ) {
return $links;
}
$settings_added = false;
$manual_overrides = get_option( 'asl_manual_overrides', array() );
$is_network = is_network_admin();
// 1. Manual overrides
if ( ! empty( $manual_overrides[ $plugin_file ] ) ) {
foreach ( (array) $manual_overrides[ $plugin_file ] as $settings_url ) {
$settings_url = trim( $settings_url );
if ( ! $settings_url ) {
continue;
}
// Validate and sanitize the URL
$settings_url = esc_url_raw( $settings_url );
if ( $this->is_valid_admin_url( $settings_url ) && ! $this->link_already_exists( $links, $settings_url ) ) {
$links = $this->prepend_settings_link( $links, array( $settings_url ), $plugin_data['Name'] );
$settings_added = true;
} else {
$this->log_debug( "Invalid manual override URL for plugin {$plugin_data['Name']}: {$settings_url}" );
}
}
}
if ( $settings_added ) {
return $links;
}
// 2. Use the trait’s extended detection approach
$plugin_basename_clean = plugin_basename( $plugin_file );
$plugin_dir_clean = dirname( $plugin_basename_clean );
$urls = $this->extended_find_settings_url( $plugin_dir_clean, $plugin_basename_clean );
if ( ! empty( $urls ) ) {
foreach ( $urls as $url ) {
$url = trim( $url );
if ( ! $url ) {
continue;
}
// Validate and sanitize the URL
if ( strpos( $url, 'http' ) === 0 ) {
$full_url = esc_url_raw( $url );