Completed
Push — fix/image-migration-backups ( 008bea )
by
unknown
14:34
created

image-widget.php ➔ jetpack_migrate_image_widget()   F

Complexity

Conditions 27
Paths 533

Size

Total Lines 192
Code Lines 115

Duplication

Lines 24
Ratio 12.5 %

Importance

Changes 0
Metric Value
cc 27
eloc 115
nc 533
nop 0
dl 24
loc 192
rs 2.678
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' ) ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
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
			$attachment_ids = get_posts( array(
158
				'fields'      => 'ids',
159
				'meta_query'  => array(
160
					array(
161
						'value'   => basename( $image_basename ),
162
						'compare' => 'LIKE',
163
						'key'     => '_wp_attachment_metadata',
164
					),
165
				),
166
				'post_status' => 'inherit',
167
				'post_type'   => 'attachment',
168
			) );
169
		}
170
171
		foreach ( (array) $attachment_ids as $attachment_id ) {
0 ignored issues
show
Bug introduced by
The variable $attachment_ids does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
172
			$image_meta = wp_get_attachment_metadata( $attachment_id );
173
174
			// Is it a full size image?
175
			$image_path_pieces = explode( '/', $image_meta['file'] );
176 View Code Duplication
			if ( $image_basename === array_pop( $image_path_pieces ) ) {
177
				$media_image[ $id ]['attachment_id'] = $attachment_id;
178
179
				// Set correct size if dimensions fit.
180
				if (
181
					$media_image[ $id ]['width']  == $image_meta['width'] ||
182
					$media_image[ $id ]['height'] == $image_meta['height']
183
				) {
184
					$media_image[ $id ]['size'] = 'full';
185
				}
186
				break;
187
			}
188
189
			// Is it a down-sized image?
190
			foreach ( $image_meta['sizes'] as $size => $image ) {
191 View Code Duplication
				if ( false !== array_search( $image_basename, $image ) ) {
192
					$media_image[ $id ]['attachment_id'] = $attachment_id;
193
194
					// Set correct size if dimensions fit.
195
					if (
196
						$media_image[ $id ]['width']  == $image['width'] ||
197
						$media_image[ $id ]['height'] == $image['height']
198
					) {
199
						$media_image[ $id ]['size'] = $size;
200
					}
201
					break 2;
202
				}
203
			}
204
		}
205
206
		if ( ! empty( $widget['link'] ) ) {
207
			$media_image[ $id ]['link_type'] = $widget['link'] === $widget['img_url'] ? 'file' : 'custom';
208
		}
209
210
		foreach ( $sidebars_widgets as $sidebar => $widgets ) {
211
			if (
212
				is_array( $widgets )
213
				&& false !== ( $key = array_search( "image-{$id}", $widgets, true ) )
214
			) {
215
				$sidebars_widgets[ $sidebar ][ $key ] = "media_image-{$id}";
216
			}
217
		}
218
219
		$widgets_to_unregister[] = $id;
220
	}
221
222
	if ( update_option( 'widget_media_image', $media_image ) ) {
223
		delete_option( 'widget_image' );
224
225
		// Now un-register old widgets and register new.
226
		foreach ( $widgets_to_unregister as $id ) {
227
			wp_unregister_sidebar_widget( "image-${id}" );
228
229
			// register new widget.
230
			$media_image_widget = new WP_Widget_Media_Image();
231
			$media_image_widget->_set( $id );
232
			$media_image_widget->_register_one( $id );
233
		}
234
235
		wp_set_sidebars_widgets( $sidebars_widgets );
236
237
		Jetpack_Options::update_option( 'image_widget_migration', true );
238
239
		// We need to refresh on widgets page for changes to take effect.
240
		add_action( 'current_screen', 'jetpack_refresh_on_widget_page' );
241
	}
242
}
243
add_action( 'widgets_init', 'jetpack_migrate_image_widget' );
244
245
function jetpack_refresh_on_widget_page( $current ) {
246
	if ( 'widgets' === $current->base ) {
247
		wp_safe_redirect( admin_url( 'widgets.php' ) );
248
	}
249
}
250