-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathutils-wp.php
More file actions
611 lines (524 loc) · 17.9 KB
/
utils-wp.php
File metadata and controls
611 lines (524 loc) · 17.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
<?php
// Utilities that depend on WordPress code.
namespace WP_CLI\Utils;
use ReflectionClass;
use ReflectionParameter;
use WP_CLI;
use WP_CLI\UpgraderSkin;
/**
* @return void
*/
function wp_not_installed() {
global $wpdb, $table_prefix;
if ( ! is_blog_installed() && ! defined( 'WP_INSTALLING' ) ) {
$tables = $wpdb->get_col( "SHOW TABLES LIKE '%_options'" );
$found_prefixes = [];
if ( count( $tables ) ) {
foreach ( $tables as $table ) {
$maybe_prefix = substr( $table, 0, - strlen( 'options' ) );
if ( $maybe_prefix !== $table_prefix ) {
$found_prefixes[] = $maybe_prefix;
}
}
}
if ( count( $found_prefixes ) ) {
sort( $found_prefixes );
$prefix_list = implode( ', ', $found_prefixes );
$install_label = count( $found_prefixes ) > 1 ? 'installations' : 'installation';
WP_CLI::error(
"The site you have requested is not installed.\n" .
"Your table prefix is '{$table_prefix}'. Found {$install_label} with table prefix: {$prefix_list}.\n" .
'Or, run `wp core install` to create database tables.'
);
} else {
WP_CLI::error(
"The site you have requested is not installed.\n" .
'Run `wp core install` to create database tables.'
);
}
}
}
// phpcs:disable WordPress.PHP.IniSet -- Intentional & correct usage.
/**
* @return void
*/
function wp_debug_mode() {
if ( WP_CLI::get_config( 'debug' ) ) {
if ( ! defined( 'WP_DEBUG' ) ) {
define( 'WP_DEBUG', true );
}
error_reporting( E_ALL & ~E_DEPRECATED );
} else {
if ( WP_DEBUG ) {
error_reporting( E_ALL );
if ( WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 1 );
} elseif ( null !== WP_DEBUG_DISPLAY ) {
ini_set( 'display_errors', 0 );
}
// @phpstan-ignore cast.useless
if ( in_array( strtolower( (string) WP_DEBUG_LOG ), [ 'true', '1' ], true ) ) {
$log_path = WP_CONTENT_DIR . '/debug.log';
// @phpstan-ignore function.alreadyNarrowedType
} elseif ( is_string( WP_DEBUG_LOG ) ) {
$log_path = WP_DEBUG_LOG;
} else {
$log_path = false;
}
if ( false !== $log_path ) {
ini_set( 'log_errors', 1 );
ini_set( 'error_log', $log_path );
}
} else {
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
}
// wp_doing_ajax() might not be available.
// @phpstan-ignore phpstanWP.wpConstant.fetch
if ( defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
ini_set( 'display_errors', 0 );
}
}
// XDebug already sends errors to STDERR.
ini_set( 'display_errors', function_exists( 'xdebug_debug_zval' ) ? false : 'stderr' );
}
// phpcs:enable
/**
* @return void
*/
function replace_wp_die_handler() {
\remove_filter( 'wp_die_handler', '_default_wp_die_handler' );
\add_filter(
'wp_die_handler',
function () {
return __NAMESPACE__ . '\\wp_die_handler';
}
);
}
/**
* @return never
*/
function wp_die_handler( $message ) {
if ( $message instanceof \WP_Error ) {
$text_message = $message->get_error_message();
} else {
$text_message = $message;
}
$text_message = wp_clean_error_message( $text_message );
WP_CLI::error( $text_message );
}
/**
* Clean HTML error message so suitable for text display.
*
* @param string $message
* @return string
*/
function wp_clean_error_message( $message ) {
$original_message = trim( $message );
$message = $original_message;
if ( preg_match( '|^\<h1>(.+?)</h1>|', $original_message, $matches ) ) {
$message = $matches[1] . '.';
}
if ( preg_match( '|\<p>(.+?)</p>|', $original_message, $matches ) ) {
$message .= ' ' . $matches[1];
}
$search_replace = [
'<code>' => '`',
'</code>' => '`',
];
$message = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $message );
$message = namespace\strip_tags( $message );
$message = html_entity_decode( $message, ENT_COMPAT, 'UTF-8' );
return $message;
}
/**
* @param string $url
* @return string
*/
function wp_redirect_handler( $url ) {
WP_CLI::warning( 'Some code is trying to do a URL redirect. Backtrace:' );
ob_start();
debug_print_backtrace();
fwrite( STDERR, (string) ob_get_clean() );
return $url;
}
/**
* @param string $since Version number.
* @param string $path File to include.
* @return void
*/
function maybe_require( $since, $path ) {
if ( wp_version_compare( $since, '>=' ) ) {
require $path;
}
}
/**
* @template T of \WP_Upgrader
*
* @param class-string<T> $class_name Class name.
* @param bool $insecure Optional. Default false.
* @param \WP_Upgrader_Skin $skin. Optional. Upgrader skin. Default \WP_CLI\UpgraderSkin.
*
* @return T Upgrader instance.
* @throws \ReflectionException
*/
function get_upgrader( $class_name, $insecure = false, $skin = null ) {
if ( ! class_exists( '\WP_Upgrader' ) ) {
if ( file_exists( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ) ) {
include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
}
}
if ( ! class_exists( '\WP_Upgrader_Skin' ) ) {
if ( file_exists( ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php' ) ) {
include ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
}
}
$uses_insecure_flag = false;
$reflection = new ReflectionClass( $class_name );
$constructor = $reflection->getConstructor();
if ( $constructor ) {
$arguments = $constructor->getParameters();
/** @var ReflectionParameter $argument */
foreach ( $arguments as $argument ) {
if ( 'insecure' === $argument->name ) {
$uses_insecure_flag = true;
break;
}
}
}
if ( $uses_insecure_flag ) {
/**
* @var T $result
*/
// TODO: Introduce custom upgrader interface supporting two arguments.
// @phpstan-ignore arguments.count
$result = new $class_name( $skin ?: new UpgraderSkin(), $insecure );
return $result;
}
/**
* @var T $result
*/
$result = new $class_name( $skin ?: new UpgraderSkin() );
return $result;
}
/**
* Converts a plugin basename back into a friendly slug.
*
* @param string $basename
* @return string
*/
function get_plugin_name( $basename ) {
if ( false === strpos( $basename, '/' ) ) {
$name = basename( $basename, '.php' );
} else {
$name = dirname( $basename );
}
return $name;
}
/**
* Determine whether a plugin is skipped.
*
* @param string $file
* @return bool
*/
function is_plugin_skipped( $file ) {
$name = get_plugin_name( str_replace( WP_PLUGIN_DIR . '/', '', $file ) );
$skipped_plugins = WP_CLI::get_runner()->config['skip-plugins'];
if ( true === $skipped_plugins ) {
return true;
}
if ( ! is_array( $skipped_plugins ) ) {
$skipped_plugins = explode( ',', $skipped_plugins );
}
return in_array( $name, array_filter( $skipped_plugins ), true );
}
/**
* Get theme name from path.
*
* @param string $path
* @return string
*/
function get_theme_name( $path ) {
return basename( $path );
}
/**
* Determine whether a theme is skipped.
*
* @param string $path
* @return bool
*/
function is_theme_skipped( $path ) {
$name = get_theme_name( $path );
$skipped_themes = WP_CLI::get_runner()->config['skip-themes'];
if ( true === $skipped_themes ) {
return true;
}
if ( ! is_array( $skipped_themes ) ) {
$skipped_themes = explode( ',', $skipped_themes );
}
return in_array( $name, array_filter( $skipped_themes ), true );
}
/**
* Register the sidebar for unused widgets.
* Core does this in /wp-admin/widgets.php, which isn't helpful.
*
* @return void
*/
function wp_register_unused_sidebar() {
register_sidebar(
[
'name' => __( 'Inactive Widgets' ),
'id' => 'wp_inactive_widgets',
'class' => 'inactive-sidebar',
'description' => __( 'Drag widgets here to remove them from the sidebar but keep their settings.' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
]
);
}
/**
* Attempts to determine which object cache is being used.
*
* Note that the guesses made by this function are based on the WP_Object_Cache classes
* that define the 3rd party object cache extension. Changes to those classes could render
* problems with this function's ability to determine which object cache is being used.
*
* @return string
*/
function wp_get_cache_type() {
global $_wp_using_ext_object_cache, $wp_object_cache;
$message = 'Unknown';
if ( ! empty( $_wp_using_ext_object_cache ) ) {
// Test for Memcached PECL extension memcached object cache (https://github.com/tollmanz/wordpress-memcached-backend)
if ( isset( $wp_object_cache->m ) && $wp_object_cache->m instanceof \Memcached ) {
$message = 'Memcached';
// Test for Memcache PECL extension memcached object cache (https://wordpress.org/extend/plugins/memcached/)
} elseif ( isset( $wp_object_cache->mc ) ) {
$is_memcache = true;
foreach ( $wp_object_cache->mc as $bucket ) {
if ( ! $bucket instanceof \Memcache && ! $bucket instanceof \Memcached ) {
$is_memcache = false;
}
}
if ( $is_memcache ) {
$message = 'Memcache';
}
// Test for Xcache object cache (https://plugins.svn.wordpress.org/xcache/trunk/object-cache.php)
} elseif ( $wp_object_cache instanceof \XCache_Object_Cache ) {
$message = 'Xcache';
// Test for WinCache object cache (https://wordpress.org/extend/plugins/wincache-object-cache-backend/)
} elseif ( class_exists( 'WinCache_Object_Cache' ) ) {
$message = 'WinCache';
// Test for APC object cache (https://wordpress.org/extend/plugins/apc/)
} elseif ( class_exists( 'APC_Object_Cache' ) ) {
$message = 'APC';
// Test for WP Redis (https://wordpress.org/plugins/wp-redis/)
} elseif ( isset( $wp_object_cache->redis ) && $wp_object_cache->redis instanceof \Redis ) {
$message = 'Redis';
// Test for Redis Object Cache (https://wordpress.org/plugins/redis-cache/)
} elseif ( method_exists( $wp_object_cache, 'redis_instance' ) && method_exists( $wp_object_cache, 'redis_status' ) ) {
$message = 'Redis';
// Test for Object Cache Pro (https://objectcache.pro/)
} elseif ( method_exists( $wp_object_cache, 'config' ) && method_exists( $wp_object_cache, 'connection' ) ) {
$message = 'Redis';
// Test for WP LCache Object cache (https://github.com/lcache/wp-lcache)
} elseif ( isset( $wp_object_cache->lcache ) && $wp_object_cache->lcache instanceof \LCache\Integrated ) {
$message = 'WP LCache';
// Test for WP-Stash (https://github.com/inpsyde/WP-Stash)
} elseif ( class_exists( 'Inpsyde\WpStash\WpStash' ) ) {
try {
$wp_stash = \Inpsyde\WpStash\WpStash::instance();
if ( is_object( $wp_stash ) && method_exists( $wp_stash, 'driver' ) ) {
$driver = $wp_stash->driver();
if ( is_object( $driver ) ) {
$message = 'WP-Stash (' . get_class( $driver ) . ')';
} else {
$message = 'WP-Stash';
}
} else {
$message = 'WP-Stash';
}
} catch ( \Throwable $e ) {
// If WP-Stash fails to initialize, we can't determine the driver
$message = 'WP-Stash';
}
} elseif ( function_exists( 'w3_instance' ) ) {
$config = w3_instance( 'W3_Config' );
if ( $config->get_boolean( 'objectcache.enabled' ) ) {
$message = 'W3TC ' . $config->get_string( 'objectcache.engine' );
}
}
// If still unknown, provide the class name for debugging
if ( 'Unknown' === $message && is_object( $wp_object_cache ) ) {
$message = 'Unknown: ' . get_class( $wp_object_cache );
}
} else {
$message = 'Default';
}
return $message;
}
/**
* Clear WordPress internal object caches.
*
* In long-running scripts, the internal caches on `$wp_object_cache` and `$wpdb`
* can grow to consume gigabytes of memory. Periodically calling this utility
* can help with memory management.
*
* @access public
* @category System
* @deprecated 1.5.0
*
* @return void
*/
function wp_clear_object_cache() {
global $wpdb, $wp_object_cache;
$wpdb->queries = [];
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) ) {
if ( wp_cache_supports( 'flush_runtime' ) ) {
wp_cache_flush_runtime();
return;
}
}
if ( ! is_object( $wp_object_cache ) ) {
return;
}
// The following are Memcached (Redux) plugin specific (see https://core.trac.wordpress.org/ticket/31463).
// @phpstan-ignore property.notFound
if ( isset( $wp_object_cache->group_ops ) ) {
$wp_object_cache->group_ops = [];
}
// @phpstan-ignore property.notFound
if ( isset( $wp_object_cache->stats ) ) {
$wp_object_cache->stats = [];
}
// @phpstan-ignore property.notFound
if ( isset( $wp_object_cache->memcache_debug ) ) {
$wp_object_cache->memcache_debug = [];
}
// Used by `WP_Object_Cache` also.
// @phpstan-ignore property.notFound
if ( isset( $wp_object_cache->cache ) ) {
$wp_object_cache->cache = [];
}
}
/**
* Get a set of tables in the database.
*
* Interprets common command-line options into a resolved set of table names.
*
* @param array<string> $args Provided table names, or tables with wildcards.
* @param array<string, bool|string> $assoc_args Optional flags for groups of tables (e.g. --network)
* @return array<string>
*/
function wp_get_table_names( $args, $assoc_args = [] ) {
global $wpdb;
// Abort if incompatible args supplied.
if ( get_flag_value( $assoc_args, 'base-tables-only' ) && get_flag_value( $assoc_args, 'views-only' ) ) {
WP_CLI::error( 'You cannot supply --base-tables-only and --views-only at the same time.' );
}
// Pre-load tables SQL query with Views restriction if needed.
if ( get_flag_value( $assoc_args, 'base-tables-only' ) ) {
$tables_sql = 'SHOW FULL TABLES WHERE Table_Type = "BASE TABLE"';
} elseif ( get_flag_value( $assoc_args, 'views-only' ) ) {
$tables_sql = 'SHOW FULL TABLES WHERE Table_Type = "VIEW"';
}
if ( get_flag_value( $assoc_args, 'all-tables' ) ) {
if ( empty( $tables_sql ) ) {
$tables_sql = 'SHOW TABLES';
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is safe, see above.
$tables = $wpdb->get_col( $tables_sql, 0 );
} elseif ( get_flag_value( $assoc_args, 'all-tables-with-prefix' ) ) {
if ( empty( $tables_sql ) ) {
$tables_sql = $wpdb->prepare( 'SHOW TABLES LIKE %s', esc_like( $wpdb->get_blog_prefix() ) . '%' );
} else {
$tables_sql .= sprintf( " AND %s LIKE '%s'", esc_sql_ident( 'Tables_in_' . $wpdb->dbname ), esc_like( $wpdb->get_blog_prefix() ) . '%' );
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared, see above.
$tables = $wpdb->get_col( $tables_sql, 0 );
} else {
$scope = get_flag_value( $assoc_args, 'scope', 'all' );
// Note: BC change 1.5.0, taking scope into consideration for network also.
if ( get_flag_value( $assoc_args, 'network' ) && is_multisite() ) {
$network_global_scope = in_array( $scope, [ 'all', 'global', 'ms_global' ], true ) ? ( 'all' === $scope ? 'global' : $scope ) : '';
$wp_tables = array_values( $wpdb->tables( $network_global_scope ) );
if ( in_array( $scope, [ 'all', 'blog' ], true ) ) {
// Do directly for compat with old WP versions. Note: private, deleted, archived sites are not excluded.
$blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs WHERE site_id = $wpdb->siteid" );
foreach ( $blog_ids as $blog_id ) {
$wp_tables = array_merge( $wp_tables, array_values( $wpdb->tables( 'blog', true /*prefix*/, $blog_id ) ) );
}
}
} else {
$wp_tables = array_values( $wpdb->tables( $scope ) );
}
// The global_terms_enabled() function has been deprecated with WP 6.1+.
// @phpstan-ignore function.deprecated
if ( wp_version_compare( '6.1', '>=' ) || ! global_terms_enabled() ) { // phpcs:ignore WordPress.WP.DeprecatedFunctions.global_terms_enabledFound
// Only include sitecategories when it's actually enabled.
$wp_tables = array_values( array_diff( $wp_tables, [ $wpdb->sitecategories ] ) );
}
// Note: BC change 1.5.0, tables are sorted (via TABLES view).
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- uses esc_sql_ident() and $wpdb->_escape().
$tables = $wpdb->get_col( sprintf( "SHOW TABLES WHERE %s IN ('%s')", esc_sql_ident( 'Tables_in_' . $wpdb->dbname ), implode( "', '", $wpdb->_escape( $wp_tables ) ) ) );
// Filter tables after the query for improved SQLite compatibility.
// See https://github.com/WordPress/sqlite-database-integration/issues/319.
if ( 'sqlite' === get_db_type() ) {
$tables = array_values( array_intersect( $tables, $wp_tables ) );
}
if ( get_flag_value( $assoc_args, 'base-tables-only' ) || get_flag_value( $assoc_args, 'views-only' ) ) {
// Apply Views restriction args if needed.
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared, see above.
$views_query_tables = $wpdb->get_col( $tables_sql, 0 ); // @phpstan-ignore variable.undefined
$tables = array_intersect( $tables, $views_query_tables );
}
}
// Filter by `$args`.
if ( $args ) {
$args_tables = [];
foreach ( $args as $arg ) {
if ( false !== strpos( $arg, '*' ) || false !== strpos( $arg, '?' ) ) {
$args_tables = array_merge(
$args_tables,
array_filter(
$tables,
function ( $v ) use ( $arg ) {
return fnmatch( $arg, $v );
}
)
);
} else {
$args_tables[] = $arg;
}
}
$args_tables = array_values( array_unique( $args_tables ) );
$tables = array_values( array_intersect( $tables, $args_tables ) );
if ( empty( $tables ) ) {
WP_CLI::error( sprintf( "Couldn't find any tables matching: %s", implode( ' ', $args ) ) );
}
}
return $tables;
}
/**
* Failsafe use of the WordPress wp_strip_all_tags() function.
*
* Automatically falls back to strip_tags() function if the WP function is not
* available.
*
* @param string $string String to strip the tags from.
* @return string String devoid of tags.
*/
function strip_tags( $string ) {
if ( function_exists( 'wp_strip_all_tags' ) ) {
return \wp_strip_all_tags( $string );
}
$string = (string) preg_replace(
'@<(script|style)[^>]*?>.*?</\\1>@si',
'',
$string
);
// phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Fallback.
$string = \strip_tags( $string );
return trim( $string );
}