-
Notifications
You must be signed in to change notification settings - Fork 11
/
wp-site-cloner.php
603 lines (507 loc) · 15.3 KB
/
wp-site-cloner.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
<?php
/**
* Plugin Name: WP Site Cloner
* Plugin URI: https://wordpress.org/plugins/wp-site-cloner/
* Author: John James Jacoby
* Author URI: https://profiles.wordpress.org/johnjamesjacoby/
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Description: Create sites with content from other sites
* Version: 0.1.0
* Text Domain: wp-site-cloner
* Domain Path: /assets/lang/
*/
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/**
* Clone a site
*
* @since 0.1.0
*
* @param array $args
*
* @return \WP_Site_Cloner
*/
function wp_clone_site( $args = array() ) {
$cloner = new WP_Site_Cloner( $args );
return $cloner->clone_site();
}
/**
* The main site cloner class
*
* @since 0.1.0
*/
final class WP_Site_Cloner {
/**
* @var int Source site ID
*/
private $from_site_id = 0;
/**
* @var int Destination site ID
*/
private $to_site_id = 0;
/**
* @var int Source site ID
*/
private $from_site_prefix = '';
/**
* @var int Destination site ID
*/
private $to_site_prefix = '';
/**
* @var array Arguments for the new site
*/
private $arguments = array();
/**
* @var string URL of the new site, based on arguments
*/
private $home_url = '';
/**
* Start to clone the site
*
* @since 0.1.0
*
* @param array $args
* @return int
*/
public function __construct( $args = array() ) {
$this->arguments = wp_parse_args( $args, array(
'domain' => '',
'path' => '/',
'title' => '',
'meta' => array( 'public' => 1 ),
'from_site_id' => 0,
'to_network_id' => get_current_site()->id,
'user_id' => get_current_user_id(),
'callback' => 'wpmu_create_blog',
'cleanup' => ''
) );
}
/**
* Main function of the plugin : duplicates a site
*
* @since 0.1.0
*
* @param array $args parameters from form
*/
public function clone_site() {
// Bail if no source siteID
if ( empty( $this->arguments['from_site_id'] ) ) {
return;
}
// Setup sites
$this->from_site_id = (int) $this->arguments[ 'from_site_id' ];
// Bail if from site does not exist
if ( ! get_blog_details( $this->from_site_id ) ) {
return;
}
// Attempt to create a site
$this->to_site_id = (int) $this->create_site();
// Bail if no site was created
if ( empty( $this->to_site_id ) ) {
return false;
}
// Setup the new URL
$this->home_url = esc_url_raw( implode( '/', array(
rtrim( $this->arguments['domain'], '/' ),
ltrim( rtrim( $this->arguments['path'], '/' ), '/' )
) ) );
// Primary blog
$this->maybe_set_primary_blog();
// Temporarily bump known limitations
@ini_set( 'memory_limit', '1024M' );
@ini_set( 'max_execution_time', '0' );
// Copy site and all of it's data
$this->db_copy_tables();
$this->db_set_options();
$this->db_update_data();
// Maybe run a clean-up routine
$this->cleanup_site();
// Return the new site ID
return (int) $this->to_site_id;
}
/**
* Attempt to create a new site
*
* This method checks if your callback function exists. If it does, it calls
* it; if not, it calls do_action() with the name of your callback.
*
* Your custom callback function should be based on wpmu_create_blog(), and
* take care to mimic it's quirky requirements.
*
* @since 0.1.0
*
* @return int
*/
private function create_site() {
global $wpdb;
// Default site ID
$site_id = false;
// Always hide DB errors
$wpdb->hide_errors();
// Try to create
if ( function_exists( $this->arguments['callback'] ) ) {
$site_id = call_user_func(
$this->arguments['callback'],
$this->arguments['domain'],
$this->arguments['path'],
$this->arguments['title'],
$this->arguments['user_id'],
$this->arguments['meta'],
$this->arguments['to_network_id']
);
} else {
$site_id = apply_filters( $this->arguments['callback'], $this->arguments );
}
// Restore error visibility
$wpdb->show_errors();
// Return site ID or false
return ! is_wp_error( $site_id )
? (int) $site_id
: false;
}
/**
* Attempt to clean up a new site
*
* This method checks if your clean-up callback function exists. If it does,
* it calls it; if not, it calls do_action() with the name of your callback.
*
* @since 0.1.0
*
* @return int
*/
private function cleanup_site() {
// Bail if no clean-up function passed
if ( empty( $this->arguments['cleanup'] ) ) {
return;
}
// Switch to the new site
switch_to_blog( $this->to_site_id );
// Try to clean-up
if ( function_exists( $this->arguments['cleanup'] ) ) {
call_user_func( $this->arguments['cleanup'] );
} else {
do_action( $this->arguments['cleanup'] );
}
// Switch back
restore_current_blog();
}
/**
* User rights adjustment for maybe setting the primary blog for this user
*
* @since 0.1.0
*/
private function maybe_set_primary_blog() {
if ( ! is_super_admin( $this->arguments['user_id'] ) && ! get_user_meta( 'primary_blog', $this->arguments['user_id'], true ) ) {
update_user_meta( $this->arguments['user_id'], 'primary_blog', $this->to_site_id );
}
}
/**
* Copy tables from a site to another
*
* @since 0.1.0
*/
private function db_copy_tables() {
global $wpdb;
// Destination Site information
$this->to_site_prefix = $wpdb->get_blog_prefix( $this->to_site_id );
$this->from_site_prefix = $wpdb->get_blog_prefix( $this->from_site_id );
// Setup from site query info
$from_site_prefix_length = strlen( $this->from_site_prefix );
$from_site_prefix_like = $wpdb->esc_like( $this->from_site_prefix );
// Get sources Tables
if ( $this->from_site_id === (int) get_current_site()->blog_id ) {
$from_site_tables = $this->get_primary_tables( $this->from_site_prefix );
} else {
$sql_query = $wpdb->prepare( 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE \'%s\'', $from_site_prefix_like . '%' );
$from_site_tables = $this->do_sql_query( $sql_query, 'col' );
}
// Loop through tables, and cleanup/create/populate
foreach ( $from_site_tables as $table ) {
$table_name = $this->to_site_prefix . substr( $table, $from_site_prefix_length );
// Drop table if exists
$this->do_sql_query( 'DROP TABLE IF EXISTS `' . $table_name . '`' );
// Create new table from source table
$this->do_sql_query( 'CREATE TABLE IF NOT EXISTS `' . $table_name . '` LIKE `' . $table . '`' );
// Populate database with data from source table
$this->do_sql_query( 'INSERT `' . $table_name . '` SELECT * FROM `' . $table . '`' );
}
}
/**
* Options that should be preserved in the new blog.
*
* @since 0.1.0
*/
private function db_set_options() {
// Update options according to new location
$new_site_options = array(
'siteurl' => $this->home_url,
'home' => $this->home_url,
'blogname' => $this->arguments['title'],
'admin_email' => get_userdata( $this->arguments['user_id'] )->user_email,
);
// Apply key options from new blog.
switch_to_blog( $this->to_site_id );
foreach ( $new_site_options as $option_name => $option_value ) {
update_option( $option_name, $option_value );
}
restore_current_blog();
}
/**
* Get tables to copy if duplicated site is primary site
*
* @since 0.1.0
*
* @return array of strings : the tables
*/
private function get_primary_tables() {
// Tables to copy
$default_tables = array_keys( $this->get_default_tables() );
foreach ( $default_tables as $k => $default_table ) {
$default_tables[ $k ] = $this->from_site_prefix . $default_table;
}
return $default_tables;
}
/**
* Return array of tables & values to search & replace
*
* Note that this will need to be updated if tables are added or removed, or
* if custom tables are desired.
*
* @since 0.1.0
*
* @return array
*/
private function get_default_tables() {
return array(
'terms' => array(),
'termmeta' => array(),
'term_taxonomy' => array(),
'term_relationships' => array(),
'commentmeta' => array(),
'comments' => array(),
'postmeta' => array( 'meta_value' ),
'posts' => array( 'post_content', 'guid' ),
'links' => array( 'link_url', 'link_image' ),
'options' => array( 'option_name', 'option_value' ),
);
}
/**
* Updated tables from a site to another
*
* @since 0.1.0
*/
public function db_update_data() {
global $wpdb;
// Looking for uploads dirs
switch_to_blog( $this->from_site_id );
$dir = wp_upload_dir();
$from_upload_url = str_replace( network_site_url(), get_bloginfo( 'url' ) . '/', $dir[ 'baseurl' ] );
$from_blog_url = get_blog_option( $this->from_site_id, 'siteurl' );
switch_to_blog( $this->to_site_id );
$dir = wp_upload_dir();
$to_upload_url = str_replace( network_site_url(), get_bloginfo( 'url' ) . '/', $dir[ 'baseurl' ] );
$to_blog_url = get_blog_option( $this->to_site_id, 'siteurl' );
// Switch back to "from" site
restore_current_blog();
// Setup empty tables array
$tables = array();
// Bugfix : escape '_' , '%' and '/' character for mysql 'like' queries
$to_site_prefix_like = $wpdb->esc_like( $this->to_site_prefix );
$results = $this->do_sql_query( 'SHOW TABLES LIKE \'' . $to_site_prefix_like . '%\'', 'col', false );
foreach ( $results as $k => $v ) {
$tables[ str_replace( $this->to_site_prefix, '', $v ) ] = array();
}
foreach ( array_keys( $tables ) as $table ) {
$results = $this->do_sql_query( 'SHOW COLUMNS FROM `' . $this->to_site_prefix . $table . '`', 'col', false );
$columns = array();
foreach ( $results as $k => $v ) {
$columns[] = $v;
}
$tables[ $table ] = $columns;
}
// Maybe don't copy _links
$default_tables = $this->get_default_tables();
if ( ! get_blog_option( $this->from_site_id, 'link_manager_enabled', 0 ) ) {
unset( $default_tables['links'] );
}
// Setup tables & fields to loop through
foreach ( $default_tables as $table => $fields ) {
$tables[ $table ] = $fields;
}
// Setup array of old & new strings to replace
$string_to_replace = array(
$from_upload_url => $to_upload_url,
$from_blog_url => $to_blog_url,
$this->from_site_prefix => $this->to_site_prefix
);
// Try to update data in fields
foreach ( $tables as $table => $fields ) {
foreach ( $string_to_replace as $from_string => $to_string ) {
$this->update( $this->to_site_prefix . $table, $fields, $from_string, $to_string );
}
}
// Restore back to original source site
restore_current_blog();
// Clear cache
refresh_blog_details( $this->to_site_id );
}
/**
* Updates a table
*
* @since 0.1.0
*
* @param string $table to update
* @param array $fields of string $fields to update
* @param string $from_string original string to replace
* @param string $to_string new string
*/
public function update( $table, $fields, $from_string, $to_string ) {
global $wpdb;
// Bail if fields isn't an array
if ( empty( $fields ) || ! is_array( $fields ) ) {
return;
}
// Loop through fields
foreach ( $fields as $field ) {
// Bugfix : escape '_' , '%' and '/' character for mysql 'like' queries
$from_string_like = $wpdb->esc_like( $from_string );
$sql_query = $wpdb->prepare( 'SELECT `' . $field . '` FROM `' . $table . '` WHERE `' . $field . '` LIKE "%s" ', '%' . $from_string_like . '%' );
$results = $this->do_sql_query( $sql_query, 'results', false );
// Skip if no results
if ( empty( $results ) ) {
continue;
}
// Build the update query
$update = 'UPDATE `' . $table . '` SET `' . $field . '` = "%s" WHERE `' . $field . '` = "%s"';
// Loop through results & replace any URL & site ID related values
foreach ( $results as $row ) {
$old_value = $row[ $field ];
$new_value = $this->try_replace( $row, $field, $from_string, $to_string );
$sql_query = $wpdb->prepare( $update, $new_value, $old_value );
$results = $this->do_sql_query( $sql_query );
}
}
}
/**
* Replace $from_string with $to_string in $val. If $to_string already
* in $val, no replacement is made
*
* @since 0.1.0
*
* @param string $val
* @param string $from_string
* @param string $to_string
* @return string the new string
*/
public function replace( $val, $from_string, $to_string ) {
$new = $val;
if ( is_string( $val ) ) {
$pos = strpos( $val, $to_string );
if ( $pos === false ) {
$new = str_replace( $from_string, $to_string, $val );
}
}
return $new;
}
/**
* Replace recursively $from_string with $to_string in $val
*
* @since 0.1.0
*
* @param mixed (string|array) $val
* @param string $from_string
* @param string $to_string
*
* @return string the new string
*/
public function replace_recursive( $val, $from_string, $to_string ) {
$unset = array();
if ( is_array( $val ) ) {
foreach ( array_keys( $val ) as $k ) {
$val[ $k ] = $this->try_replace( $val, $k, $from_string, $to_string );
}
} else {
$val = $this->replace( $val, $from_string, $to_string );
}
foreach ( $unset as $k ) {
unset( $val[ $k ] );
}
return $val;
}
/**
* Try to replace $from_string with $to_string in a row
*
* @since 0.1.0
*
* @param array $row the row
* @param array $field the field
* @param string $from_string
* @param string $to_string
*
* @return the data, maybe replaced
*/
public function try_replace( $row, $field, $from_string, $to_string ) {
if ( is_serialized( $row[ $field ] ) ) {
$double_serialize = false;
$row[ $field ] = @unserialize( $row[ $field ] );
// FOR SERIALISED OPTIONS, like in wp_carousel plugin
if ( is_serialized( $row[ $field ] ) ) {
$row[ $field ] = @unserialize( $row[ $field ] );
$double_serialize = true;
}
if ( is_array( $row[ $field ] ) ) {
$row[ $field ] = $this->replace_recursive( $row[ $field ], $from_string, $to_string );
} else if ( is_object( $row[ $field ] ) || $row[ $field ] instanceof __PHP_Incomplete_Class ) {
$array_object = ( array ) $row[ $field ];
$array_object = $this->replace_recursive( $array_object, $from_string, $to_string );
foreach ( $array_object as $key => $field ) {
$row[ $field ]->$key = $field;
}
} else {
$row[ $field ] = $this->replace( $row[ $field ], $from_string, $to_string );
}
$row[ $field ] = serialize( $row[ $field ] );
// Pour des options comme wp_carousel...
if ( $double_serialize ) {
$row[ $field ] = serialize( $row[ $field ] );
}
} else {
$row[ $field ] = $this->replace( $row[ $field ], $from_string, $to_string );
}
return $row[ $field ];
}
/**
* Runs a WPDB query
*
* @since 0.1.0
*
* @param string $sql_query the query
* @param string $type type of result
*
* @return $results of the query
*/
public function do_sql_query( $sql_query, $type = '' ) {
global $wpdb;
$wpdb->hide_errors();
switch ( $type ) {
case 'col':
$results = $wpdb->get_col( $sql_query );
break;
case 'row':
$results = $wpdb->get_row( $sql_query );
break;
case 'var':
$results = $wpdb->get_var( $sql_query );
break;
case 'results':
$results = $wpdb->get_results( $sql_query, ARRAY_A );
break;
default:
$results = $wpdb->query( $sql_query );
break;
}
$wpdb->show_errors();
return $results;
}
}