-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathCore_Command.php
More file actions
1967 lines (1738 loc) · 62.7 KB
/
Core_Command.php
File metadata and controls
1967 lines (1738 loc) · 62.7 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
use Composer\Semver\Comparator;
use WP_CLI\Extractor;
use WP_CLI\Iterators\Table as TableIterator;
use WP_CLI\Utils;
use WP_CLI\Formatter;
use WP_CLI\Loggers;
use WP_CLI\WpOrgApi;
/**
* Downloads, installs, updates, and manages a WordPress installation.
*
* ## EXAMPLES
*
* # Download WordPress core
* $ wp core download --locale=nl_NL
* Downloading WordPress 4.5.2 (nl_NL)...
* md5 hash verified: c5366d05b521831dd0b29dfc386e56a5
* Success: WordPress downloaded.
*
* # Install WordPress
* $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword --admin_email=info@example.com
* Success: WordPress installed successfully.
*
* # Display the WordPress version
* $ wp core version
* 4.5.2
*
* @package wp-cli
*
* @phpstan-type HTTP_Response array{headers: array<string, string>, body: string, response: array{code:false|int, message: false|string}, cookies: array<string, string>, http_response: mixed}
*/
class Core_Command extends WP_CLI_Command {
/**
* Stores HTTP API errors encountered during version check.
*
* @var \WP_Error|null
*/
private $version_check_error = null;
/**
* Checks for WordPress updates via Version Check API.
*
* Lists the most recent versions when there are updates available,
* or success message when up to date.
*
* ## OPTIONS
*
* [--minor]
* : Compare only the first two parts of the version number.
*
* [--major]
* : Compare only the first part of the version number.
*
* [--force-check]
* : Bypass the transient cache and force a fresh update check.
*
* [--field=<field>]
* : Prints the value of a single field for each update.
*
* [--fields=<fields>]
* : Limit the output to specific object fields. Defaults to version,update_type,package_url.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - count
* - json
* - yaml
* ---
*
* ## EXAMPLES
*
* $ wp core check-update
* +---------+-------------+-------------------------------------------------------------+
* | version | update_type | package_url |
* +---------+-------------+-------------------------------------------------------------+
* | 4.5.2 | major | https://downloads.wordpress.org/release/wordpress-4.5.2.zip |
* +---------+-------------+-------------------------------------------------------------+
*
* @subcommand check-update
*
* @param string[] $args Positional arguments. Unused.
* @param array{minor?: bool, major?: bool, 'force-check'?: bool, field?: string, format: string} $assoc_args Associative arguments.
*/
public function check_update( $args, $assoc_args ) {
$format = Utils\get_flag_value( $assoc_args, 'format', 'table' );
$updates = $this->get_updates( $assoc_args );
if ( $updates || 'table' !== $format ) {
$updates = array_reverse( $updates );
$formatter = new Formatter(
$assoc_args,
[ 'version', 'update_type', 'package_url' ]
);
$formatter->display_items( $updates );
} elseif ( $this->version_check_error ) {
// If there was an HTTP error during version check, show a warning
WP_CLI::warning(
sprintf(
'Failed to check for updates: %s',
$this->version_check_error->get_error_message()
)
);
} else {
WP_CLI::success( 'WordPress is at the latest version.' );
}
}
/**
* Downloads core WordPress files.
*
* Downloads and extracts WordPress core files to the specified path. Uses
* current directory when no path is specified. Downloaded build is verified
* to have the correct md5 and then cached to the local filesystem.
* Subsequent uses of command will use the local cache if it still exists.
*
* ## OPTIONS
*
* [<download-url>]
* : Download directly from a provided URL instead of fetching the URL from the wordpress.org servers.
*
* [--path=<path>]
* : Specify the path in which to install WordPress. Defaults to current
* directory.
*
* [--locale=<locale>]
* : Select which language you want to download.
*
* [--version=<version>]
* : Select which version you want to download. Accepts a version number, 'latest' or 'nightly'.
*
* [--skip-content]
* : Download WP without the default themes and plugins.
*
* [--force]
* : Overwrites existing files, if present.
*
* [--insecure]
* : Retry download without certificate validation if TLS handshake fails. Note: This makes the request vulnerable to a MITM attack.
*
* [--extract]
* : Whether to extract the downloaded file. Defaults to true.
*
* ## EXAMPLES
*
* $ wp core download --locale=nl_NL
* Downloading WordPress 4.5.2 (nl_NL)...
* md5 hash verified: c5366d05b521831dd0b29dfc386e56a5
* Success: WordPress downloaded.
*
* @skipglobalargcheck Reusing `--path` on purpose.
* @when before_wp_load
*
* @param array{0?: string} $args Positional arguments.
* @param array{path?: string, locale?: string, version?: string, 'skip-content'?: bool, force?: bool, insecure?: bool, extract?: bool} $assoc_args Associative arguments.
*/
public function download( $args, $assoc_args ) {
/**
* @var string $download_dir
*/
$download_dir = ! empty( $assoc_args['path'] )
? ( rtrim( $assoc_args['path'], '/\\' ) . '/' )
: ABSPATH;
// Check for files if WordPress already present or not.
$wordpress_present = is_readable( $download_dir . 'wp-load.php' )
|| is_readable( $download_dir . 'wp-mail.php' )
|| is_readable( $download_dir . 'wp-cron.php' )
|| is_readable( $download_dir . 'wp-links-opml.php' );
if ( $wordpress_present && ! Utils\get_flag_value( $assoc_args, 'force' ) ) {
WP_CLI::error( 'WordPress files seem to already be present here.' );
}
if ( ! is_dir( $download_dir ) ) {
if ( ! is_writable( dirname( $download_dir ) ) ) {
WP_CLI::error( "Insufficient permission to create directory '{$download_dir}'." );
}
WP_CLI::log( "Creating directory '{$download_dir}'." );
if ( ! @mkdir( $download_dir, 0777, true /*recursive*/ ) ) {
$error = error_get_last();
if ( $error ) {
WP_CLI::error( "Failed to create directory '{$download_dir}': {$error['message']}." );
} else {
WP_CLI::error( "Failed to create directory '{$download_dir}'." );
}
}
}
if ( ! is_writable( $download_dir ) ) {
WP_CLI::error( "'{$download_dir}' is not writable by current user." );
}
$locale = Utils\get_flag_value( $assoc_args, 'locale', 'en_US' );
$skip_content = Utils\get_flag_value( $assoc_args, 'skip-content', false );
$insecure = Utils\get_flag_value( $assoc_args, 'insecure', false );
$extract = Utils\get_flag_value( $assoc_args, 'extract', true );
if ( $skip_content && ! $extract ) {
WP_CLI::error( 'Cannot use both --skip-content and --no-extract at the same time.' );
}
$download_url = array_shift( $args );
$from_url = ! empty( $download_url );
if ( $from_url ) {
$version = null;
if ( isset( $assoc_args['version'] ) ) {
WP_CLI::error( 'Version option is not available for URL downloads.' );
}
if ( $skip_content || 'en_US' !== $locale ) {
WP_CLI::error( 'Skip content and locale options are not available for URL downloads.' );
}
} elseif ( isset( $assoc_args['version'] ) && 'latest' !== $assoc_args['version'] ) {
$version = $assoc_args['version'];
if ( in_array( strtolower( $version ), [ 'trunk', 'nightly' ], true ) ) {
$version = 'nightly';
}
// Nightly builds and skip content are only available in .zip format.
$extension = ( ( 'nightly' === $version ) || $skip_content )
? 'zip'
: 'tar.gz';
$download_url = $this->get_download_url( $version, $locale, $extension );
} else {
try {
$offer = ( new WpOrgApi( [ 'insecure' => $insecure ] ) )
->get_core_download_offer( $locale );
} catch ( Exception $exception ) {
WP_CLI::error( $exception );
}
if ( ! $offer ) {
WP_CLI::error( "The requested locale ({$locale}) was not found." );
}
$version = $offer['current'];
$download_url = $offer['download'];
if ( ! $skip_content ) {
$download_url = str_replace( '.zip', '.tar.gz', $download_url );
}
}
if ( 'nightly' === $version && 'en_US' !== $locale ) {
WP_CLI::error( 'Nightly builds are only available for the en_US locale.' );
}
$from_version = '';
if ( file_exists( $download_dir . 'wp-includes/version.php' ) ) {
$wp_details = self::get_wp_details( $download_dir );
$from_version = $wp_details['wp_version'];
}
if ( $from_url ) {
WP_CLI::log( "Downloading from {$download_url} ..." );
} else {
WP_CLI::log( "Downloading WordPress {$version} ({$locale})..." );
}
$path_parts = pathinfo( $download_url );
$extension = 'tar.gz';
if ( isset( $path_parts['extension'] ) && 'zip' === $path_parts['extension'] ) {
$extension = 'zip';
if ( $extract && ! class_exists( 'ZipArchive' ) ) {
WP_CLI::error( 'Extracting a zip file requires ZipArchive.' );
}
}
if ( $skip_content && 'zip' !== $extension ) {
WP_CLI::error( 'Skip content is only available for ZIP files.' );
}
$cache = WP_CLI::get_cache();
if ( $from_url ) {
$cache_file = null;
} else {
$cache_key = "core/wordpress-{$version}-{$locale}.{$extension}";
$cache_file = $cache->has( $cache_key );
}
$bad_cache = false;
if ( is_string( $cache_file ) ) {
WP_CLI::log( "Using cached file '{$cache_file}'..." );
$skip_content_cache_file = $skip_content ? self::strip_content_dir( $cache_file ) : null;
if ( $extract ) {
try {
Extractor::extract( $skip_content_cache_file ?: $cache_file, $download_dir );
} catch ( Exception $exception ) {
WP_CLI::warning( 'Extraction failed, downloading a new copy...' );
$bad_cache = true;
}
} else {
copy( $cache_file, $download_dir . basename( $cache_file ) );
}
}
if ( ! $cache_file || $bad_cache ) {
// We need to use a temporary file because piping from cURL to tar is flaky
// on MinGW (and probably in other environments too).
$temp = Utils\get_temp_dir() . uniqid( 'wp_' ) . ".{$extension}";
register_shutdown_function(
function () use ( $temp ) {
if ( file_exists( $temp ) ) {
unlink( $temp );
}
}
);
$headers = [ 'Accept' => 'application/json' ];
$options = [
'timeout' => 600, // 10 minutes ought to be enough for everybody
'filename' => $temp,
'insecure' => $insecure,
];
/** @var \WpOrg\Requests\Response $response */
$response = Utils\http_request( 'GET', $download_url, null, $headers, $options );
if ( 404 === (int) $response->status_code ) {
WP_CLI::error( 'Release not found. Double-check locale or version.' );
} elseif ( 20 !== (int) substr( (string) $response->status_code, 0, 2 ) ) {
WP_CLI::error( "Couldn't access download URL (HTTP code {$response->status_code})." );
}
if ( 'nightly' !== $version ) {
unset( $options['filename'] );
/** @var \WpOrg\Requests\Response $md5_response */
$md5_response = Utils\http_request( 'GET', $download_url . '.md5', null, [], $options );
if ( $md5_response->status_code >= 200 && $md5_response->status_code < 300 ) {
$md5_file = md5_file( $temp );
if ( $md5_file === $md5_response->body ) {
WP_CLI::log( 'md5 hash verified: ' . $md5_file );
} else {
WP_CLI::error( "md5 hash for download ({$md5_file}) is different than the release hash ({$md5_response->body})." );
}
} else {
WP_CLI::warning( "Couldn't access md5 hash for release ({$download_url}.md5, HTTP code {$md5_response->status_code})." );
}
} else {
WP_CLI::warning( 'md5 hash checks are not available for nightly downloads.' );
}
$skip_content_temp = $skip_content ? self::strip_content_dir( $temp ) : null;
if ( $extract ) {
try {
Extractor::extract( $skip_content_temp ?: $temp, $download_dir );
} catch ( Exception $exception ) {
WP_CLI::error( "Couldn't extract WordPress archive. {$exception->getMessage()}" );
}
} else {
copy( $temp, $download_dir . basename( $temp ) );
}
// Do not use the cache for nightly builds or for downloaded URLs
// (the URL could be something like "latest.zip" or "nightly.zip").
if ( ! $from_url && 'nightly' !== $version ) {
$cache->import( $cache_key, $temp );
}
}
if ( $wordpress_present ) {
$this->cleanup_extra_files( $from_version, $version, $locale, $insecure );
}
WP_CLI::success( 'WordPress downloaded.' );
}
/**
* Checks if WordPress is installed.
*
* Determines whether WordPress is installed by checking if the standard
* database tables are installed. Doesn't produce output; uses exit codes
* to communicate whether WordPress is installed.
*
* ## OPTIONS
*
* [--network]
* : Check if this is a multisite installation.
*
* ## EXAMPLES
*
* # Bash script for checking if WordPress is not installed.
*
* if ! wp core is-installed 2>/dev/null; then
* # WP is not installed. Let's try installing it.
* wp core install
* fi
*
* # Bash script for checking if WordPress is installed, with fallback.
*
* if wp core is-installed 2>/dev/null; then
* # WP is installed. Let's do some things we should only do in a confirmed WP environment.
* wp core verify-checksums
* else
* # Fallback if WP is not installed.
* echo 'Hey Friend, you are in the wrong spot. Move in to your WordPress directory and try again.'
* fi
*
* @subcommand is-installed
*
* @param string[] $args Positional arguments. Unused.
* @param array{network?: bool} $assoc_args Associative arguments.
*/
public function is_installed( $args, $assoc_args ) {
if ( is_blog_installed() && ( ! Utils\get_flag_value( $assoc_args, 'network' ) || is_multisite() ) ) {
WP_CLI::halt( 0 );
}
WP_CLI::halt( 1 );
}
/**
* Runs the standard WordPress installation process.
*
* Creates the WordPress tables in the database using the URL, title, and
* default admin user details provided. Performs the famous 5 minute install
* in seconds or less.
*
* Note: if you've installed WordPress in a subdirectory, then you'll need
* to `wp option update siteurl` after `wp core install`. For instance, if
* WordPress is installed in the `/wp` directory and your domain is example.com,
* then you'll need to run `wp option update siteurl http://example.com/wp` for
* your WordPress installation to function properly.
*
* Note: When using custom user tables (e.g. `CUSTOM_USER_TABLE`), the admin
* email and password are ignored if the user_login already exists. If the
* user_login doesn't exist, a new user will be created.
*
* ## OPTIONS
*
* --url=<url>
* : The address of the new site.
*
* --title=<site-title>
* : The title of the new site.
*
* --admin_user=<username>
* : The name of the admin user.
*
* [--admin_password=<password>]
* : The password for the admin user. Defaults to randomly generated string.
*
* --admin_email=<email>
* : The email address for the admin user.
*
* [--locale=<locale>]
* : The locale/language for the installation (e.g. `de_DE`). Default is `en_US`.
*
* [--skip-email]
* : Don't send an email notification to the new admin user.
*
* ## EXAMPLES
*
* # Install WordPress in 5 seconds
* $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword --admin_email=info@example.com
* Success: WordPress installed successfully.
*
* # Install WordPress without disclosing admin_password to bash history
* $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_email=info@example.com --prompt=admin_password < admin_password.txt
*
* @skipglobalargcheck Reusing `--url` on purpose.
*
* @param string[] $args Positional arguments. Unused.
* @param array{url: string, title: string, admin_user: string, admin_password?: string, admin_email: string, locale?: string, 'skip-email'?: bool} $assoc_args Associative arguments.
*/
public function install( $args, $assoc_args ) {
if ( $this->do_install( $assoc_args ) ) {
WP_CLI::success( 'WordPress installed successfully.' );
} else {
WP_CLI::log( 'WordPress is already installed.' );
}
}
/**
* Transforms an existing single-site installation into a multisite installation.
*
* Creates the multisite database tables, and adds the multisite constants
* to wp-config.php.
*
* For those using WordPress with Apache, remember to update the `.htaccess`
* file with the appropriate multisite rewrite rules.
*
* [Review the multisite documentation](https://wordpress.org/support/article/create-a-network/)
* for more details about how multisite works.
*
* ## OPTIONS
*
* [--title=<network-title>]
* : The title of the new network.
*
* [--base=<url-path>]
* : Base path after the domain name that each site url will start with.
* ---
* default: /
* ---
*
* [--subdomains]
* : If passed, the network will use subdomains, instead of subdirectories. Doesn't work with 'localhost'.
*
* [--skip-config]
* : Don't add multisite constants to wp-config.php.
*
* ## EXAMPLES
*
* $ wp core multisite-convert
* Set up multisite database tables.
* Added multisite constants to wp-config.php.
* Success: Network installed. Don't forget to set up rewrite rules.
*
* @subcommand multisite-convert
* @alias install-network
*
* @param string[] $args Positional arguments. Unused.
* @param array{title?: string, base: string, subdomains?: bool, 'skip-config'?: bool} $assoc_args Associative arguments.
*/
public function multisite_convert( $args, $assoc_args ) {
if ( is_multisite() ) {
WP_CLI::error( 'This already is a multisite installation.' );
}
$assoc_args = self::set_multisite_defaults( $assoc_args );
if ( ! isset( $assoc_args['title'] ) ) {
/**
* @var string $blogname
*/
$blogname = get_option( 'blogname' );
// translators: placeholder is blog name
$assoc_args['title'] = sprintf( _x( '%s Sites', 'Default network name' ), $blogname );
}
if ( $this->multisite_convert_( $assoc_args ) ) {
WP_CLI::success( "Network installed. Don't forget to set up rewrite rules (and a .htaccess file, if using Apache)." );
}
}
/**
* Installs WordPress multisite from scratch.
*
* Creates the WordPress tables in the database using the URL, title, and
* default admin user details provided. Then, creates the multisite tables
* in the database and adds multisite constants to the wp-config.php.
*
* For those using WordPress with Apache, remember to update the `.htaccess`
* file with the appropriate multisite rewrite rules.
*
* ## OPTIONS
*
* [--url=<url>]
* : The address of the new site.
*
* [--base=<url-path>]
* : Base path after the domain name that each site url in the network will start with.
* ---
* default: /
* ---
*
* [--subdomains]
* : If passed, the network will use subdomains, instead of subdirectories. Doesn't work with 'localhost'.
*
* --title=<site-title>
* : The title of the new site.
*
* --admin_user=<username>
* : The name of the admin user.
* ---
* default: admin
* ---
*
* [--admin_password=<password>]
* : The password for the admin user. Defaults to randomly generated string.
*
* --admin_email=<email>
* : The email address for the admin user.
*
* [--skip-email]
* : Don't send an email notification to the new admin user.
*
* [--skip-config]
* : Don't add multisite constants to wp-config.php.
*
* ## EXAMPLES
*
* $ wp core multisite-install --title="Welcome to the WordPress" \
* > --admin_user="admin" --admin_password="password" \
* > --admin_email="user@example.com"
* Single site database tables already present.
* Set up multisite database tables.
* Added multisite constants to wp-config.php.
* Success: Network installed. Don't forget to set up rewrite rules.
*
* @skipglobalargcheck Reusing `--url` on purpose.
* @subcommand multisite-install
*
* @param string[] $args Positional arguments. Unused.
* @param array{url?: string, base: string, subdomains?: bool, title: string, admin_user: string, admin_password?: string, admin_email: string, 'skip-email'?: bool, 'skip-config'?: bool} $assoc_args Associative arguments.
*/
public function multisite_install( $args, $assoc_args ) {
if ( $this->do_install( $assoc_args ) ) {
WP_CLI::log( 'Created single site database tables.' );
} else {
WP_CLI::log( 'Single site database tables already present.' );
}
$assoc_args = self::set_multisite_defaults( $assoc_args );
// translators: placeholder is user supplied title
$assoc_args['title'] = sprintf( _x( '%s Sites', 'Default network name' ), $assoc_args['title'] );
// Overwrite runtime args, to avoid mismatches.
$consts_to_args = [
'SUBDOMAIN_INSTALL' => 'subdomains',
'PATH_CURRENT_SITE' => 'base',
'SITE_ID_CURRENT_SITE' => 'site_id',
'BLOG_ID_CURRENT_SITE' => 'blog_id',
];
foreach ( $consts_to_args as $const => $arg ) {
if ( defined( $const ) ) {
$assoc_args[ $arg ] = constant( $const );
}
}
if ( ! $this->multisite_convert_( $assoc_args ) ) {
return;
}
// Do the steps that were skipped by populate_network(),
// which checks is_multisite().
if ( is_multisite() ) {
$site_user = get_user_by( 'email', $assoc_args['admin_email'] );
self::add_site_admins( $site_user );
$domain = self::get_clean_basedomain();
self::create_initial_blog(
$assoc_args['site_id'],
$assoc_args['blog_id'],
$domain,
$assoc_args['base'],
$assoc_args['subdomains'],
$site_user
);
}
WP_CLI::success( "Network installed. Don't forget to set up rewrite rules (and a .htaccess file, if using Apache)." );
}
private static function set_multisite_defaults( $assoc_args ) {
$defaults = [
'subdomains' => false,
'base' => '/',
'site_id' => 1,
'blog_id' => 1,
];
return array_merge( $defaults, $assoc_args );
}
private function do_install( $assoc_args ) {
/**
* @var \wpdb $wpdb
*/
global $wpdb;
if ( is_blog_installed() ) {
return false;
}
if ( true === Utils\get_flag_value( $assoc_args, 'skip-email' ) ) {
if ( ! function_exists( 'wp_new_blog_notification' ) ) {
// @phpstan-ignore function.inner
function wp_new_blog_notification() {
// Silence is golden
}
}
// WP 4.9.0 - skip "Notice of Admin Email Change" email as well (https://core.trac.wordpress.org/ticket/39117).
add_filter( 'send_site_admin_email_change_email', '__return_false' );
}
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$defaults = [
'title' => '',
'admin_user' => '',
'admin_email' => '',
'admin_password' => '',
];
$defaults['locale'] = '';
$args = wp_parse_args( $assoc_args, $defaults );
// Support prompting for the `--url=<url>`,
// which is normally a runtime argument
if ( isset( $assoc_args['url'] ) ) {
WP_CLI::set_url( $assoc_args['url'] );
}
$public = true;
$password = wp_slash( $args['admin_password'] );
if ( ! is_email( $args['admin_email'] ) ) {
WP_CLI::error( "The '{$args['admin_email']}' email address is invalid." );
}
/**
* @var string $password
*/
$result = wp_install(
$args['title'],
$args['admin_user'],
$args['admin_email'],
$public,
'',
$password,
$args['locale']
);
if ( ! empty( $wpdb->last_error ) ) {
WP_CLI::error( 'Installation produced database errors, and may have partially or completely failed.' );
}
if ( empty( $args['admin_password'] ) ) {
WP_CLI::log( "Admin password: {$result['password']}" );
}
// Confirm the uploads directory exists
$upload_dir = wp_upload_dir();
if ( ! empty( $upload_dir['error'] ) ) {
WP_CLI::warning( $upload_dir['error'] );
}
return true;
}
private function multisite_convert_( $assoc_args ) {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$domain = self::get_clean_basedomain();
if ( 'localhost' === $domain && ! empty( $assoc_args['subdomains'] ) ) {
WP_CLI::error( "Multisite with subdomains cannot be configured when domain is 'localhost'." );
}
// need to register the multisite tables manually for some reason
foreach ( $wpdb->tables( 'ms_global' ) as $table => $prefixed_table ) {
$wpdb->$table = $prefixed_table;
}
install_network();
/**
* @var string $admin_email
*/
$admin_email = get_option( 'admin_email' );
$result = populate_network(
$assoc_args['site_id'],
$domain,
$admin_email,
$assoc_args['title'],
$assoc_args['base'],
$assoc_args['subdomains']
);
$site_id = $wpdb->get_var( "SELECT id FROM $wpdb->site" );
$site_id = ( null === $site_id ) ? 1 : (int) $site_id;
if ( true === $result ) {
WP_CLI::log( 'Set up multisite database tables.' );
} else {
switch ( $result->get_error_code() ) {
case 'siteid_exists':
WP_CLI::log( $result->get_error_message() );
return false;
case 'no_wildcard_dns':
WP_CLI::warning( __( 'Wildcard DNS may not be configured correctly.' ) );
break;
default:
WP_CLI::error( $result );
}
}
// delete_site_option() cleans the alloptions cache to prevent dupe option
delete_site_option( 'upload_space_check_disabled' );
update_site_option( 'upload_space_check_disabled', 1 );
if ( ! is_multisite() ) {
$subdomain_export = Utils\get_flag_value( $assoc_args, 'subdomains' ) ? 'true' : 'false';
$ms_config = <<<EOT
define( 'WP_ALLOW_MULTISITE', true );
define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', {$subdomain_export} );
\$base = '{$assoc_args['base']}';
define( 'DOMAIN_CURRENT_SITE', '{$domain}' );
define( 'PATH_CURRENT_SITE', '{$assoc_args['base']}' );
define( 'SITE_ID_CURRENT_SITE', {$site_id} );
define( 'BLOG_ID_CURRENT_SITE', 1 );
EOT;
$wp_config_path = Utils\locate_wp_config();
if ( true === Utils\get_flag_value( $assoc_args, 'skip-config' ) ) {
WP_CLI::log( "Addition of multisite constants to 'wp-config.php' skipped. You need to add them manually:\n{$ms_config}" );
} elseif ( is_writable( $wp_config_path ) && self::modify_wp_config( $ms_config ) ) {
WP_CLI::log( "Added multisite constants to 'wp-config.php'." );
} else {
WP_CLI::warning( "Multisite constants could not be written to 'wp-config.php'. You may need to add them manually:\n{$ms_config}" );
}
} else {
/* Multisite constants are defined, therefore we already have an empty site_admins site meta.
*
* Code based on parts of delete_network_option. */
$rows = $wpdb->get_results( "SELECT meta_id, site_id FROM {$wpdb->sitemeta} WHERE meta_key = 'site_admins' AND meta_value = ''" );
foreach ( $rows as $row ) {
wp_cache_delete( "{$row->site_id}:site_admins", 'site-options' );
$wpdb->delete(
$wpdb->sitemeta,
[ 'meta_id' => $row->meta_id ]
);
}
}
return true;
}
// copied from populate_network()
private static function create_initial_blog(
$network_id,
$blog_id,
$domain,
$path,
$subdomain_install,
$site_user
) {
global $wpdb, $current_site, $wp_rewrite;
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- This is meant to replace Core functionality.
$current_site = new stdClass();
$current_site->domain = $domain;
$current_site->path = $path;
$current_site->site_name = ucfirst( $domain );
$blog_data = [
'site_id' => $network_id,
'domain' => $domain,
'path' => $path,
'registered' => current_time( 'mysql' ),
];
$wpdb->insert( $wpdb->blogs, $blog_data );
$current_site->blog_id = $wpdb->insert_id;
$blog_id = $wpdb->insert_id;
update_user_meta( $site_user->ID, 'source_domain', $domain );
update_user_meta( $site_user->ID, 'primary_blog', $blog_id );
if ( $subdomain_install ) {
$wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' );
} else {
$wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' );
}
flush_rewrite_rules();
}
// copied from populate_network()
private static function add_site_admins( $site_user ) {
$site_admins = [ $site_user->user_login ];
$users = get_users( [ 'fields' => [ 'ID', 'user_login' ] ] );
if ( $users ) {
foreach ( $users as $user ) {
if ( is_super_admin( $user->ID )
&& ! in_array( $user->user_login, $site_admins, true ) ) {
$site_admins[] = $user->user_login;
}
}
}
update_site_option( 'site_admins', $site_admins );
}
private static function modify_wp_config( $content ) {
$wp_config_path = Utils\locate_wp_config();
$token = "/* That's all, stop editing!";
$config_contents = (string) file_get_contents( $wp_config_path );
if ( false === strpos( $config_contents, $token ) ) {
return false;
}
list( $before, $after ) = explode( $token, $config_contents );
$content = trim( $content );
file_put_contents(
$wp_config_path,
"{$before}\n\n{$content}\n\n{$token}{$after}"
);
return true;
}
private static function get_clean_basedomain() {
/**
* @var string $siteurl
*/
$siteurl = get_option( 'siteurl' );
$domain = (string) preg_replace( '|https?://|', '', $siteurl );
$slash = strpos( $domain, '/' );
if ( false !== $slash ) {
$domain = substr( $domain, 0, $slash );
}
return $domain;
}
/**
* Displays the WordPress version.
*
* ## OPTIONS
*
* [--extra]
* : Show extended version information.
*
* ## EXAMPLES
*
* # Display the WordPress version
* $ wp core version
* 4.5.2
*
* # Display WordPress version along with other information
* $ wp core version --extra
* WordPress version: 4.5.2
* Database revision: 36686
* TinyMCE version: 4.310 (4310-20160418)
* Package language: en_US
*
* @when before_wp_load
*
* @param string[] $args Positional arguments. Unused.
* @param array{extra?: bool} $assoc_args Associative arguments.
*/
public function version( $args = [], $assoc_args = [] ) {
$details = self::get_wp_details();
if ( ! Utils\get_flag_value( $assoc_args, 'extra' ) ) {
WP_CLI::line( $details['wp_version'] );
return;
}
$match = [];
$found_version = preg_match( '/(\d)(\d+)-/', $details['tinymce_version'], $match );
$human_readable_tiny_mce = $found_version ? "{$match[1]}.{$match[2]}" : '';
echo Utils\mustache_render(
self::get_template_path( 'versions.mustache' ),
[
'wp-version' => $details['wp_version'],
'db-version' => $details['wp_db_version'],
'local-package' => empty( $details['wp_local_package'] )
? 'en_US'
: $details['wp_local_package'],
'mce-version' => $human_readable_tiny_mce
? "{$human_readable_tiny_mce} ({$details['tinymce_version']})"
: $details['tinymce_version'],
]
);
}
/**
* Gets version information from `wp-includes/version.php`.
*
* @return array {
* @type string $wp_version The WordPress version.
* @type int $wp_db_version The WordPress DB revision.
* @type string $tinymce_version The TinyMCE version.
* @type string $wp_local_package The TinyMCE version.
* }
*/
private static function get_wp_details( $abspath = ABSPATH ) {
$versions_path = $abspath . 'wp-includes/version.php';
if ( ! is_readable( $versions_path ) ) {
WP_CLI::error(
"This does not seem to be a WordPress installation.\n" .
'Pass --path=`path/to/wordpress` or run `wp core download`.'
);
}
$version_content = (string) file_get_contents( $versions_path, false, null, 6, 2048 );