forked from wp-cli/wp-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.php
More file actions
1890 lines (1660 loc) · 52.1 KB
/
utils.php
File metadata and controls
1890 lines (1660 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Utilities that do NOT depend on WordPress code.
namespace WP_CLI\Utils;
use ArrayIterator;
use cli;
use cli\progress\Bar;
use cli\Shell;
use Closure;
use Composer\Semver\Comparator;
use Composer\Semver\Semver;
use Exception;
use Mustache_Engine;
use ReflectionFunction;
use RuntimeException;
use WP_CLI;
use WP_CLI\ExitException;
use WP_CLI\Formatter;
use WP_CLI\Inflector;
use WP_CLI\Iterators\Transform;
use WP_CLI\NoOp;
use WP_CLI\Process;
use WP_CLI\RequestsLibrary;
/**
* File stream wrapper prefix for Phar archives.
*
* @var string
*/
const PHAR_STREAM_PREFIX = 'phar://';
/**
* Regular expression pattern to match __FILE__ and __DIR__ constants.
*
* We try to be smart and only replace the constants when they are not within quotes.
* Regular expressions being stateless, this is probably not 100% correct for edge cases.
*
* @see https://regex101.com/r/9hXp5d/11
* @see https://stackoverflow.com/a/171499/933065
*
* @var string
*/
const FILE_DIR_PATTERN = '%(?>#.*?$)|(?>//.*?$)|(?>/\*.*?\*/)|(?>\'(?:(?=(\\\\?))\1.)*?\')|(?>"(?:(?=(\\\\?))\2.)*?")|(?<file>\b__FILE__\b)|(?<dir>\b__DIR__\b)%ms';
/**
* Check if a certain path is within a Phar archive.
*
* If no path is provided, the function checks whether the current WP_CLI instance is
* running from within a Phar archive.
*
* @param string|null $path Optional. Path to check. Defaults to null, which checks WP_CLI_ROOT.
*/
function inside_phar( $path = null ) {
if ( null === $path ) {
if ( ! defined( 'WP_CLI_ROOT' ) ) {
return false;
}
$path = WP_CLI_ROOT;
}
return 0 === strpos( $path, PHAR_STREAM_PREFIX );
}
/**
* Extract a file from a Phar archive.
*
* Files that need to be read by external programs have to be extracted from the Phar archive.
* If the file is not within a Phar archive, the function returns the path unchanged.
*
* @param string $path Path to the file to extract.
* @return string Path to the extracted file.
*/
function extract_from_phar( $path ) {
if ( ! inside_phar( $path ) ) {
return $path;
}
$fname = basename( $path );
$tmp_path = get_temp_dir() . uniqid( 'wp-cli-extract-from-phar-', true ) . "-$fname";
copy( $path, $tmp_path );
register_shutdown_function(
function () use ( $tmp_path ) {
if ( file_exists( $tmp_path ) ) {
unlink( $tmp_path );
}
}
);
return $tmp_path;
}
function load_dependencies() {
if ( inside_phar() ) {
if ( file_exists( WP_CLI_ROOT . '/vendor/autoload.php' ) ) {
require WP_CLI_ROOT . '/vendor/autoload.php';
} elseif ( file_exists( dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php' ) ) {
require dirname( dirname( WP_CLI_ROOT ) ) . '/autoload.php';
}
return;
}
$has_autoload = false;
foreach ( get_vendor_paths() as $vendor_path ) {
if ( file_exists( $vendor_path . '/autoload.php' ) ) {
require $vendor_path . '/autoload.php';
$has_autoload = true;
break;
}
}
if ( ! $has_autoload ) {
fwrite( STDERR, "Internal error: Can't find Composer autoloader.\nTry running: composer install\n" );
exit( 3 );
}
}
function get_vendor_paths() {
$vendor_paths = [
WP_CLI_ROOT . '/../../../vendor', // Part of a larger project / installed via Composer (preferred).
WP_CLI_ROOT . '/vendor', // Top-level project / installed as Git clone.
];
$maybe_composer_json = WP_CLI_ROOT . '/../../../composer.json';
if ( file_exists( $maybe_composer_json ) && is_readable( $maybe_composer_json ) ) {
$composer = json_decode( file_get_contents( $maybe_composer_json ) );
if ( ! empty( $composer->config ) && ! empty( $composer->config->{'vendor-dir'} ) ) {
array_unshift( $vendor_paths, WP_CLI_ROOT . '/../../../' . $composer->config->{'vendor-dir'} );
}
}
return $vendor_paths;
}
// Using require() directly inside a class grants access to private methods to the loaded code.
function load_file( $path ) {
require_once $path;
}
function load_command( $name ) {
$path = WP_CLI_ROOT . "/php/commands/$name.php";
if ( is_readable( $path ) ) {
include_once $path;
}
}
/**
* Like array_map(), except it returns a new iterator, instead of a modified array.
*
* Example:
*
* $arr = array('Football', 'Socker');
*
* $it = iterator_map($arr, 'strtolower', function($val) {
* return str_replace('foo', 'bar', $val);
* });
*
* foreach ( $it as $val ) {
* var_dump($val);
* }
*
* @param array|object $it Either a plain array or another iterator.
* @param callback $fn The function to apply to an element.
* @return object An iterator that applies the given callback(s).
*/
function iterator_map( $it, $fn ) {
if ( is_array( $it ) ) {
$it = new ArrayIterator( $it );
}
if ( ! method_exists( $it, 'add_transform' ) ) {
$it = new Transform( $it );
}
foreach ( array_slice( func_get_args(), 1 ) as $fn ) {
$it->add_transform( $fn );
}
return $it;
}
/**
* Search for file by walking up the directory tree until the first file is found or until $stop_check($dir) returns true.
*
* @param string|array $files The files (or file) to search for.
* @param string|null $dir The directory to start searching from; defaults to CWD.
* @param callable $stop_check Function which is passed the current dir each time a directory level is traversed.
* @return null|string Null if the file was not found.
*/
function find_file_upward( $files, $dir = null, $stop_check = null ) {
$files = (array) $files;
if ( is_null( $dir ) ) {
$dir = getcwd();
}
while ( is_readable( $dir ) ) {
// Stop walking up when the supplied callable returns true being passed the $dir
if ( is_callable( $stop_check ) && call_user_func( $stop_check, $dir ) ) {
return null;
}
foreach ( $files as $file ) {
$path = $dir . DIRECTORY_SEPARATOR . $file;
if ( file_exists( $path ) ) {
return $path;
}
}
$parent_dir = dirname( $dir );
if ( empty( $parent_dir ) || $parent_dir === $dir ) {
break;
}
$dir = $parent_dir;
}
return null;
}
function is_path_absolute( $path ) {
// Windows.
if ( isset( $path[1] ) && ':' === $path[1] ) {
return true;
}
return isset( $path[0] ) && '/' === $path[0];
}
/**
* Composes positional arguments into a command string.
*
* @param array $args Positional arguments to compose.
* @return string
*/
function args_to_str( $args ) {
return ' ' . implode( ' ', array_map( 'escapeshellarg', $args ) );
}
/**
* Composes associative arguments into a command string.
*
* @param array $assoc_args Associative arguments to compose.
* @return string
*/
function assoc_args_to_str( $assoc_args ) {
$str = '';
foreach ( $assoc_args as $key => $value ) {
if ( true === $value ) {
$str .= " --$key";
} elseif ( is_array( $value ) ) {
foreach ( $value as $v ) {
$str .= assoc_args_to_str(
[
$key => $v,
]
);
}
} else {
$str .= " --$key=" . escapeshellarg( $value );
}
}
return $str;
}
/**
* Given a template string and an arbitrary number of arguments,
* returns the final command, with the parameters escaped.
*/
function esc_cmd( $cmd ) {
if ( func_num_args() < 2 ) {
trigger_error( 'esc_cmd() requires at least two arguments.', E_USER_WARNING );
}
$args = func_get_args();
$cmd = array_shift( $args );
return vsprintf( $cmd, array_map( 'escapeshellarg', $args ) );
}
/**
* Gets path to WordPress configuration.
*
* @return string
*/
function locate_wp_config() {
static $path;
if ( null === $path ) {
$path = false;
if ( getenv( 'WP_CONFIG_PATH' ) && file_exists( getenv( 'WP_CONFIG_PATH' ) ) ) {
$path = getenv( 'WP_CONFIG_PATH' );
} elseif ( file_exists( ABSPATH . 'wp-config.php' ) ) {
$path = ABSPATH . 'wp-config.php';
} elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
$path = dirname( ABSPATH ) . '/wp-config.php';
}
if ( $path ) {
$path = realpath( $path );
}
}
return $path;
}
function wp_version_compare( $since, $operator ) {
$wp_version = str_replace( '-src', '', $GLOBALS['wp_version'] );
$since = str_replace( '-src', '', $since );
return version_compare( $wp_version, $since, $operator );
}
/**
* Render a collection of items as an ASCII table, JSON, CSV, YAML, list of ids, or count.
*
* Given a collection of items with a consistent data structure:
*
* ```
* $items = array(
* array(
* 'key' => 'foo',
* 'value' => 'bar',
* )
* );
* ```
*
* Render `$items` as an ASCII table:
*
* ```
* WP_CLI\Utils\format_items( 'table', $items, array( 'key', 'value' ) );
*
* # +-----+-------+
* # | key | value |
* # +-----+-------+
* # | foo | bar |
* # +-----+-------+
* ```
*
* Or render `$items` as YAML:
*
* ```
* WP_CLI\Utils\format_items( 'yaml', $items, array( 'key', 'value' ) );
*
* # ---
* # -
* # key: foo
* # value: bar
* ```
*
* @access public
* @category Output
*
* @param string $format Format to use: 'table', 'json', 'csv', 'yaml', 'ids', 'count'.
* @param array $items An array of items to output.
* @param array|string $fields Named fields for each item of data. Can be array or comma-separated list.
*/
function format_items( $format, $items, $fields ) {
$assoc_args = [
'format' => $format,
'fields' => $fields,
];
$formatter = new Formatter( $assoc_args );
$formatter->display_items( $items );
}
/**
* Write data as CSV to a given file.
*
* @access public
*
* @param resource $fd File descriptor.
* @param array $rows Array of rows to output.
* @param array $headers List of CSV columns (optional).
*/
function write_csv( $fd, $rows, $headers = [] ) {
if ( ! empty( $headers ) ) {
fputcsv( $fd, $headers );
}
foreach ( $rows as $row ) {
if ( ! empty( $headers ) ) {
$row = pick_fields( $row, $headers );
}
fputcsv( $fd, array_values( $row ) );
}
}
/**
* Pick fields from an associative array or object.
*
* @param array|object $item Associative array or object to pick fields from.
* @param array $fields List of fields to pick.
* @return array
*/
function pick_fields( $item, $fields ) {
$values = [];
if ( is_object( $item ) ) {
foreach ( $fields as $field ) {
$values[ $field ] = isset( $item->$field ) ? $item->$field : null;
}
} else {
foreach ( $fields as $field ) {
$values[ $field ] = isset( $item[ $field ] ) ? $item[ $field ] : null;
}
}
return $values;
}
/**
* Launch system's $EDITOR for the user to edit some text.
*
* @access public
* @category Input
*
* @param string $input Some form of text to edit (e.g. post content).
* @param string $title Title to display in the editor.
* @param string $ext Extension to use with the temp file.
* @return string|bool Edited text, if file is saved from editor; false, if no change to file.
*/
function launch_editor_for_input( $input, $title = 'WP-CLI', $ext = 'tmp' ) {
check_proc_available( 'launch_editor_for_input' );
$tmpdir = get_temp_dir();
do {
$tmpfile = basename( $title );
$tmpfile = preg_replace( '|\.[^.]*$|', '', $tmpfile );
$tmpfile .= '-' . substr( md5( mt_rand() ), 0, 6 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- no crypto and WP not loaded.
$tmpfile = $tmpdir . $tmpfile . '.' . $ext;
$fp = fopen( $tmpfile, 'xb' );
if ( ! $fp && is_writable( $tmpdir ) && file_exists( $tmpfile ) ) {
$tmpfile = '';
continue;
}
if ( $fp ) {
fclose( $fp );
}
} while ( ! $tmpfile );
if ( ! $tmpfile ) {
WP_CLI::error( 'Error creating temporary file.' );
}
file_put_contents( $tmpfile, $input );
$editor = getenv( 'EDITOR' );
if ( ! $editor ) {
$editor = is_windows() ? 'notepad' : 'vi';
}
$descriptorspec = [ STDIN, STDOUT, STDERR ];
$process = proc_open_compat( "$editor " . escapeshellarg( $tmpfile ), $descriptorspec, $pipes );
$r = proc_close( $process );
if ( $r ) {
exit( $r );
}
$output = file_get_contents( $tmpfile );
unlink( $tmpfile );
if ( $output === $input ) {
return false;
}
return $output;
}
/**
* @param string $raw_host MySQL host string, as defined in wp-config.php.
*
* @return array
*/
function mysql_host_to_cli_args( $raw_host ) {
$assoc_args = [];
/**
* If the host string begins with 'p:' for a persistent db connection,
* replace 'p:' with nothing.
*/
if ( substr( $raw_host, 0, 2 ) === 'p:' ) {
$raw_host = substr_replace( $raw_host, '', 0, 2 );
}
$host_parts = explode( ':', $raw_host );
if ( count( $host_parts ) === 2 ) {
list( $assoc_args['host'], $extra ) = $host_parts;
$extra = trim( $extra );
if ( is_numeric( $extra ) ) {
$assoc_args['port'] = (int) $extra;
$assoc_args['protocol'] = 'tcp';
} elseif ( '' !== $extra ) {
$assoc_args['socket'] = $extra;
}
} else {
$assoc_args['host'] = $raw_host;
}
return $assoc_args;
}
/**
* Run a MySQL command and optionally return the output.
*
* @since v2.5.0 Deprecated $descriptors argument.
*
* @param string $cmd Command to run.
* @param array $assoc_args Associative array of arguments to use.
* @param mixed $_ Deprecated. Former $descriptors argument.
* @param bool $send_to_shell Optional. Whether to send STDOUT and STDERR
* immediately to the shell. Defaults to true.
* @param bool $interactive Optional. Whether MySQL is meant to be
* executed as an interactive process. Defaults
* to false.
*
* @return array {
* Associative array containing STDOUT and STDERR output.
*
* @type string $stdout Output that was sent to STDOUT.
* @type string $stderr Output that was sent to STDERR.
* @type int $exit_code Exit code of the process.
* }
*/
function run_mysql_command( $cmd, $assoc_args, $_ = null, $send_to_shell = true, $interactive = false ) {
check_proc_available( 'run_mysql_command' );
$descriptors = ( $interactive || $send_to_shell ) ?
[
0 => STDIN,
1 => STDOUT,
2 => STDERR,
] :
[
0 => STDIN,
1 => [ 'pipe', 'w' ],
2 => [ 'pipe', 'w' ],
];
$stdout = '';
$stderr = '';
$pipes = [];
if ( isset( $assoc_args['host'] ) ) {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_host_to_cli_args -- Misidentified as PHP native MySQL function.
$assoc_args = array_merge( $assoc_args, mysql_host_to_cli_args( $assoc_args['host'] ) );
}
if ( isset( $assoc_args['pass'] ) ) {
$old_password = getenv( 'MYSQL_PWD' );
putenv( 'MYSQL_PWD=' . $assoc_args['pass'] );
unset( $assoc_args['pass'] );
}
$final_cmd = force_env_on_nix_systems( $cmd ) . assoc_args_to_str( $assoc_args );
WP_CLI::debug( 'Final MySQL command: ' . $final_cmd, 'db' );
$process = proc_open_compat( $final_cmd, $descriptors, $pipes );
if ( isset( $old_password ) ) {
putenv( 'MYSQL_PWD=' . $old_password );
}
if ( ! $process ) {
WP_CLI::debug( 'Failed to create a valid process using proc_open_compat()', 'db' );
exit( 1 );
}
if ( is_resource( $process ) && ! $send_to_shell && ! $interactive ) {
$stdout = stream_get_contents( $pipes[1] );
$stderr = stream_get_contents( $pipes[2] );
fclose( $pipes[1] );
fclose( $pipes[2] );
}
$exit_code = proc_close( $process );
if ( $exit_code && ( $send_to_shell || $interactive ) ) {
exit( $exit_code );
}
return [
$stdout,
$stderr,
$exit_code,
];
}
/**
* Render PHP or other types of files using Mustache templates.
*
* IMPORTANT: Automatic HTML escaping is disabled!
*/
function mustache_render( $template_name, $data = [] ) {
if ( ! file_exists( $template_name ) ) {
$template_name = WP_CLI_ROOT . "/templates/$template_name";
}
$template = file_get_contents( $template_name );
$mustache = new Mustache_Engine(
[
'escape' => function ( $val ) {
return $val; },
]
);
return $mustache->render( $template, $data );
}
/**
* Create a progress bar to display percent completion of a given operation.
*
* Progress bar is written to STDOUT, and disabled when command is piped. Progress
* advances with `$progress->tick()`, and completes with `$progress->finish()`.
* Process bar also indicates elapsed time and expected total time.
*
* ```
* # `wp user generate` ticks progress bar each time a new user is created.
* #
* # $ wp user generate --count=500
* # Generating users 22 % [=======> ] 0:05 / 0:23
*
* $progress = \WP_CLI\Utils\make_progress_bar( 'Generating users', $count );
* for ( $i = 0; $i < $count; $i++ ) {
* // uses wp_insert_user() to insert the user
* $progress->tick();
* }
* $progress->finish();
* ```
*
* @access public
* @category Output
*
* @param string $message Text to display before the progress bar.
* @param integer $count Total number of ticks to be performed.
* @param int $interval Optional. The interval in milliseconds between updates. Default 100.
* @return \cli\progress\Bar|\WP_CLI\NoOp
*/
function make_progress_bar( $message, $count, $interval = 100 ) {
if ( Shell::isPiped() ) {
return new NoOp();
}
return new Bar( $message, $count, $interval );
}
/**
* Helper function to use wp_parse_url when available or fall back to PHP's
* parse_url if not.
*
* Additionally, this adds 'http://' to the URL if no scheme was found.
*
* @param string $url The URL to parse.
* @param int $component Optional. The specific component to retrieve.
* Use one of the PHP predefined constants to
* specify which one. Defaults to -1 (= return
* all parts as an array).
* @param bool $auto_add_scheme Optional. Automatically add an http:// scheme if
* none was found. Defaults to true.
* @return mixed False on parse failure; Array of URL components on success;
* When a specific component has been requested: null if the
* component doesn't exist in the given URL; a string or - in the
* case of PHP_URL_PORT - integer when it does. See parse_url()'s
* return values.
*/
function parse_url( $url, $component = - 1, $auto_add_scheme = true ) {
if (
function_exists( 'wp_parse_url' )
&& (
-1 === $component
|| wp_version_compare( '4.7', '>=' )
)
) {
$url_parts = wp_parse_url( $url, $component );
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Fallback.
$url_parts = \parse_url( $url, $component );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Own version based on WP one.
if ( $auto_add_scheme && ! parse_url( $url, PHP_URL_SCHEME, false ) ) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- Own version based on WP one.
$url_parts = parse_url( 'http://' . $url, $component, false );
}
return $url_parts;
}
/**
* Check if we're running in a Windows environment (cmd.exe).
*
* @return bool
*/
function is_windows() {
$test_is_windows = getenv( 'WP_CLI_TEST_IS_WINDOWS' );
return false !== $test_is_windows ? (bool) $test_is_windows : strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN';
}
/**
* Replace magic constants in some PHP source code.
*
* Replaces the __FILE__ and __DIR__ magic constants with the values they are
* supposed to represent at runtime.
*
* @param string $source The PHP code to manipulate.
* @param string $path The path to use instead of the magic constants.
* @return string Adapted PHP code.
*/
function replace_path_consts( $source, $path ) {
// Solve issue with Windows allowing single quotes in account names.
$file = addslashes( $path );
if ( file_exists( $file ) ) {
$file = realpath( $file );
}
$dir = dirname( $file );
// Replace __FILE__ and __DIR__ constants with value of $file or $dir.
return preg_replace_callback(
FILE_DIR_PATTERN,
static function ( $matches ) use ( $file, $dir ) {
if ( ! empty( $matches['file'] ) ) {
return "'{$file}'";
}
if ( ! empty( $matches['dir'] ) ) {
return "'{$dir}'";
}
return $matches[0];
},
$source
);
}
/**
* Make a HTTP request to a remote URL.
*
* Wraps the Requests HTTP library to ensure every request includes a cert.
*
* ```
* # `wp core download` verifies the hash for a downloaded WordPress archive
*
* $md5_response = Utils\http_request( 'GET', $download_url . '.md5' );
* if ( 20 != substr( $md5_response->status_code, 0, 2 ) ) {
* WP_CLI::error( "Couldn't access md5 hash for release (HTTP code {$response->status_code})" );
* }
* ```
*
* @access public
*
* @param string $method HTTP method (GET, POST, DELETE, etc.).
* @param string $url URL to make the HTTP request to.
* @param array|null $data Data to send either as a query string for GET/HEAD requests,
* or in the body for POST requests.
* @param array $headers Add specific headers to the request.
* @param array $options {
* Optional. An associative array of additional request options.
*
* @type bool $halt_on_error Whether or not command execution should be halted on error. Default: true
* @type bool|string $verify A boolean to use enable/disable SSL verification
* or string absolute path to CA cert to use.
* Defaults to detected CA cert bundled with the Requests library.
* @type bool $insecure Whether to retry automatically without certificate validation.
* }
* @return object
* @throws RuntimeException If the request failed.
* @throws ExitException If the request failed and $halt_on_error is true.
*/
function http_request( $method, $url, $data = null, $headers = [], $options = [] ) {
$insecure = isset( $options['insecure'] ) && (bool) $options['insecure'];
$halt_on_error = ! isset( $options['halt_on_error'] ) || (bool) $options['halt_on_error'];
unset( $options['halt_on_error'] );
if ( ! isset( $options['verify'] ) ) {
// 'curl.cainfo' enforces the CA file to use, otherwise fallback to system-wide defaults then use the embedded CA file.
$options['verify'] = ! empty( ini_get( 'curl.cainfo' ) ) ? ini_get( 'curl.cainfo' ) : true;
}
RequestsLibrary::register_autoloader();
$request_method = [ RequestsLibrary::get_class_name(), 'request' ];
try {
try {
return $request_method( $url, $headers, $data, $method, $options );
} catch ( Exception $exception ) {
if ( RequestsLibrary::is_requests_exception( $exception ) ) {
if (
true !== $options['verify']
|| 'curlerror' !== $exception->getType()
|| curl_errno( $exception->getData() ) !== CURLE_SSL_CACERT
) {
throw $exception;
}
$options['verify'] = get_default_cacert( $halt_on_error );
return $request_method( $url, $headers, $data, $method, $options );
}
throw $exception;
}
} catch ( Exception $exception ) {
if ( RequestsLibrary::is_requests_exception( $exception ) ) {
// CURLE_SSL_CACERT_BADFILE only defined for PHP >= 7.
if (
! $insecure
||
'curlerror' !== $exception->getType()
||
! in_array( curl_errno( $exception->getData() ), [ CURLE_SSL_CONNECT_ERROR, CURLE_SSL_CERTPROBLEM, 77 /*CURLE_SSL_CACERT_BADFILE*/ ], true )
) {
$error_msg = sprintf( "Failed to get url '%s': %s.", $url, $exception->getMessage() );
if ( $halt_on_error ) {
WP_CLI::error( $error_msg );
}
throw new RuntimeException( $error_msg, 0, $exception );
}
$warning = sprintf(
"Re-trying without verify after failing to get verified url '%s' %s.",
$url,
$exception->getMessage()
);
WP_CLI::warning( $warning );
// Disable certificate validation for the next try.
$options['verify'] = false;
try {
return $request_method( $url, $headers, $data, $method, $options );
} catch ( Exception $exception ) {
if ( RequestsLibrary::is_requests_exception( $exception ) ) {
$error_msg = sprintf( "Failed to get non-verified url '%s' %s.", $url, $exception->getMessage() );
if ( $halt_on_error ) {
WP_CLI::error( $error_msg );
}
throw new RuntimeException( $error_msg, 0, $exception );
}
throw $exception;
}
}
throw $exception;
}
}
/**
* Gets the full path to the default CA cert.
*
* @param bool $halt_on_error Whether or not command execution should be halted on error. Default: false
* @return string Absolute path to the default CA cert.
* @throws RuntimeException If unable to locate the cert.
* @throws ExitException If unable to locate the cert and $halt_on_error is true.
*/
function get_default_cacert( $halt_on_error = false ) {
$cert_path = RequestsLibrary::get_bundled_certificate_path();
$error_msg = 'Cannot find SSL certificate.';
if ( inside_phar( $cert_path ) ) {
// cURL can't read Phar archives.
return extract_from_phar( $cert_path );
}
if ( file_exists( $cert_path ) ) {
return $cert_path;
}
if ( $halt_on_error ) {
WP_CLI::error( $error_msg );
}
throw new RuntimeException( $error_msg );
}
/**
* Increments a version string using the "x.y.z-pre" format.
*
* Can increment the major, minor or patch number by one.
* If $new_version == "same" the version string is not changed.
* If $new_version is not a known keyword, it will be used as the new version string directly.
*
* @param string $current_version
* @param string $new_version
* @return string
*/
function increment_version( $current_version, $new_version ) {
// split version assuming the format is x.y.z-pre.
$current_version = explode( '-', $current_version, 2 );
$current_version[0] = explode( '.', $current_version[0] );
switch ( $new_version ) {
case 'same':
// do nothing.
break;
case 'patch':
++$current_version[0][2];
$current_version = [ $current_version[0] ]; // Drop possible pre-release info.
break;
case 'minor':
++$current_version[0][1];
$current_version[0][2] = 0;
$current_version = [ $current_version[0] ]; // Drop possible pre-release info.
break;
case 'major':
++$current_version[0][0];
$current_version[0][1] = 0;
$current_version[0][2] = 0;
$current_version = [ $current_version[0] ]; // Drop possible pre-release info.
break;
default: // not a keyword.
$current_version = [ [ $new_version ] ];
break;
}
// Reconstruct version string.
$current_version[0] = implode( '.', $current_version[0] );
$current_version = implode( '-', $current_version );
return $current_version;
}
/**
* Compare two version strings to get the named semantic version.
*
* @access public
*
* @param string $new_version
* @param string $original_version
* @return string 'major', 'minor', 'patch'
*/
function get_named_sem_ver( $new_version, $original_version ) {
if ( ! Comparator::greaterThan( $new_version, $original_version ) ) {
return '';
}
$parts = explode( '-', $original_version );
$bits = explode( '.', $parts[0] );
$major = $bits[0];
if ( isset( $bits[1] ) ) {
$minor = $bits[1];
}
if ( isset( $bits[2] ) ) {
$patch = $bits[2];
}
try {
if ( isset( $minor ) && Semver::satisfies( $new_version, "{$major}.{$minor}.x" ) ) {
return 'patch';
}
if ( Semver::satisfies( $new_version, "{$major}.x.x" ) ) {
return 'minor';
}
} catch ( \UnexpectedValueException $e ) {
return '';
}
return 'major';
}
/**
* Return the flag value or, if it's not set, the $default value.
*
* Because flags can be negated (e.g. --no-quiet to negate --quiet), this
* function provides a safer alternative to using
* `isset( $assoc_args['quiet'] )` or similar.
*
* @access public
* @category Input
*
* @param array $assoc_args Arguments array.
* @param string $flag Flag to get the value.
* @param mixed $default Default value for the flag. Default: NULL.
* @return mixed
*/
function get_flag_value( $assoc_args, $flag, $default = null ) {
return isset( $assoc_args[ $flag ] ) ? $assoc_args[ $flag ] : $default;
}
/**
* Get the home directory.