| 1 |
<?php |
| 2 |
|
| 3 |
class Red_Json_File extends Red_FileIO { |
| 4 |
public function force_download() { |
| 5 |
parent::force_download(); |
| 6 |
|
| 7 |
header( 'Content-Type: application/json' ); |
| 8 |
header( 'Content-Disposition: attachment; filename="' . $this->export_filename( 'json' ) . '"' ); |
| 9 |
} |
| 10 |
|
| 11 |
public function get_data( array $items, array $groups ) { |
| 12 |
$version = red_get_plugin_data( dirname( dirname( __FILE__ ) ) . '/redirection.php' ); |
| 13 |
|
| 14 |
$items = array( |
| 15 |
'plugin' => array( |
| 16 |
'version' => trim( $version['Version'] ), |
| 17 |
'date' => date( 'r' ), |
| 18 |
), |
| 19 |
'groups' => $groups, |
| 20 |
'redirects' => array_map( function( $item ) { |
| 21 |
return $item->to_json(); |
| 22 |
}, $items ), |
| 23 |
); |
| 24 |
|
| 25 |
return wp_json_encode( $items, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) . PHP_EOL; |
| 26 |
} |
| 27 |
|
| 28 |
public function load( $group, $filename, $data ) { |
| 29 |
global $wpdb; |
| 30 |
|
| 31 |
$count = 0; |
| 32 |
$json = @json_decode( $data, true ); |
| 33 |
if ( $json === false ) { |
| 34 |
return 0; |
| 35 |
} |
| 36 |
|
| 37 |
// Import groups |
| 38 |
$groups = array(); |
| 39 |
$group_map = array(); |
| 40 |
|
| 41 |
if ( isset( $json['groups'] ) ) { |
| 42 |
foreach ( $json['groups'] as $group ) { |
| 43 |
$old_group_id = $group['id']; |
| 44 |
unset( $group['id'] ); |
| 45 |
|
| 46 |
$group = Red_Group::create( $group['name'], $group['module_id'], $group['enabled'] ? true : false ); |
| 47 |
if ( $group ) { |
| 48 |
$group_map[ $old_group_id ] = $group->get_id(); |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
unset( $json['groups'] ); |
| 54 |
|
| 55 |
// Import redirects |
| 56 |
if ( isset( $json['redirects'] ) ) { |
| 57 |
foreach ( $json['redirects'] as $pos => $redirect ) { |
| 58 |
unset( $redirect['id'] ); |
| 59 |
|
| 60 |
if ( ! isset( $group_map[ $redirect['group_id'] ] ) ) { |
| 61 |
$new_group = Red_Group::create( 'Group', 1 ); |
| 62 |
$group_map[ $redirect['group_id'] ] = $new_group->get_id(); |
| 63 |
} |
| 64 |
|
| 65 |
if ( $redirect['match_type'] === 'url' && isset( $redirect['action_data'] ) && ! is_array( $redirect['action_data'] ) ) { |
| 66 |
$redirect['action_data'] = array( 'url' => $redirect['action_data'] ); |
| 67 |
} |
| 68 |
|
| 69 |
$redirect['group_id'] = $group_map[ $redirect['group_id'] ]; |
| 70 |
Red_Item::create( $redirect ); |
| 71 |
$count++; |
| 72 |
|
| 73 |
// Helps reduce memory usage |
| 74 |
unset( $json['redirects'][ $pos ] ); |
| 75 |
$wpdb->queries = array(); |
| 76 |
$wpdb->num_queries = 0; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
return $count; |
| 81 |
} |
| 82 |
} |
| 83 |
|