Completed
Push — master ( b689ee...25c6e1 )
by Stephanie
03:29
created

FrmCSVExportHelper::has_parent_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
class FrmCSVExportHelper {
4
5
	protected static $separator        = ', ';
6
	protected static $column_separator = ',';
7
	protected static $line_break       = 'return';
8
	protected static $charset          = 'UTF-8';
9
	protected static $to_encoding      = 'UTF-8';
10
	protected static $wp_date_format   = 'Y-m-d H:i:s';
11
	protected static $comment_count    = 0;
12
	protected static $form_id          = 0;
13
	protected static $headings         = array();
14
	protected static $fields           = array();
15
	protected static $entry;
16
	protected static $has_parent_id;
17
18
	public static function csv_format_options() {
19
		$formats = array( 'UTF-8', 'ISO-8859-1', 'windows-1256', 'windows-1251', 'macintosh' );
20
		$formats = apply_filters( 'frm_csv_format_options', $formats );
21
		return $formats;
22
	}
23
24
	public static function generate_csv( $atts ) {
25
		global $frm_vars;
26
		$frm_vars['prevent_caching'] = true;
27
28
		self::$fields = $atts['form_cols'];
29
		self::$form_id = $atts['form']->id;
30
		self::set_class_paramters();
31
		self::set_has_parent_id( $atts['form'] );
32
33
		$filename = apply_filters( 'frm_csv_filename', date( 'ymdHis', time() ) . '_' . sanitize_title_with_dashes( $atts['form']->name ) . '_formidable_entries.csv', $atts['form'] );
34
		unset( $atts['form'], $atts['form_cols'] );
35
36
		self::print_file_headers( $filename );
37
		unset( $filename );
38
39
		$comment_count = FrmDb::get_count(
40
			'frm_item_metas',
41
			array(
42
				'item_id'  => $atts['entry_ids'],
43
				'field_id' => 0,
44
				'meta_value like' => '{',
45
			),
46
			array(
47
				'group_by' => 'item_id',
48
				'order_by' => 'count(*) DESC',
49
				'limit'    => 1,
50
			)
51
		);
52
		self::$comment_count = $comment_count;
53
54
		self::prepare_csv_headings();
55
56
		// fetch 20 posts at a time rather than loading the entire table into memory
57
		while ( $next_set = array_splice( $atts['entry_ids'], 0, 20 ) ) {
58
			self::prepare_next_csv_rows( $next_set );
59
		}
60
	}
61
62
	private static function set_class_paramters() {
63
		self::$separator = apply_filters( 'frm_csv_sep', self::$separator );
64
		self::$line_break = apply_filters( 'frm_csv_line_break', self::$line_break );
65
		self::$wp_date_format = apply_filters( 'frm_csv_date_format', self::$wp_date_format );
66
		self::get_csv_format();
67
		self::$charset = get_option( 'blog_charset' );
68
69
		$col_sep = ( isset( $_POST['csv_col_sep'] ) && ! empty( $_POST['csv_col_sep'] ) ) ? sanitize_text_field( $_POST['csv_col_sep'] ) : self::$column_separator;
70
		self::$column_separator = apply_filters( 'frm_csv_column_sep', $col_sep );
71
	}
72
73
	private static function set_has_parent_id( $form ) {
74
		self::$has_parent_id = $form->parent_form_id > 0;
75
	}
76
77
	private static function print_file_headers( $filename ) {
78
		header( 'Content-Description: File Transfer' );
79
		header( 'Content-Disposition: attachment; filename="' . esc_attr( $filename ) . '"' );
80
		header( 'Content-Type: text/csv; charset=' . self::$charset, true );
81
		header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', mktime( date( 'H' ) + 2, date( 'i' ), date( 's' ), date( 'm' ), date( 'd' ), date( 'Y' ) ) ) . ' GMT' );
82
		header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
83
		header( 'Cache-Control: no-cache, must-revalidate' );
84
		header( 'Pragma: no-cache' );
85
86
		do_action( 'frm_csv_headers', array(
87
			'form_id' => self::$form_id,
88
			'fields'  => self::$fields,
89
		) );
90
	}
91
92
	public static function get_csv_format() {
93
		$csv_format = FrmAppHelper::get_post_param( 'csv_format', 'UTF-8', 'sanitize_text_field' );
94
		$csv_format = apply_filters( 'frm_csv_format', $csv_format );
95
		self::$to_encoding = $csv_format;
96
	}
97
98
	private static function prepare_csv_headings() {
99
		$headings = array();
100
		self::csv_headings( $headings );
101
		$headings = apply_filters( 'frm_csv_columns', $headings, self::$form_id, array(
102
			'fields' => self::$fields,
103
		) );
104
		self::$headings = $headings;
105
106
		self::print_csv_row( $headings );
107
	}
108
109
	private static function csv_headings( &$headings ) {
110
		foreach ( self::$fields as $col ) {
111
			$field_headings = array();
112
			if ( isset( $col->field_options['separate_value'] ) && $col->field_options['separate_value'] && ! in_array( $col->type, array( 'user_id', 'file', 'data', 'date' ), true ) ) {
113
				$field_headings[ $col->id . '_label' ] = strip_tags( $col->name . ' ' . __( '(label)', 'formidable' ) );
114
			}
115
116
			$field_headings[ $col->id ] = strip_tags( $col->name );
117
			$field_headings = apply_filters( 'frm_csv_field_columns', $field_headings, array(
118
				'field' => $col,
119
			) );
120
			$headings += $field_headings;
121
		}
122
123
		if ( self::$comment_count ) {
124
			for ( $i = 0; $i < self::$comment_count; $i++ ) {
125
				$headings[ 'comment' . $i ] = __( 'Comment', 'formidable' );
126
				$headings[ 'comment_user_id' . $i ] = __( 'Comment User', 'formidable' );
127
				$headings[ 'comment_created_at' . $i ] = __( 'Comment Date', 'formidable' );
128
			}
129
			unset( $i );
130
		}
131
132
		$headings['created_at'] = __( 'Timestamp', 'formidable' );
133
		$headings['updated_at'] = __( 'Last Updated', 'formidable' );
134
		$headings['user_id'] = __( 'Created By', 'formidable' );
135
		$headings['updated_by'] = __( 'Updated By', 'formidable' );
136
		$headings['is_draft'] = __( 'Draft', 'formidable' );
137
		$headings['ip'] = __( 'IP', 'formidable' );
138
		$headings['id'] = __( 'ID', 'formidable' );
139
		$headings['item_key'] = __( 'Key', 'formidable' );
140
		if ( self::has_parent_id() ) {
141
			$headings['parent_id'] = __( 'Parent ID', 'formidable' );
142
		}
143
	}
144
145
	private static function has_parent_id() {
146
		return self::$has_parent_id;
147
	}
148
149
	private static function prepare_next_csv_rows( $next_set ) {
150
		// order by parent_item_id so children will be first
151
		$where = array(
152
			'or' => 1,
153
			'id' => $next_set,
154
			'parent_item_id' => $next_set,
155
		);
156
		$entries = FrmEntry::getAll( $where, ' ORDER BY parent_item_id DESC', '', true, false );
157
158
		foreach ( $entries as $k => $entry ) {
159
			self::$entry = $entry;
160
			unset( $entry );
161
162
			if ( self::$entry->form_id !== self::$form_id ) {
163
				self::add_repeat_field_values_to_csv( $entries );
164
			} else {
165
				self::prepare_csv_row();
166
			}
167
		}
168
	}
169
170
	private static function prepare_csv_row() {
171
		$row = array();
172
		self::add_field_values_to_csv( $row );
173
		self::add_entry_data_to_csv( $row );
174
		$row = apply_filters( 'frm_csv_row', $row, array(
175
			'entry'         => self::$entry,
176
			'date_format'   => self::$wp_date_format,
177
			'comment_count' => self::$comment_count,
178
		) );
179
		self::print_csv_row( $row );
180
	}
181
182
	private static function add_repeat_field_values_to_csv( &$entries ) {
183
		if ( isset( self::$entry->metas ) ) {
184
			// add child entries to the parent
185
			foreach ( self::$entry->metas as $meta_id => $meta_value ) {
186
				if ( ! is_numeric( $meta_id ) || '' === $meta_value ) {
187
					// if the hook is being used to include field keys in the metas array,
188
					// we need to skip the keys and only process field ids
189
					continue;
190
				}
191
192
				if ( ! isset( $entries[ self::$entry->parent_item_id ]->metas[ $meta_id ] ) ) {
193
					$entries[ self::$entry->parent_item_id ]->metas[ $meta_id ] = array();
194
				} elseif ( ! is_array( $entries[ self::$entry->parent_item_id ]->metas[ $meta_id ] ) ) {
195
					// if the data is here, it should be an array but if this field has collected data
196
					// both while inside and outside of the repeating section, it's possible this is a string
197
					$entries[ self::$entry->parent_item_id ]->metas[ $meta_id ] = (array) $entries[ self::$entry->parent_item_id ]->metas[ $meta_id ];
198
				}
199
200
				//add the repeated values
201
				$entries[ self::$entry->parent_item_id ]->metas[ $meta_id ][] = $meta_value;
202
			}
203
			$entries[ self::$entry->parent_item_id ]->metas += self::$entry->metas;
204
		}
205
206
		// add the embedded form id
207
		if ( ! isset( $entries[ self::$entry->parent_item_id ]->embedded_fields ) ) {
208
			$entries[ self::$entry->parent_item_id ]->embedded_fields = array();
209
		}
210
		$entries[ self::$entry->parent_item_id ]->embedded_fields[ self::$entry->id ] = self::$entry->form_id;
211
	}
212
213
	private static function add_field_values_to_csv( &$row ) {
214
		foreach ( self::$fields as $col ) {
215
			$field_value = isset( self::$entry->metas[ $col->id ] ) ? self::$entry->metas[ $col->id ] : false;
216
217
			$field_value = maybe_unserialize( $field_value );
218
			self::add_array_values_to_columns( $row, compact( 'col', 'field_value' ) );
219
220
			$field_value = apply_filters( 'frm_csv_value', $field_value, array(
221
				'field'     => $col,
222
				'entry'     => self::$entry,
223
				'separator' => self::$separator,
224
			) );
225
226
			if ( isset( $col->field_options['separate_value'] ) && $col->field_options['separate_value'] ) {
227
				$sep_value = FrmEntriesHelper::display_value( $field_value, $col, array(
228
					'type'      => $col->type,
229
					'post_id'   => self::$entry->post_id,
230
					'show_icon' => false,
231
					'entry_id'  => self::$entry->id,
232
					'sep'       => self::$separator,
233
					'embedded_field_id' => ( isset( self::$entry->embedded_fields ) && isset( self::$entry->embedded_fields[ self::$entry->id ] ) ) ? 'form' . self::$entry->embedded_fields[ self::$entry->id ] : 0,
234
				) );
235
				$row[ $col->id . '_label' ] = $sep_value;
236
				unset( $sep_value );
237
			}
238
239
			$row[ $col->id ] = $field_value;
240
241
			unset( $col, $field_value );
242
		}
243
	}
244
245
	/**
246
	 * @since 2.0.23
247
	 */
248
	private static function add_array_values_to_columns( &$row, $atts ) {
249
		if ( is_array( $atts['field_value'] ) ) {
250
			foreach ( $atts['field_value'] as $key => $sub_value ) {
251
				$column_key = $atts['col']->id . '_' . $key;
252
				if ( ! is_numeric( $key ) && isset( self::$headings[ $column_key ] ) ) {
253
					$row[ $column_key ] = $sub_value;
254
				}
255
			}
256
		}
257
	}
258
259
	private static function add_entry_data_to_csv( &$row ) {
260
		$row['created_at'] = FrmAppHelper::get_formatted_time( self::$entry->created_at, self::$wp_date_format, ' ' );
261
		$row['updated_at'] = FrmAppHelper::get_formatted_time( self::$entry->updated_at, self::$wp_date_format, ' ' );
262
		$row['user_id'] = self::$entry->user_id;
263
		$row['updated_by'] = self::$entry->updated_by;
264
		$row['is_draft'] = self::$entry->is_draft ? '1' : '0';
265
		$row['ip'] = self::$entry->ip;
266
		$row['id'] = self::$entry->id;
267
		$row['item_key'] = self::$entry->item_key;
268
		if ( self::has_parent_id() ) {
269
			$row['parent_id'] = self::$entry->parent_item_id;
270
		}
271
	}
272
273
	private static function print_csv_row( $rows ) {
274
		$sep = '';
275
276
		foreach ( self::$headings as $k => $heading ) {
277
			$row = isset( $rows[ $k ] ) ? $rows[ $k ] : '';
278
			if ( is_array( $row ) ) {
279
				// implode the repeated field values
280
				$row = implode( self::$separator, FrmAppHelper::array_flatten( $row, 'reset' ) );
281
			}
282
283
			$val = self::encode_value( $row );
284
			if ( 'return' !== self::$line_break ) {
285
				$val = str_replace( array( "\r\n", "\r", "\n" ), self::$line_break, $val );
286
			}
287
288
			echo $sep . '"' . $val . '"'; // WPCS: XSS ok.
289
			$sep = self::$column_separator;
290
291
			unset( $k, $row );
292
		}
293
		echo "\n";
294
	}
295
296
	public static function encode_value( $line ) {
297
		if ( '' === $line ) {
298
			return $line;
299
		}
300
301
		$convmap = false;
302
303
		switch ( self::$to_encoding ) {
304
			case 'macintosh':
305
				// this map was derived from the differences between the MacRoman and UTF-8 Charsets
306
				// Reference:
307
				//   - http://www.alanwood.net/demos/macroman.html
308
				$convmap = array( 256, 304, 0, 0xffff, 306, 337, 0, 0xffff, 340, 375, 0, 0xffff, 377, 401, 0, 0xffff, 403, 709, 0, 0xffff, 712, 727, 0, 0xffff, 734, 936, 0, 0xffff, 938, 959, 0, 0xffff, 961, 8210, 0, 0xffff, 8213, 8215, 0, 0xffff, 8219, 8219, 0, 0xffff, 8227, 8229, 0, 0xffff, 8231, 8239, 0, 0xffff, 8241, 8248, 0, 0xffff, 8251, 8259, 0, 0xffff, 8261, 8363, 0, 0xffff, 8365, 8481, 0, 0xffff, 8483, 8705, 0, 0xffff, 8707, 8709, 0, 0xffff, 8711, 8718, 0, 0xffff, 8720, 8720, 0, 0xffff, 8722, 8729, 0, 0xffff, 8731, 8733, 0, 0xffff, 8735, 8746, 0, 0xffff, 8748, 8775, 0, 0xffff, 8777, 8799, 0, 0xffff, 8801, 8803, 0, 0xffff, 8806, 9673, 0, 0xffff, 9675, 63742, 0, 0xffff, 63744, 64256, 0, 0xffff );
309
				break;
310
			case 'ISO-8859-1':
311
				$convmap = array( 256, 10000, 0, 0xffff );
312
		}
313
314
		if ( is_array( $convmap ) ) {
315
			$line = mb_encode_numericentity( $line, $convmap, self::$charset );
316
		}
317
318
		if ( self::$to_encoding !== self::$charset ) {
319
			$line = iconv( self::$charset, self::$to_encoding . '//IGNORE', $line );
320
		}
321
322
		return self::escape_csv( $line );
323
    }
324
325
	/**
326
	 * Escape a " in a csv with another "
327
	 * @since 2.0
328
	 */
329
	public static function escape_csv( $value ) {
330
		if ( '=' === $value[0] ) {
331
			// escape the = to prevent vulnerability
332
			$value = "'" . $value;
333
		}
334
		$value = str_replace( '"', '""', $value );
335
		return $value;
336
	}
337
}
338