-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathredirection-cli.php
More file actions
532 lines (465 loc) · 14.2 KB
/
Copy pathredirection-cli.php
File metadata and controls
532 lines (465 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
<?php
use Redirection\Database\Database;
use Redirection\Database\Status;
/**
* Implements example command.
*/
class Redirection_Cli extends WP_CLI_Command {
/**
* @param array<string, mixed> $extra CLI flags.
* @return 'import'|'ignore'|'update'
*/
private function get_duplicate_mode( array $extra ) {
$mode = isset( $extra['duplicate-mode'] ) && is_string( $extra['duplicate-mode'] ) ? $extra['duplicate-mode'] : 'import';
if ( in_array( $mode, [ 'import', 'ignore', 'update' ], true ) ) {
return $mode;
}
WP_CLI::error( 'Invalid duplicate mode - import, ignore, or update supported' );
return 'import';
}
/**
* @param array<string, mixed> $extra CLI flags.
* @param string $flag Flag name.
* @return bool
*/
private function get_boolean_flag( array $extra, $flag ) {
if ( ! isset( $extra[ $flag ] ) ) {
return false;
}
$value = $extra[ $flag ];
if ( $value === true || $value === false ) {
return $value;
}
if ( is_string( $value ) ) {
return in_array( strtolower( $value ), [ '1', 'true', 'yes' ], true );
}
if ( is_int( $value ) ) {
return $value === 1;
}
return false;
}
/**
* @param string $source Import source.
* @param string $type Import type.
* @param array{
* created: int,
* updated: int,
* ignored: int,
* groups_created: int,
* preview: array<int, array{
* source: string,
* target: string,
* code: int,
* regex: bool,
* group: string,
* result: 'created'|'updated'|'ignored',
* redirect_id?: int
* }>
* } $results Import results.
* @return void
*/
private function display_import_results( $source, $type, array $results ) {
WP_CLI::success(
sprintf(
'Imported %d redirects from %s %s (%d created, %d updated, %d ignored, %d groups created)',
$results['created'] + $results['updated'],
$type,
$source,
$results['created'],
$results['updated'],
$results['ignored'],
$results['groups_created']
)
);
}
/**
* Resolve a group ID, or return the first available group.
*
* @param int $group_id Group ID, or 0 to auto-select the first group.
* @return int|false Group ID or false when not available.
*/
private function get_group( $group_id ) {
if ( $group_id === 0 ) {
$groups = Red_Group::get_filtered( array() );
if ( count( $groups['items'] ) > 0 ) {
return $groups['items'][0]['id'];
}
} else {
$groups = Red_Group::get( $group_id );
if ( $groups !== false ) {
return $group_id;
}
}
return false;
}
/**
* Import from another plugin to Redirection.
*
* ## OPTIONS
*
* <name>
* : The plugin name to import from. Supported importers include wp-simple-redirect, seo-redirection, safe-redirect-manager, wordpress-old-slugs, rank-math, quick-redirects, pretty-links, seopress, slim-seo, eps-301-redirects, and fake-redirection.
*
* [--group=<groupid>]
* : The group ID to import into. Defaults to the first available group.
*
* [--duplicate-mode=<mode>]
* : Duplicate handling. One of import, ignore, or update. Defaults to import.
*
* [--delete-source]
* : Delete the original source data after import for importers that support it.
*
* ## EXAMPLES
*
* wp redirection plugin quick-redirects
*
* @param list<string> $args Positional arguments.
* @param array<string, mixed> $extra Associative flags.
* @return void
*/
public function plugin( $args, $extra ) {
$name = $args[0];
$group = $this->get_group( isset( $extra['group'] ) ? intval( $extra['group'], 10 ) : 0 );
$options = [
'duplicate_mode' => $this->get_duplicate_mode( $extra ),
'delete_source' => $this->get_boolean_flag( $extra, 'delete-source' ),
];
$importer = \Redirection\ImportExport\Importer\PluginRegistry::get_importer( $name );
if ( $importer !== false && $group !== false ) {
$results = $importer->import_plugin( $group, $options );
$this->display_import_results( $name, 'plugin', $results );
return;
}
if ( $importer === false ) {
WP_CLI::error( 'Invalid plugin name' );
return;
}
WP_CLI::error( 'Invalid group' );
}
/**
* Get or set a Redirection setting
*
* ## OPTIONS
*
* <name>
* : The setting name to get or set
*
* [--set=<value>]
* : The value to set. Use true/false for boolean settings, or JSON for complex values.
*
* [--verbose]
* : Display setting name along with value (e.g., "flag_case: true" instead of just "true")
*
* ## EXAMPLES
*
* wp redirection setting flag_case
* wp redirection setting flag_case --verbose
* wp redirection setting flag_case --set=true
* wp redirection setting cache_key --set=false
* wp redirection setting aliases --set='["example.com"]'
*
* @param list<string> $args Positional arguments.
* @param array<string, mixed> $extra Associative flags.
* @return void
*/
public function setting( $args, $extra ) {
$name = $args[0];
$set = isset( $extra['set'] ) ? $extra['set'] : null;
$verbose = isset( $extra['verbose'] );
$options = Red_Options::get();
if ( ! array_key_exists( $name, $options ) ) {
WP_CLI::error( 'Unsupported setting: ' . $name );
return;
}
$old_value = $options[ $name ];
if ( $set !== null ) {
if ( ! is_string( $set ) ) {
WP_CLI::error( 'No value provided for --set; please provide a value, for example: --set=true or --set=\'["example.com"]\'.' );
return;
}
$decoded = $this->parse_setting_value( $set );
$update = [];
$update[ $name ] = $decoded;
$options = Red_Options::save( $update );
$new_value = array_key_exists( $name, $options ) ? $options[ $name ] : null;
$this->display_setting_result( $name, $old_value, $new_value );
return;
}
// Just display the current value
$this->display_setting_value( $name, $old_value, $verbose );
}
/**
* Parse a setting value from CLI input.
*
* @param string $value The raw CLI value.
* @return mixed The parsed value.
*/
private function parse_setting_value( $value ) {
// Handle explicit boolean strings
if ( $value === 'true' ) {
return true;
}
if ( $value === 'false' ) {
return false;
}
// Try JSON decode for arrays/objects (but not null, which should be literal string "null")
$decoded = json_decode( $value, true );
if ( $decoded !== null ) {
return $decoded;
}
// Return as-is (string value, including literal "null")
return $value;
}
/**
* Display a setting value.
*
* @param string $name Setting name.
* @param mixed $value Setting value.
* @param bool $verbose Whether to include setting name in output.
* @return void
*/
private function display_setting_value( $name, $value, $verbose = false ) {
$display = $this->format_value_for_display( $value );
if ( $verbose ) {
WP_CLI::success( sprintf( '%s: %s', $name, $display ) );
} else {
WP_CLI::success( $display );
}
}
/**
* Display the result of setting a value.
*
* @param string $name Setting name.
* @param mixed $old_value Previous value.
* @param mixed $new_value New value.
* @return void
*/
private function display_setting_result( $name, $old_value, $new_value ) {
$old_display = $this->format_value_for_display( $old_value );
$new_display = $this->format_value_for_display( $new_value );
// Compare raw values to avoid issues with formatted display strings
if ( $old_value === $new_value ) {
WP_CLI::success( sprintf( '%s is already set to: %s', $name, $new_display ) );
} else {
WP_CLI::success( sprintf( '%s updated: %s → %s', $name, $old_display, $new_display ) );
}
}
/**
* Format a value for display in CLI output.
*
* @param mixed $value The value to format.
* @return string Formatted string for display.
*/
private function format_value_for_display( $value ) {
if ( is_bool( $value ) ) {
return $value ? 'true' : 'false';
}
if ( is_array( $value ) ) {
$encoded = wp_json_encode( $value );
return is_string( $encoded ) ? $encoded : '[]';
}
if ( $value === '' ) {
return '(empty)';
}
return (string) $value;
}
/**
* Import redirections from a JSON, CSV, or .htaccess file
*
* ## OPTIONS
*
* <file>
* : The name of the file to import.
*
* [--group=<groupid>]
* : The group ID to import into. Defaults to the first available group. JSON
* contains it's own group
*
* [--use-groups-in-file]
* : For JSON imports, use the groups defined in the file instead of importing into a single group.
*
* [--format=<importformat>]
* : The import format - csv, apache, or json. Defaults to json
*
* [--duplicate-mode=<mode>]
* : Duplicate handling. One of import, ignore, or update. Defaults to import.
*
* ## EXAMPLES
*
* wp redirection import .htaccess --format=apache
*
* @param list<string> $args Positional arguments.
* @param array<string, mixed> $extra Associative flags.
* @return void
*/
public function import( $args, $extra ) {
$format = isset( $extra['format'] ) ? $extra['format'] : 'json';
$formats = new \Redirection\ImportExport\FormatFactory();
$use_file_groups = $this->get_boolean_flag( $extra, 'use-groups-in-file' );
$group = $use_file_groups && $format === 'json' ? 0 : $this->get_group( isset( $extra['group'] ) ? intval( $extra['group'], 10 ) : 0 );
if ( $group === false ) {
WP_CLI::error( 'Invalid group' );
return;
}
$importer = $formats->create( $format );
if ( $importer === false ) {
WP_CLI::error( 'Invalid import format - csv, json, or apache supported' );
return;
}
if ( ! file_exists( $args[0] ) || ! is_readable( $args[0] ) ) {
WP_CLI::error( 'Invalid import file' );
return;
}
$file_size = filesize( $args[0] );
if ( $file_size === false ) {
WP_CLI::error( 'Invalid import file' );
return;
}
$results = ( new \Redirection\ImportExport\ImportService( $formats ) )->import(
$group,
[
'name' => basename( $args[0] ),
'tmp_name' => $args[0],
'type' => '',
'error' => 0,
'size' => $file_size,
],
[
'format' => $format,
'duplicate_mode' => $this->get_duplicate_mode( $extra ),
]
);
$this->display_import_results( $format, 'file', $results );
}
/**
* Export redirections to a CSV, JSON, .htaccess, or rewrite.rules file
*
* ## OPTIONS
*
* <module>
* : The module to export - wordpress, apache, nginx, or all
*
* <filename>
* : The file to export to, or - for stdout
*
* [--format=<exportformat>]
* : The export format. One of json, csv, apache, or nginx. Defaults to json
*
* ## EXAMPLES
*
* wp redirection export wordpress --format=apache
*
* @param list<string> $args Positional arguments.
* @param array<string, mixed> $extra Associative flags.
* @return void
*/
public function export( $args, $extra ) {
$format = isset( $extra['format'] ) ? $extra['format'] : 'json';
$exporter = ( new \Redirection\ImportExport\FormatFactory() )->create( $format );
if ( $exporter === false ) {
WP_CLI::error( 'Invalid export format - json, csv, apache, or nginx supported' );
return;
}
$file = fopen( $args[1] === '-' ? 'php://stdout' : $args[1], 'w' );
if ( $file !== false ) {
$export = ( new \Redirection\ImportExport\ExportService() )->export( $args[0], $format );
if ( $export === false ) {
// phpcs:ignore
WP_CLI::error( 'Invalid module - must be wordpress, apache, nginx, or all' );
return;
}
fwrite( $file, $export['data'] );
fclose( $file );
WP_CLI::success( 'Exported ' . $export['total'] . ' to ' . $format );
} else {
WP_CLI::error( 'Invalid output file' );
}
}
/**
* Perform Redirection database actions
*
* ## OPTIONS
*
* <action>
* : The database action to perform: install, remove, upgrade
*
* [--skip-errors]
* : Skip errors and keep on upgrading
*
* ## EXAMPLES
*
* wp redirection database install
*
* @param list<string> $args Positional arguments.
* @param array<string, mixed> $extra Associative flags.
* @return void
*/
public function database( $args, $extra ) {
$skip = isset( $extra['skip-errors'] ) ? true : false;
if ( count( $args ) === 0 || ! in_array( $args[0], array( 'install', 'remove', 'upgrade' ), true ) ) {
WP_CLI::error( 'Invalid database action - please use install, remove, or upgrade' );
return;
}
if ( $args[0] === 'install' ) {
Database::apply_to_sites(
function () {
$latest = Database::get_latest_database();
$latest->install();
WP_CLI::success( 'Site ' . get_current_blog_id() . ' database is installed' );
}
);
WP_CLI::success( 'Database install finished' );
} elseif ( $args[0] === 'upgrade' ) {
global $wpdb;
$wpdb->show_errors( false );
Database::apply_to_sites(
function () use ( $skip ) {
$database = new Database();
$status = new Status();
if ( ! $status->needs_updating() ) {
WP_CLI::success( 'Site ' . get_current_blog_id() . ' database is already the latest version' );
return;
}
$loop = 0;
while ( $loop < 50 ) {
$database->apply_upgrade( $status );
$info = $status->get_json();
if ( ! $info['inProgress'] ) {
break;
}
if ( isset( $info['result'] ) && $info['result'] === 'error' && isset( $info['reason'] ) && isset( $info['debug'] ) ) {
if ( $skip === false ) {
WP_CLI::error( 'Site ' . get_current_blog_id() . ' database failed to upgrade: ' . $info['reason'] . ' - ' . $info['debug'][0] );
return;
}
WP_CLI::warning( 'Site ' . get_current_blog_id() . ' database failed to upgrade: ' . $info['reason'] . ' - ' . $info['debug'][0] );
$status->set_next_stage();
}
$loop++;
}
WP_CLI::success( 'Site ' . get_current_blog_id() . ' database upgraded' );
}
);
WP_CLI::success( 'Database upgrade finished' );
} elseif ( $args[0] === 'remove' ) {
Database::apply_to_sites(
function () {
$latest = Database::get_latest_database();
$latest->remove();
}
);
WP_CLI::success( 'Database removed' );
}
}
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
// Register "redirection" as top-level command, and all public methods as sub-commands
WP_CLI::add_command( 'redirection', 'Redirection_Cli' );
add_action(
Red_Flusher::DELETE_HOOK,
function () {
$flusher = new Red_Flusher();
$flusher->flush();
}
);
}