Completed
Push — fix/image-migration-backups ( 45023b...0759e3 )
by
unknown
10:43
created

image-widget.php ➔ jetpack_migrate_image_widget()   D

Complexity

Conditions 27
Paths 145

Size

Total Lines 194
Code Lines 117

Duplication

Lines 24
Ratio 12.37 %

Importance

Changes 0
Metric Value
cc 27
eloc 117
nc 145
nop 0
dl 24
loc 194
rs 4.2714
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Migration from Jetpack's Image Widget to WordPress' Core Image Widget.
4
 *
5
 * @since 4.9
6
 *
7
 * @package Jetpack
8
 */
9
10
/**
11
 * Stores legacy image widget data in the database.
12
 */
13
function jetpack_store_legacy_image_widget_options( $option_name, $option_value ){
14
	$post = get_page_by_title( $option_name, 'OBJECT', 'jetpack_migration' );
15
16
	if ( null !== $post ) {
17
		return wp_insert_post( array(
18
			'ID' => $post->ID,
19
			'post_title' => $option_name,
20
			'post_content_filtered' => $option_value,
21
			'post_type' => 'jetpack_migration',
22
			'post_date' => date( 'Y-m-d H:i:s', time() ),
23
		), true );
24
	} else {
25
		return wp_insert_post( array(
26
			'post_title' => $option_name,
27
			'post_content_filtered' => $option_value,
28
			'post_type' => 'jetpack_migration',
29
			'post_date' => date( 'Y-m-d H:i:s', time() ),
30
		), true );
31
	}
32
}
33
34
/**
35
 * Retrieves legacy image widget data.
36
 */
37
function jetpack_get_legacy_image_widget_option( $option_name ) {
38
39
	$post = get_page_by_title( $option_name, 'OBJECT', 'jetpack_migration' );
40
41
	if ( null !== $post ) {
42
		return maybe_unserialize( $post->post_content_filtered );
43
	} else {
44
		return null;
45
	}
46
}
47
48
/**
49
 * Migrates all active instances of Jetpack's image widget to Core's media image widget.
50
 */
51
function jetpack_migrate_image_widget() {
52
	// Only trigger the migration from wp-admin
53
	if ( ! is_admin() ) {
54
		return;
55
	}
56
57
	// Only migrate if the new widget is available and we haven't yet migrated
58
	if ( ! class_exists( 'WP_Widget_Media_Image' ) || Jetpack_Options::get_option( 'image_widget_migration' ) ) {
59
		return;
60
	}
61
62
	$default_data = array(
63
		'attachment_id' => 0,
64
		'url' => '',
65
		'title' => '',
66
		'size' => 'custom',
67
		'width' => 0,
68
		'height' => 0,
69
		'align' => 'none',
70
		'caption' => '',
71
		'alt' => '',
72
		'link_type' => '',
73
		'link_url' => '',
74
		'image_classes' => '',
75
		'link_classes' => '',
76
		'link_rel' => '',
77
		'image_title' => '',
78
		'link_target_blank' => false,
79
		'conditions' => null,
80
	);
81
82
	$old_widgets = get_option( 'widget_image', array() );
83
	$media_image = get_option( 'widget_media_image' );
84
	$sidebars_widgets = wp_get_sidebars_widgets();
85
86
	// Persist old and current widgets in backup table.
87
	jetpack_store_legacy_image_widget_options( 'widget_image', serialize( $old_widgets ) );
88
	if ( jetpack_get_legacy_image_widget_option( 'widget_image' ) !== $old_widgets ) {
89
		return false;
90
	}
91
92
	jetpack_store_legacy_image_widget_options( 'sidebars_widgets', serialize( $sidebars_widgets ) );
93
	if ( jetpack_get_legacy_image_widget_option( 'sidebars_widgets' ) !== $sidebars_widgets ) {
94
		return false;
95
	}
96
97
	// Array to store legacy widget ids in to unregister on success.
98
	$widgets_to_unregister = array();
99
100
	foreach ( $old_widgets as $id => $widget ) {
101
		if ( is_string( $id ) ) {
102
			continue;
103
		}
104
105
		// Can be caused by instanciating but not populating a widget in the Customizer.
106
		if ( empty( $widget ) ) {
107
			continue;
108
		}
109
110
		// Ensure widget has no keys other than those expected.
111
		// Not all widgets have conditions, so lets add it in.
112
		$widget_copy = array_merge( array( 'conditions' => null ), $widget );
113
		$non_whitelisted_keys = array_diff_key( $widget_copy, array(
114
			'title' => '',
115
			'img_url' => '',
116
			'alt_text' => '',
117
			'img_title' => '',
118
			'caption' => '',
119
			'align' => '',
120
			'img_width' => '',
121
			'img_height' => '',
122
			'link' => '',
123
			'link_target_blank' => '',
124
			'conditions' => '',
125
		) );
126
127
		if ( count( $non_whitelisted_keys ) > 0 ) {
128
			// skipping the widget in question
129
			continue;
130
		}
131
132
		$media_image[ $id ] = array_merge( $default_data, $widget, array(
133
			'alt'         => $widget['alt_text'],
134
			'height'      => $widget['img_height'],
135
			'image_classes' => ! empty( $widget['align'] ) ? 'align' . $widget['align'] : '',
136
			'image_title' => $widget['img_title'],
137
			'link_url'    => $widget['link'],
138
			'url'         => $widget['img_url'],
139
			'width'       => $widget['img_width'],
140
		) );
141
142
		// Unsetting old widget fields
143
		$media_image[ $id ] = array_diff_key( $media_image[ $id ], array(
144
			'align' => false,
145
			'alt_text' => false,
146
			'img_height' => false,
147
			'img_title' => false,
148
			'img_url' => false,
149
			'img_width' => false,
150
			'link' => false,
151
		) );
152
153
		// Check if the image is in the media library.
154
		$image_basename = basename( $widget['img_url'] );
155
156
		if ( empty( $image_basename ) ) {
157
			continue;
158
		}
159
160
		$attachment_ids = get_posts( array(
161
			'fields'      => 'ids',
162
			'meta_query'  => array(
163
				array(
164
					'value'   => basename( $image_basename ),
165
					'compare' => 'LIKE',
166
					'key'     => '_wp_attachment_metadata',
167
				),
168
			),
169
			'post_status' => 'inherit',
170
			'post_type'   => 'attachment',
171
		) );
172
173
		foreach ( (array) $attachment_ids as $attachment_id ) {
174
			$image_meta = wp_get_attachment_metadata( $attachment_id );
175
176
			// Is it a full size image?
177
			$image_path_pieces = explode( '/', $image_meta['file'] );
178 View Code Duplication
			if ( $image_basename === array_pop( $image_path_pieces ) ) {
179
				$media_image[ $id ]['attachment_id'] = $attachment_id;
180
181
				// Set correct size if dimensions fit.
182
				if (
183
					$media_image[ $id ]['width']  == $image_meta['width'] ||
184
					$media_image[ $id ]['height'] == $image_meta['height']
185
				) {
186
					$media_image[ $id ]['size'] = 'full';
187
				}
188
				break;
189
			}
190
191
			// Is it a down-sized image?
192
			foreach ( $image_meta['sizes'] as $size => $image ) {
193 View Code Duplication
				if ( false !== array_search( $image_basename, $image ) ) {
194
					$media_image[ $id ]['attachment_id'] = $attachment_id;
195
196
					// Set correct size if dimensions fit.
197
					if (
198
						$media_image[ $id ]['width']  == $image['width'] ||
199
						$media_image[ $id ]['height'] == $image['height']
200
					) {
201
						$media_image[ $id ]['size'] = $size;
202
					}
203
					break 2;
204
				}
205
			}
206
		}
207
208
		if ( ! empty( $widget['link'] ) ) {
209
			$media_image[ $id ]['link_type'] = $widget['link'] === $widget['img_url'] ? 'file' : 'custom';
210
		}
211
212
		foreach ( $sidebars_widgets as $sidebar => $widgets ) {
213
			if (
214
				is_array( $widgets )
215
				&& false !== ( $key = array_search( "image-{$id}", $widgets, true ) )
216
			) {
217
				$sidebars_widgets[ $sidebar ][ $key ] = "media_image-{$id}";
218
			}
219
		}
220
221
		$widgets_to_unregister[] = $id;
222
	}
223
224
	if ( update_option( 'widget_media_image', $media_image ) ) {
225
		delete_option( 'widget_image' );
226
227
		// Now un-register old widgets and register new.
228
		foreach ( $widgets_to_unregister as $id ) {
229
			wp_unregister_sidebar_widget( "image-${id}" );
230
231
			// register new widget.
232
			$media_image_widget = new WP_Widget_Media_Image();
233
			$media_image_widget->_set( $id );
234
			$media_image_widget->_register_one( $id );
235
		}
236
237
		wp_set_sidebars_widgets( $sidebars_widgets );
238
239
		Jetpack_Options::update_option( 'image_widget_migration', true );
240
241
		// We need to refresh on widgets page for changes to take effect.
242
		add_action( 'current_screen', 'jetpack_refresh_on_widget_page' );
243
	}
244
}
245
add_action( 'widgets_init', 'jetpack_migrate_image_widget' );
246
247
function jetpack_refresh_on_widget_page( $current ) {
248
	if ( 'widgets' === $current->base ) {
249
		wp_safe_redirect( admin_url( 'widgets.php' ) );
250
	}
251
}
252