Completed
Push — master ( 1466b8...74a3d9 )
by Stephanie
14s
created

FrmXMLController::install_template()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 39
rs 9.296
c 0
b 0
f 0
1
<?php
2
3
class FrmXMLController {
4
5
	public static function menu() {
6
		add_submenu_page( 'formidable', 'Formidable | ' . __( 'Import/Export', 'formidable' ), __( 'Import/Export', 'formidable' ), 'frm_edit_forms', 'formidable-import', 'FrmXMLController::route' );
7
	}
8
9
	public static function add_default_templates() {
10
		if ( ! function_exists( 'libxml_disable_entity_loader' ) ) {
11
			// XML import is not enabled on your server
12
			return;
13
		}
14
15
		$set_err = libxml_use_internal_errors( true );
16
		$loader = libxml_disable_entity_loader( true );
17
18
		$files = apply_filters( 'frm_default_templates_files', array( FrmAppHelper::plugin_path() . '/classes/views/xml/default-templates.xml' ) );
19
20
		foreach ( (array) $files as $file ) {
21
			FrmXMLHelper::import_xml( $file );
22
			unset( $file );
23
		}
24
		/*
25
		if(is_wp_error($result))
26
			$errors[] = $result->get_error_message();
27
		else if($result)
28
			$message = $result;
29
		*/
30
31
		unset( $files );
32
33
		libxml_use_internal_errors( $set_err );
34
		libxml_disable_entity_loader( $loader );
35
	}
36
37
38
	/**
39
	 * Use the template link to install the XML template
40
	 *
41
	 * @since 3.06
42
	 */
43
	public static function install_template() {
44
		FrmAppHelper::permission_check( 'frm_create_forms' );
45
		check_ajax_referer( 'frm_ajax', 'nonce' );
46
47
		$url = FrmAppHelper::get_param( 'xml', '', 'post', 'esc_url_raw' );
48
49
		$response = wp_remote_get( $url );
50
		$body     = wp_remote_retrieve_body( $response );
51
		$xml      = simplexml_load_string( $body );
52
53
		if ( ! $xml ) {
54
			$response = array(
55
				'message' => __( 'There was an error reading the form template', 'formidable' ),
56
			);
57
			echo wp_json_encode( $response );
58
			wp_die();
59
		}
60
61
		self::set_new_form_name( $xml );
62
63
		$imported = FrmXMLHelper::import_xml_now( $xml );
64
		if ( isset( $imported['form_status'] ) && ! empty( $imported['form_status'] ) ) {
65
			// get the last form id in case there are child forms
66
			end( $imported['form_status'] );
67
			$form_id = key( $imported['form_status'] );
68
			$response = array(
69
				'id'       => $form_id,
70
				'redirect' => admin_url( 'admin.php?page=formidable&frm_action=edit&id=' . absint( $form_id ) ),
71
				'success'  => 1,
72
			);
73
		} else {
74
			$response = array(
75
				'message' => __( 'There was an error importing form', 'formidable' ),
76
			);
77
		}
78
79
		echo wp_json_encode( $response );
80
		wp_die();
81
	}
82
83
	private static function set_new_form_name( &$xml ) {
84
		if ( isset( $xml->form ) ) {
85
			$form_name   = FrmAppHelper::get_param( 'name', '', 'post', 'sanitize_text_field' );
86
			$description = FrmAppHelper::get_param( 'desc', '', 'post', 'sanitize_textarea_field' );
87
			$name_set = false;
88
89
			foreach ( $xml->form as $k => $form ) {
90
				// Use a unique key to prevent editing existing form
91
				$form->form_key = FrmAppHelper::get_unique_key( $form->form_key, 'frm_forms', 'form_key' );
92
93
				if ( ! $name_set && ( ! isset( $form->parent_form_id ) || empty( $form->parent_form_id ) ) ) {
94
					$form->name = $form_name;
95
					$form->description = $description;
96
					$name_set = true;
97
				}
98
				$xml->form[ $k ] = $form;
99
			}
100
		}
101
	}
102
103
	public static function route() {
104
		$action = isset( $_REQUEST['frm_action'] ) ? 'frm_action' : 'action';
105
		$action = FrmAppHelper::get_param( $action, '', 'get', 'sanitize_title' );
106
		if ( 'import_xml' === $action ) {
107
			return self::import_xml();
108
		} elseif ( 'export_xml' === $action ) {
109
			return self::export_xml();
110
		} elseif ( apply_filters( 'frm_xml_route', true, $action ) ) {
111
			return self::form();
112
		}
113
	}
114
115
	public static function form( $errors = array(), $message = '' ) {
116
		$where = array(
117
			'status' => array( null, '', 'published' ),
118
		);
119
		$forms = FrmForm::getAll( $where, 'name' );
120
121
		$export_types = array(
122
			'forms' => __( 'Forms', 'formidable' ),
123
			'items' => __( 'Entries', 'formidable' ),
124
		);
125
		$export_types = apply_filters( 'frm_xml_export_types', $export_types );
126
127
		$export_format = array(
128
			'xml' => array(
129
				'name'    => 'XML',
130
				'support' => 'forms',
131
				'count'   => 'multiple',
132
			),
133
			'csv' => array(
134
				'name'    => 'CSV',
135
				'support' => 'items',
136
				'count'   => 'single',
137
			),
138
		);
139
		$export_format = apply_filters( 'frm_export_formats', $export_format );
140
141
		include( FrmAppHelper::plugin_path() . '/classes/views/xml/import_form.php' );
142
	}
143
144
	public static function import_xml() {
145
		$errors = array();
146
		$message = '';
147
148
		$permission_error = FrmAppHelper::permission_nonce_error( 'frm_edit_forms', 'import-xml', 'import-xml-nonce' );
149
		if ( false !== $permission_error ) {
150
			$errors[] = $permission_error;
151
			self::form( $errors );
152
			return;
153
		}
154
155
		if ( ! isset( $_FILES ) || ! isset( $_FILES['frm_import_file'] ) || empty( $_FILES['frm_import_file']['name'] ) || (int) $_FILES['frm_import_file']['size'] < 1 ) {
156
			$errors[] = __( 'Oops, you didn\'t select a file.', 'formidable' );
157
			self::form( $errors );
158
			return;
159
		}
160
161
		$file = $_FILES['frm_import_file']['tmp_name'];
162
163
		if ( ! is_uploaded_file( $file ) ) {
164
			unset( $file );
165
			$errors[] = __( 'The file does not exist, please try again.', 'formidable' );
166
			self::form( $errors );
167
			return;
168
		}
169
170
		//add_filter('upload_mimes', 'FrmXMLController::allow_mime');
171
172
		$export_format = array(
173
			'xml' => array(
174
				'name'    => 'XML',
175
				'support' => 'forms',
176
				'count'   => 'multiple',
177
			),
178
		);
179
		$export_format = apply_filters( 'frm_export_formats', $export_format );
180
181
		$file_type = strtolower( pathinfo( $_FILES['frm_import_file']['name'], PATHINFO_EXTENSION ) );
182
		if ( 'xml' !== $file_type && isset( $export_format[ $file_type ] ) ) {
183
			// allow other file types to be imported
184
			do_action( 'frm_before_import_' . $file_type );
185
			return;
186
		}
187
		unset( $file_type );
188
189
		if ( ! function_exists( 'libxml_disable_entity_loader' ) ) {
190
			$errors[] = __( 'XML import is not enabled on your server with the libxml_disable_entity_loader function.', 'formidable' );
191
			self::form( $errors );
192
			return;
193
		}
194
195
		$set_err = libxml_use_internal_errors( true );
196
		$loader = libxml_disable_entity_loader( true );
197
198
		$result = FrmXMLHelper::import_xml( $file );
199
		FrmXMLHelper::parse_message( $result, $message, $errors );
200
201
		unset( $file );
202
203
		libxml_use_internal_errors( $set_err );
204
		libxml_disable_entity_loader( $loader );
205
206
		self::form( $errors, $message );
207
	}
208
209
	public static function export_xml() {
210
		$error = FrmAppHelper::permission_nonce_error( 'frm_edit_forms', 'export-xml', 'export-xml-nonce' );
211
		if ( ! empty( $error ) ) {
212
			wp_die( esc_html( $error ) );
213
		}
214
215
		$ids = FrmAppHelper::get_post_param( 'frm_export_forms', array() );
216
		$type = FrmAppHelper::get_post_param( 'type', array() );
217
		$format = FrmAppHelper::get_post_param( 'format', 'xml', 'sanitize_title' );
218
219
		if ( ! headers_sent() && ! $type ) {
220
			wp_redirect( esc_url_raw( admin_url( 'admin.php?page=formidable-import' ) ) );
221
			die();
222
		}
223
224
		if ( 'xml' === $format ) {
225
			self::generate_xml( $type, compact( 'ids' ) );
226
		} elseif ( 'csv' === $format ) {
227
			self::generate_csv( compact( 'ids' ) );
228
		} else {
229
			do_action( 'frm_export_format_' . $format, compact( 'ids' ) );
230
		}
231
232
		wp_die();
233
	}
234
235
	public static function generate_xml( $type, $args = array() ) {
236
		global $wpdb;
237
238
		self::prepare_types_array( $type );
239
240
		$tables = array(
241
			'items'     => $wpdb->prefix . 'frm_items',
242
			'forms'     => $wpdb->prefix . 'frm_forms',
243
			'posts'     => $wpdb->posts,
244
			'styles'    => $wpdb->posts,
245
			'actions'   => $wpdb->posts,
246
		);
247
248
		$defaults = array(
249
			'ids' => false,
250
		);
251
		$args = wp_parse_args( $args, $defaults );
252
253
		// Make sure ids are numeric.
254
		if ( is_array( $args['ids'] ) && ! empty( $args['ids'] ) ) {
255
			$args['ids'] = array_filter( $args['ids'], 'is_numeric' );
256
		}
257
258
		$records = array();
259
260
		foreach ( $type as $tb_type ) {
261
			$where = array();
262
			$join = '';
263
			$table = $tables[ $tb_type ];
264
265
			$select = $table . '.id';
266
			$query_vars = array();
267
268
			switch ( $tb_type ) {
269
				case 'forms':
270
					//add forms
271
					if ( $args['ids'] ) {
272
						$where[] = array(
273
							'or'           => 1,
274
							$table . '.id' => $args['ids'],
275
							$table . '.parent_form_id' => $args['ids'],
276
						);
277
					} else {
278
						$where[ $table . '.status !' ] = 'draft';
279
					}
280
					break;
281
				case 'actions':
282
					$select = $table . '.ID';
283
					$where['post_type'] = FrmFormActionsController::$action_post_type;
284
					if ( ! empty( $args['ids'] ) ) {
285
						$where['menu_order'] = $args['ids'];
286
					}
287
					break;
288
				case 'items':
289
					//$join = "INNER JOIN {$wpdb->prefix}frm_item_metas im ON ($table.id = im.item_id)";
290
					if ( $args['ids'] ) {
291
						$where[ $table . '.form_id' ] = $args['ids'];
292
					}
293
					break;
294
				case 'styles':
295
					// Loop through all exported forms and get their selected style IDs
296
					$frm_style = new FrmStyle();
297
					$default_style = $frm_style->get_default_style();
298
					$form_ids = $args['ids'];
299
					$style_ids = array();
300
					foreach ( $form_ids as $form_id ) {
301
						$form_data = FrmForm::getOne( $form_id );
302
						// For forms that have not been updated while running 2.0, check if custom_style is set
303
						if ( isset( $form_data->options['custom_style'] ) ) {
304
							if ( 1 === absint( $form_data->options['custom_style'] ) ) {
305
								$style_ids[] = $default_style->ID;
306
							} else {
307
								$style_ids[] = $form_data->options['custom_style'];
308
							}
309
						}
310
						unset( $form_id, $form_data );
311
					}
312
					$select = $table . '.ID';
313
					$where['post_type'] = 'frm_styles';
314
315
					// Only export selected styles
316
					if ( ! empty( $style_ids ) ) {
317
						$where['ID'] = $style_ids;
318
					}
319
					break;
320
				default:
321
					$select = $table . '.ID';
322
					$join = ' INNER JOIN ' . $wpdb->postmeta . ' pm ON (pm.post_id=' . $table . '.ID)';
323
					$where['pm.meta_key'] = 'frm_form_id';
324
325
					if ( empty( $args['ids'] ) ) {
326
						$where['pm.meta_value >'] = 1;
327
					} else {
328
						$where['pm.meta_value'] = $args['ids'];
329
					}
330
			}
331
332
			$records[ $tb_type ] = FrmDb::get_col( $table . $join, $where, $select );
333
			unset( $tb_type );
334
		}
335
336
		$filename = self::get_file_name( $args, $type, $records );
337
338
		header( 'Content-Description: File Transfer' );
339
		header( 'Content-Disposition: attachment; filename=' . $filename );
340
		header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
341
342
		echo '<?xml version="1.0" encoding="' . esc_attr( get_bloginfo( 'charset' ) ) . "\" ?>\n";
343
		include( FrmAppHelper::plugin_path() . '/classes/views/xml/xml.php' );
344
	}
345
346
	private static function prepare_types_array( &$type ) {
347
		$type = (array) $type;
348
		if ( ! in_array( 'forms', $type ) && ( in_array( 'items', $type ) || in_array( 'posts', $type ) ) ) {
349
			// make sure the form is included if there are entries
350
			$type[] = 'forms';
351
		}
352
353
		if ( in_array( 'forms', $type ) ) {
354
			// include actions with forms
355
			$type[] = 'actions';
356
		}
357
	}
358
359
	/**
360
	 * Use a generic file name if multiple items are exported.
361
	 * Use the nme of the form if only one form is exported.
362
	 *
363
	 * @since 3.05.01
364
	 *
365
	 * @return string
366
	 */
367
	private static function get_file_name( $args, $type, $records ) {
368
		$has_one_form = isset( $records['forms'] ) && ! empty( $records['forms'] ) && count( $args['ids'] ) === 1;
369
		if ( $has_one_form ) {
370
			// one form is being exported
371
			$selected_form_id = reset( $args['ids'] );
372
			foreach ( $records['forms'] as $form_id ) {
373
				$filename = 'form-' . $form_id . '.xml';
374
				if ( $selected_form_id === $form_id ) {
375
					$form = FrmForm::getOne( $form_id );
376
					$filename = sanitize_title( $form->name ) . '-form.xml';
377
					break;
378
				}
379
			}
380
		} else {
381
			$sitename = sanitize_key( get_bloginfo( 'name' ) );
382
383
			if ( ! empty( $sitename ) ) {
384
				$sitename .= '.';
385
			}
386
			$filename = $sitename . 'formidable.' . date( 'Y-m-d' ) . '.xml';
387
		}
388
		return $filename;
0 ignored issues
show
Bug introduced by
The variable $filename 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...
389
	}
390
391
	public static function generate_csv( $atts ) {
392
		$form_ids = $atts['ids'];
393
		if ( empty( $form_ids ) ) {
394
			wp_die( esc_html__( 'Please select a form', 'formidable' ) );
395
		}
396
		self::csv( reset( $form_ids ) );
397
	}
398
399
	/**
400
	 * Export to CSV
401
	 *
402
	 * @since 2.0.19
403
	 */
404
	public static function csv( $form_id = false, $search = '', $fid = '' ) {
405
		FrmAppHelper::permission_check( 'frm_view_entries' );
406
407
		if ( ! $form_id ) {
408
			$form_id = FrmAppHelper::get_param( 'form', '', 'get', 'sanitize_text_field' );
409
			$search = FrmAppHelper::get_param( ( isset( $_REQUEST['s'] ) ? 's' : 'search' ), '', 'get', 'sanitize_text_field' );
410
			$fid = FrmAppHelper::get_param( 'fid', '', 'get', 'sanitize_text_field' );
411
		}
412
413
		set_time_limit( 0 ); //Remove time limit to execute this function
414
		$mem_limit = str_replace( 'M', '', ini_get( 'memory_limit' ) );
415
		if ( (int) $mem_limit < 256 ) {
416
			ini_set( 'memory_limit', '256M' );
417
		}
418
419
		global $wpdb;
420
421
		$form = FrmForm::getOne( $form_id );
422
		$form_id = $form->id;
423
424
		$form_cols = self::get_fields_for_csv_export( $form_id, $form );
425
426
		$item_id = FrmAppHelper::get_param( 'item_id', 0, 'get', 'sanitize_text_field' );
427
		if ( ! empty( $item_id ) ) {
428
			$item_id = explode( ',', $item_id );
429
		}
430
431
		$query = array(
432
			'form_id' => $form_id,
433
		);
434
435
		if ( $item_id ) {
436
			$query['id'] = $item_id;
437
		}
438
439
		/**
440
		 * Allows the query to be changed for fetching the entry ids to include in the export
441
		 *
442
		 * $query is the array of options to be filtered. It includes form_id, and maybe id (array of entry ids),
443
		 * and the search query. This should return an array, but it can be handled as a string as well.
444
		 */
445
		$query = apply_filters( 'frm_csv_where', $query, compact( 'form_id', 'search', 'fid', 'item_id' ) );
446
447
		$entry_ids = FrmDb::get_col( $wpdb->prefix . 'frm_items it', $query );
448
		unset( $query );
449
450
		if ( empty( $entry_ids ) ) {
451
			esc_html_e( 'There are no entries for that form.', 'formidable' );
452
		} else {
453
			FrmCSVExportHelper::generate_csv( compact( 'form', 'entry_ids', 'form_cols' ) );
454
		}
455
456
		wp_die();
457
	}
458
459
	/**
460
	* Get the fields that should be included in the CSV export
461
	*
462
	* @since 2.0.19
463
	*
464
	* @param int $form_id
465
	* @param object $form
466
	* @return array $csv_fields
467
	*/
468
	private static function get_fields_for_csv_export( $form_id, $form ) {
469
		$csv_fields = FrmField::get_all_for_form( $form_id, '', 'include', 'include' );
470
		$no_export_fields = FrmField::no_save_fields();
471
		foreach ( $csv_fields as $k => $f ) {
472
			if ( in_array( $f->type, $no_export_fields ) ) {
473
				unset( $csv_fields[ $k ] );
474
			}
475
		}
476
477
		return $csv_fields;
478
	}
479
480
	public static function allow_mime( $mimes ) {
481
		if ( ! isset( $mimes['csv'] ) ) {
482
			// allow csv files
483
			$mimes['csv'] = 'text/csv';
484
		}
485
486
		if ( ! isset( $mimes['xml'] ) ) {
487
			// allow xml
488
			$mimes['xml'] = 'text/xml';
489
		}
490
491
		return $mimes;
492
	}
493
}
494