Completed
Push — master ( 362e5f...944326 )
by Stephanie
03:30
created

FrmXMLController::route()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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