Completed
Push — master ( e7739e...f03d96 )
by Stephanie
03:59
created

FrmStyle::update()   C

Complexity

Conditions 18
Paths 46

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 59
rs 6.3239
cc 18
eloc 34
nc 46
nop 1

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
class FrmStyle {
3
    public $number = false;	// Unique ID number of the current instance.
4
	public $id = 0; // the id of the post
5
6
	/**
7
	 * @param int|string $id The id of the stylsheet or 'default'
8
	 */
9
	public function __construct( $id = 0 ) {
10
        $this->id = $id;
11
    }
12
13
    public function get_new() {
14
		$this->id = 0;
15
16
        $max_slug_value = pow(36, 6);
17
        $min_slug_value = 37; // we want to have at least 2 characters in the slug
18
        $key = base_convert( rand($min_slug_value, $max_slug_value), 10, 36 );
19
20
        $style = array(
21
            'post_type'     => FrmStylesController::$post_type,
22
            'ID'            => '',
23
            'post_title'    => __( 'New Style', 'formidable' ),
24
            'post_name'     => $key,
25
            'post_content'  => $this->get_defaults(),
26
            'menu_order'    => '',
27
            'post_status'   => 'publish',
28
        );
29
30
        return (object) $style;
31
    }
32
33
	public function save( $settings ) {
34
		return FrmAppHelper::save_settings( $settings, 'frm_styles' );
35
    }
36
37
	public function duplicate( $id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
        // duplicating is a pro feature
39
    }
40
41
    public function update( $id = 'default' ) {
42
 		$all_instances = $this->get_all();
43
44
 		if ( empty($id) ) {
45
 		     $new_style = (array) $this->get_new();
46
 		     $all_instances[] = $new_style;
47
 		}
48
49
        $action_ids = array();
50
51
 		foreach ( $all_instances as $number => $new_instance ) {
52
 			$new_instance = stripslashes_deep( (array) $new_instance);
53
 			$this->id = $new_instance['ID'];
54
 			if ( $id != $this->id || ! $_POST || ! isset($_POST['frm_style_setting']) ) {
55
				$all_instances[ $number ] = $new_instance;
56
57
 			    if ( $new_instance['menu_order'] && $_POST && empty($_POST['prev_menu_order']) && isset($_POST['frm_style_setting']['menu_order']) ) {
58
 			        // this style was set to default, so remove default setting on previous default style
59
 			        $new_instance['menu_order'] = 0;
60
 			        $action_ids[] = $this->save($new_instance);
61
 			    }
62
63
 			    // don't continue if not saving this style
64
 			    continue;
65
 			}
66
67
 			$new_instance['post_title'] = sanitize_text_field( $_POST['frm_style_setting']['post_title'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
68
 			$new_instance['post_content'] = $_POST['frm_style_setting']['post_content'];
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
69
 			$new_instance['post_type']  = FrmStylesController::$post_type;
70
            $new_instance['post_status']  = 'publish';
71
			$new_instance['menu_order']  = isset( $_POST['frm_style_setting']['menu_order'] ) ? absint( $_POST['frm_style_setting']['menu_order'] ) : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
72
73
            if ( empty($id) ) {
74
                $new_instance['post_name'] = $new_instance['post_title'];
75
            }
76
77
            $default_settings = $this->get_defaults();
78
79
            foreach ( $default_settings as $setting => $default ) {
80
				if ( strpos( $setting, 'color' ) !== false || in_array( $setting, array( 'error_bg', 'error_border', 'error_text' ) ) ) {
81
                    //if is a color
82
					$new_instance['post_content'][ $setting ] = str_replace( '#', '', $new_instance['post_content'][ $setting ] );
83
				} else if ( in_array( $setting, array( 'submit_style', 'important_style', 'auto_width' ) ) && ! isset( $new_instance['post_content'][ $setting ] ) ) {
84
					$new_instance['post_content'][ $setting ] = 0;
85
                } else if ( $setting == 'font' ) {
86
                	$new_instance['post_content'][ $setting ] = $this->force_balanced_quotation( $new_instance['post_content'][ $setting ] );
87
                }
88
            }
89
90
			$all_instances[ $number ] = $new_instance;
91
92
            $action_ids[] = $this->save($new_instance);
93
94
 		}
95
96
 		$this->save_settings($all_instances);
97
98
 		return $action_ids;
99
 	}
100
101
    /**
102
     * Create static css file
103
     */
104
	public function save_settings( $styles ) {
105
		$filename = FrmAppHelper::plugin_path() . '/css/custom_theme.css.php';
106
		update_option( 'frm_last_style_update', date('njGi') );
107
108
        if ( ! is_file($filename) ) {
109
            return;
110
        }
111
112
        $defaults = $this->get_defaults();
113
        $uploads = wp_upload_dir();
114
		$target_path = $uploads['basedir'] . '/formidable';
115
		$needed_dirs = array( $target_path, $target_path . '/css' );
116
        $dirs_exist = true;
117
118
        $saving = true;
119
		$css = '/* ' . __( 'WARNING: Any changes made to this file will be lost when your Formidable settings are updated', 'formidable' ) . ' */' . "\n";
120
121
        ob_start();
122
        $frm_style = $this;
123
        include($filename);
124
		$css .= preg_replace( '/\/\*(.|\s)*?\*\//', '', str_replace( array( "\r\n", "\r", "\n", "\t", '    ' ), '', ob_get_contents() ) );
125
        ob_end_clean();
126
127
        $access_type = get_filesystem_method();
128
        if ( $access_type === 'direct' ) {
129
			$creds = request_filesystem_credentials( site_url() . '/wp-admin/', '', false, false, array() );
130
		} else {
131
			$creds = $this->get_ftp_creds( $access_type );
132
		}
133
134
		if ( ! empty( $creds ) ) {
135
        	// initialize the API
136
        	if ( ! WP_Filesystem( $creds ) ) {
137
        		// any problems and we exit
138
        		$dirs_exist = false;
139
			}
140
141
            if ( $dirs_exist ) {
142
	        	global $wp_filesystem;
143
144
            	$chmod_dir = defined('FS_CHMOD_DIR') ? FS_CHMOD_DIR : ( fileperms( ABSPATH ) & 0777 | 0755 );
145
            	$chmod_file = defined('FS_CHMOD_FILE') ? FS_CHMOD_FILE : ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 );
146
147
                // Create the directories if need be:
148
            	foreach ( $needed_dirs as $_dir ) {
149
                    // Only check to see if the Dir exists upon creation failure. Less I/O this way.
150
            		if ( ! $wp_filesystem->mkdir( $_dir, $chmod_dir ) && ! $wp_filesystem->is_dir( $_dir ) ) {
151
            			$dirs_exist = false;
152
                    }
153
            	}
154
155
				$index_path = $target_path . '/index.php';
156
                $wp_filesystem->put_contents( $index_path, "<?php\n// Silence is golden.\n?>", $chmod_file );
157
158
                // only write the file if the folders exist
159
                if ( $dirs_exist ) {
160
					$css_file = $target_path . '/css/formidablepro.css';
161
                    $wp_filesystem->put_contents( $css_file, $css, $chmod_file );
162
                }
163
            }
164
        }
165
166
        update_option('frmpro_css', $css);
167
168
        delete_transient('frmpro_css');
169
        set_transient('frmpro_css', $css);
170
	}
171
172
	private function get_ftp_creds( $type ) {
173
		$credentials = get_option( 'ftp_credentials', array( 'hostname' => '', 'username' => '' ) );
174
175
		$credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : $credentials['hostname'];
176
		$credentials['username'] = defined('FTP_USER') ? FTP_USER : $credentials['username'];
177
		$credentials['password'] = defined('FTP_PASS') ? FTP_PASS : '';
178
179
		// Check to see if we are setting the public/private keys for ssh
180
		$credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : '';
181
		$credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : '';
182
183
		// Sanitize the hostname, Some people might pass in odd-data:
184
		$credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); //Strip any schemes off
185
186
		if ( strpos( $credentials['hostname'], ':' ) ) {
187
			list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 );
188
			if ( ! is_numeric( $credentials['port'] ) ) {
189
				unset( $credentials['port'] );
190
			}
191
		} else {
192
			unset( $credentials['port'] );
193
		}
194
195
		if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' == FS_METHOD ) ) {
196
			$credentials['connection_type'] = 'ssh';
197
		} else if ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' == $type ) {
198
			//Only the FTP Extension understands SSL
199
			$credentials['connection_type'] = 'ftps';
200
		} else if ( ! isset( $credentials['connection_type'] ) ) {
201
			//All else fails (And it's not defaulted to something else saved), Default to FTP
202
			$credentials['connection_type'] = 'ftp';
203
		}
204
205
		$has_creds = ( ! empty( $credentials['password'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['hostname'] ) );
206
		$can_ssh = ( 'ssh' == $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] ) );
207
		if ( $has_creds || $can_ssh ) {
208
			$stored_credentials = $credentials;
209
			if ( ! empty( $stored_credentials['port'] ) ) {
210
				//save port as part of hostname to simplify above code.
211
				$stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
212
			}
213
214
			unset( $stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key'] );
215
216
			return $credentials;
217
		}
218
219
		return false;
220
	}
221
222
	public function destroy( $id ) {
223
        return wp_delete_post($id);
224
    }
225
226
    public function get_one() {
227
        if ( 'default' == $this->id ) {
228
            $style = $this->get_default_style();
229
            if ( $style ) {
230
                $this->id = $style->ID;
231
            } else {
232
                $this->id = 0;
233
            }
234
            return $style;
235
        }
236
237
        $style = get_post($this->id);
238
239
        if ( ! $style ) {
240
            return $style;
241
        }
242
243
        $style->post_content = FrmAppHelper::maybe_json_decode($style->post_content);
244
245
        $default_values = $this->get_defaults();
246
247
        // fill default values
248
        $style->post_content = $this->override_defaults($style->post_content);
249
        $style->post_content = wp_parse_args( $style->post_content, $default_values);
250
251
        return $style;
252
    }
253
254
    public function get_all( $orderby = 'title', $order = 'ASC', $limit = 99 ) {
255
        $post_atts = array(
256
			'post_type'   => FrmStylesController::$post_type,
257
			'post_status' => 'publish',
258
			'numberposts' => $limit,
259
			'orderby'     => $orderby,
260
			'order'       => $order,
261
        );
262
263
        $temp_styles = FrmAppHelper::check_cache(serialize($post_atts), 'frm_styles', $post_atts, 'get_posts');
0 ignored issues
show
Documentation introduced by
$post_atts is of type array<string,string|inte...ing","order":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
264
265
        if ( empty($temp_styles) ) {
266
            global $wpdb;
267
            // make sure there wasn't a conflict with the query
268
			$query = $wpdb->prepare( 'SELECT * FROM ' . $wpdb->posts . ' WHERE post_type=%s AND post_status=%s ORDER BY post_title ASC LIMIT 99', FrmStylesController::$post_type, 'publish' );
269
            $temp_styles = FrmAppHelper::check_cache('frm_backup_style_check', 'frm_styles', $query, 'get_results');
270
271
            if ( empty($temp_styles) ) {
272
                // create a new style if there are none
273
         		$new = $this->get_new();
274
         		$new->post_title = $new->post_name = __( 'Formidable Style', 'formidable' );
275
         		$new->menu_order = 1;
276
         		$new = $this->save( (array) $new);
277
         		$this->update('default');
278
279
                $post_atts['include'] = $new;
280
281
                $temp_styles = get_posts( $post_atts );
282
            }
283
        }
284
285
        $default_values = $this->get_defaults();
286
        $default_style = false;
287
288
        $styles = array();
289
        foreach ( $temp_styles as $style ) {
290
            $this->id = $style->ID;
291
            if ( $style->menu_order ) {
292
                if ( $default_style ) {
293
                    // only return one default
294
                    $style->menu_order = 0;
295
                } else {
296
                    // check for a default style
297
                    $default_style = $style->ID;
298
                }
299
            }
300
301
            $style->post_content = FrmAppHelper::maybe_json_decode($style->post_content);
302
303
            // fill default values
304
            $style->post_content = $this->override_defaults($style->post_content);
305
            $style->post_content = wp_parse_args( $style->post_content, $default_values);
306
307
			$styles[ $style->ID ] = $style;
308
        }
309
310
        if ( ! $default_style ) {
311
            $default_style = reset($styles);
312
			$styles[ $default_style->ID ]->menu_order = 1;
313
        }
314
315
        return $styles;
316
    }
317
318
	public function get_default_style( $styles = null ) {
319
        if ( ! isset($styles) ) {
320
			$styles = $this->get_all( 'menu_order', 'DESC', 1 );
321
        }
322
323
        foreach ( $styles as $style ) {
324
            if ( $style->menu_order ) {
325
                return $style;
326
            }
327
        }
328
    }
329
330
	public function override_defaults( $settings ) {
331
	    if ( ! is_array($settings) ) {
332
	        return $settings;
333
	    }
334
335
	    $settings['line_height'] = ( ! isset($settings['field_height']) || $settings['field_height'] == '' || $settings['field_height'] == 'auto') ? 'normal' : $settings['field_height'];
336
337
	    if ( ! isset($settings['form_desc_size']) && isset($settings['description_font_size']) ) {
338
	        $settings['form_desc_size'] = $settings['description_font_size'];
339
	        $settings['form_desc_color'] = $settings['description_color'];
340
	        $settings['title_color'] = $settings['label_color'];
341
	    }
342
343
	    if ( ! isset($settings['section_color']) && isset($settings['label_color']) ) {
344
	        $settings['section_color'] = $settings['label_color'];
345
	        $settings['section_border_color'] = $settings['border_color'];
346
	    }
347
348
	    if ( ! isset($settings['submit_hover_bg_color']) && isset($settings['submit_bg_color']) ) {
349
	        $settings['submit_hover_bg_color'] = $settings['submit_bg_color'];
350
	        $settings['submit_hover_color'] = $settings['submit_text_color'];
351
	        $settings['submit_hover_border_color'] = $settings['submit_border_color'];
352
353
	        $settings['submit_active_bg_color'] = $settings['submit_bg_color'];
354
	        $settings['submit_active_color'] = $settings['submit_text_color'];
355
            $settings['submit_active_border_color'] = $settings['submit_border_color'];
356
	    }
357
358
	    return $settings;
359
	}
360
361
	public function get_defaults() {
362
        return array(
363
            'theme_css'         => 'ui-lightness',
364
            'theme_name'        => 'UI Lightness',
365
366
			'center_form'		=> '',
367
            'form_width'        => '100%',
368
            'form_align'        => 'left',
369
            'direction'         => is_rtl() ? 'rtl' : 'ltr',
370
            'fieldset'          => '0px',
371
            'fieldset_color'    => '000000',
372
            'fieldset_padding'  => '0 0 15px 0',
373
            'fieldset_bg_color' => '',
374
375
            'title_size'        => '20px',
376
            'title_color'       => '444444',
377
			'title_margin_top'  => '10px',
378
			'title_margin_bottom' => '10px',
379
            'form_desc_size'    => '14px',
380
            'form_desc_color'   => '666666',
381
			'form_desc_margin_top' => '10px',
382
			'form_desc_margin_bottom' => '25px',
383
384
            'font'              => '"Lucida Grande","Lucida Sans Unicode",Tahoma,sans-serif',
385
            'font_size'         => '14px',
386
            'label_color'       => '444444',
387
            'weight'            => 'bold',
388
            'position'          => 'none',
389
            'align'             => 'left',
390
            'width'             => '150px',
391
            'required_color'    => 'B94A48',
392
            'required_weight'   => 'bold',
393
            'label_padding'     => '0 0 3px 0',
394
395
            'description_font_size' => '12px',
396
            'description_color' => '666666',
397
            'description_weight' => 'normal',
398
            'description_style' => 'normal',
399
            'description_align' => 'left',
400
401
            'field_font_size'   => '14px',
402
            'field_height' 		=> '32px',
403
            'line_height'		=> 'normal',
404
            'field_width'       => '100%',
405
            'auto_width'        => false,
406
            'field_pad'         => '6px 10px',
407
            'field_margin'      => '20px',
408
			'field_weight' => 'normal',
409
            'text_color'        => '555555',
410
            //'border_color_hv'   => 'cccccc',
411
            'border_color'      => 'cccccc',
412
            'field_border_width' => '1px',
413
            'field_border_style' => 'solid',
414
415
            'bg_color'          => 'ffffff',
416
            //'bg_color_hv'       => 'ffffff',
417
			'remove_box_shadow' => '',
418
            'bg_color_active'   => 'ffffff',
419
			'border_color_active' => '66afe9',
420
			'remove_box_shadow_active' => '',
421
            'text_color_error'  => '444444',
422
            'bg_color_error'    => 'ffffff',
423
			'border_color_error' => 'B94A48',
424
			'border_width_error' => '1px',
425
			'border_style_error' => 'solid',
426
            'bg_color_disabled' => 'ffffff',
427
            'border_color_disabled' => 'E5E5E5',
428
            'text_color_disabled' => 'A1A1A1',
429
430
            'radio_align'       => 'block',
431
            'check_align'       => 'block',
432
            'check_font_size'   => '13px',
433
            'check_label_color' => '444444',
434
            'check_weight'      => 'normal',
435
436
            'section_font_size' => '18px',
437
            'section_color'     => '444444',
438
            'section_weight'    => 'bold',
439
            'section_pad'       => '15px 0 3px 0',
440
            'section_mar_top'   => '15px',
441
			'section_mar_bottom' => '12px',
442
            'section_bg_color'  => '',
443
            'section_border_color' => 'e8e8e8',
444
            'section_border_width' => '2px',
445
            'section_border_style' => 'solid',
446
            'section_border_loc' => '-top',
447
            'collapse_icon'     => '6',
448
            'collapse_pos'      => 'after',
449
            'repeat_icon'       => '1',
450
451
            'submit_style'      => false,
452
            'submit_font_size'  => '14px',
453
            'submit_width'      => 'auto',
454
            'submit_height'     => 'auto',
455
            'submit_bg_color'   => 'ffffff',
456
            'submit_border_color' => 'cccccc',
457
            'submit_border_width' => '1px',
458
            'submit_text_color' => '444444',
459
            'submit_weight'     => 'normal',
460
            'submit_border_radius' => '4px',
461
            'submit_bg_img'     => '',
462
            'submit_margin'     => '10px',
463
            'submit_padding'    => '6px 11px',
464
            'submit_shadow_color' => 'eeeeee',
465
            'submit_hover_bg_color' => 'efefef',
466
            'submit_hover_color' => '444444',
467
            'submit_hover_border_color' => 'cccccc',
468
            'submit_active_bg_color' => 'efefef',
469
            'submit_active_color' => '444444',
470
            'submit_active_border_color' => 'cccccc',
471
472
            'border_radius'     => '4px',
473
            'error_bg'          => 'F2DEDE',
474
            'error_border'      => 'EBCCD1',
475
            'error_text'        => 'B94A48',
476
            'error_font_size'   => '14px',
477
478
            'success_bg_color'  => 'DFF0D8',
479
            'success_border_color' => 'D6E9C6',
480
            'success_text_color' => '468847',
481
            'success_font_size' => '14px',
482
483
            'important_style'   => false,
484
485
            'custom_css'        => '',
486
        );
487
    }
488
489
	public function get_field_name( $field_name, $post_field = 'post_content' ) {
490
		return 'frm_style_setting' . ( empty( $post_field ) ? '' : '[' . $post_field . ']' ) . '[' . $field_name . ']';
491
	}
492
493
	public static function get_bold_options() {
494
		return array(
495
			100 => 100, 200 => 200, 300 => 300,
496
			'normal' => __( 'normal', 'formidable' ),
497
			500 => 500, 600 => 600,
498
			'bold' => __( 'bold', 'formidable' ),
499
			800 => 800, 900 => 900,
500
		);
501
	}
502
503
504
	/**
505
	 * Don't let imbalanced font families ruin the whole stylesheet
506
	 */
507
	public function force_balanced_quotation( $value ) {
508
		$balanced_characters = array( '"', "'" );
509
		foreach ( $balanced_characters as $char ) {
510
			$char_count = substr_count( $value, $char );
511
			$is_balanced = $char_count % 2 == 0;
512
			if ( ! $is_balanced ) {
513
				$value .= $char;
514
			}
515
		}
516
		return $value;
517
	}
518
}
519