Test Failed
Push — issues/2114 ( 447fcd )
by Ravinder
06:06
created

Give_Import_Donations::import_success()   C

Complexity

Conditions 10
Paths 96

Size

Total Lines 91
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 65
nc 96
nop 0
dl 0
loc 91
rs 5.1219
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
 * Donations Import Class
4
 *
5
 * This class handles donations import.
6
 *
7
 * @package     Give
8
 * @subpackage  Classes/Give_Import_Donations
9
 * @copyright   Copyright (c) 2017, WordImpress
10
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
11
 * @since       1.8.14
12
 */
13
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit; // Exit if accessed directly
16
}
17
18
if ( ! class_exists( 'Give_Import_Donations' ) ) {
19
20
	/**
21
	 * Give_Import_Donations.
22
	 *
23
	 * @since 1.8.14
24
	 */
25
	final class Give_Import_Donations {
26
27
		/**
28
		 * Importer type
29
		 *
30
		 * @since 1.8.13
31
		 * @var string
32
		 */
33
		private $importer_type = 'import_donations';
34
35
		/**
36
		 * Instance.
37
		 *
38
		 * @since
39
		 * @access static
40
		 * @var
41
		 */
42
		static private $instance;
43
44
		/**
45
		 * Importing donation per page.
46
		 *
47
		 * @since 1.8.14
48
		 *
49
		 * @var   int
50
		 */
51
		public static $per_page = 5;
52
53
		/**
54
		 * Singleton pattern.
55
		 *
56
		 * @since
57
		 * @access private
58
		 */
59
		private function __construct() {
60
		}
61
62
63
		/**
64
		 * Get instance.
65
		 *
66
		 * @since
67
		 * @access static
68
		 * @return static
69
		 */
70
		public static function get_instance() {
71
			if ( null === static::$instance ) {
72
				self::$instance = new static();
73
			}
74
75
			return self::$instance;
76
		}
77
78
		/**
79
		 * Setup
80
		 *
81
		 * @since 1.8.14
82
		 *
83
		 * @return void
84
		 */
85
		public function setup() {
86
			$this->setup_hooks();
87
		}
88
89
90
		/**
91
		 * Setup Hooks.
92
		 *
93
		 * @since 1.8.14
94
		 *
95
		 * @return void
96
		 */
97
		private function setup_hooks() {
98
			if ( ! $this->is_donations_import_page() ) {
99
				return;
100
			}
101
102
			// Do not render main import tools page.
103
			remove_action( 'give_admin_field_tools_import', array( 'Give_Settings_Import', 'render_import_field', ) );
104
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
105
106
			// Render donation import page
107
			add_action( 'give_admin_field_tools_import', array( $this, 'render_page' ) );
108
109
			// Print the HTML.
110
			add_action( 'give_tools_import_donations_form_start', array( $this, 'html' ), 10 );
111
112
			// Run when form submit.
113
			add_action( 'give-tools_save_import', array( $this, 'save' ) );
114
115
			add_action( 'give-tools_update_notices', array( $this, 'update_notices' ), 11, 1 );
116
117
			// Used to add submit button.
118
			add_action( 'give_tools_import_donations_form_end', array( $this, 'submit' ), 10 );
119
		}
120
121
122
		/**
123
		 * Update notice
124
		 *
125
		 * @since 1.8.14
126
		 *
127
		 * @param $messages
128
		 *
129
		 * @return mixed
130
		 */
131
		public function update_notices( $messages ) {
132
			if ( ! empty( $_GET['tab'] ) && 'import' === give_clean( $_GET['tab'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
133
				unset( $messages['give-setting-updated'] );
134
			}
135
136
			return $messages;
137
		}
138
139
		/**
140
		 * Print submit and nonce button.
141
		 *
142
		 * @since 1.8.14
143
		 */
144
		public function submit() {
145
			wp_nonce_field( 'give-save-settings', '_give-save-settings' );
146
			?>
147
			<input type="hidden" class="import-step" id="import-step" name="step" value="<?php echo $this->get_step(); ?>"/>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$this'
Loading history...
148
			<input type="hidden" class="importer-type" value="<?php echo $this->importer_type; ?>"/>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$this'
Loading history...
149
			<?php
150
		}
151
152
		/**
153
		 * Print the HTML for importer.
154
		 *
155
		 * @since 1.8.14
156
		 */
157
		public function html() {
158
			$step = $this->get_step();
159
160
			// Show progress.
161
			$this->render_progress();
162
			?>
163
			<section>
164
				<table class="widefat export-options-table give-table <?php echo "step-{$step}"; ?>" id="<?php echo "step-{$step}"; ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '"step-{$step}"'
Loading history...
165
					<tbody>
166
						<?php
167
						switch ( $this->get_step() ) {
168
							case 1:
169
								$this->render_media_csv();
170
								break;
171
172
							case 2:
173
								$this->render_dropdown();
174
								break;
175
176
							case 3:
177
								$this->start_import();
178
								break;
179
180
							case 4:
181
								$this->import_success();
182
						}
183
184
						if ( false === $this->check_for_dropdown_or_import() ) {
185
							?>
186
							<tr valign="top">
187
								<th></th>
188
								<th>
189
									<input type="submit"
190
										   class="button button-primary button-large button-secondary <?php echo "step-{$step}"; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '"step-{$step}"'
Loading history...
191
										   id="recount-stats-submit"
192
										   value="<?php esc_attr_e( 'Submit', 'give' ); ?>"/>
193
								</th>
194
							</tr>
195
							<?php
196
						}
197
						?>
198
					</tbody>
199
				</table>
200
			</section>
201
			<?php
202
		}
203
204
		/**
205
		 * Show success notice
206
		 *
207
		 * @since 1.8.14
208
		 */
209
		public function import_success() {
210
211
			$delete_csv = ( ! empty( $_GET['delete_csv'] ) ? absint( $_GET['delete_csv'] ) : false );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
212
			$csv        = ( ! empty( $_GET['csv'] ) ? absint( $_GET['csv'] ) : false );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
213
			if ( ! empty( $delete_csv ) && ! empty( $csv ) ) {
214
				wp_delete_attachment( $csv, true );
215
			}
216
217
			$report      = give_import_donation_report();
218
			$report_html = array(
219
				'duplicate_donor'    => array(
220
					__( '%s duplicate %s detected', 'give' ),
221
					__( 'donor', 'give' ),
222
					__( 'donors', 'give' ),
223
				),
224
				'create_donor'       => array(
225
					__( '%s %s created', 'give' ),
226
					__( 'donor', 'give' ),
227
					__( 'donors', 'give' ),
228
				),
229
				'create_form'        => array(
230
					__( '%s donation %s created', 'give' ),
231
					__( 'form', 'give' ),
232
					__( 'forms', 'give' ),
233
				),
234
				'duplicate_donation' => array(
235
					__( '%s duplicate %s detected', 'give' ),
236
					__( 'donation', 'give' ),
237
					__( 'donations', 'give' ),
238
				),
239
				'create_donation'    => array(
240
					__( '%s %s imported', 'give' ),
241
					__( 'donation', 'give' ),
242
					__( 'donations', 'give' ),
243
				),
244
			);
245
			$total       = (int) $_GET['total'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
246
			-- $total;
247
			$success = (bool) $_GET['success'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
248
			?>
249
			<tr valign="top" class="give-import-dropdown">
250
				<th colspan="2">
251
					<h2>
252
						<?php
253
						if ( $success ) {
254
							echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
255
								__( 'Import complete! %s donations processed', 'give' ),
256
								"<strong>{$total}</strong>"
257
							);
258
						} else {
259
							echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
260
								__( 'Failed to import %s donations', 'give' ),
261
								"<strong>{$total}</strong>"
262
							);
263
						}
264
						?>
265
					</h2>
266
267
					<?php
268
					$text      = __( 'Import Donation', 'give' );
269
					$query_arg = array(
270
						'post_type' => 'give_forms',
271
						'page'      => 'give-tools',
272
						'tab'       => 'import',
273
					);
274
					if ( $success ) {
275
						$query_arg = array(
276
							'post_type' => 'give_forms',
277
							'page'      => 'give-payment-history',
278
						);
279
						$text      = __( 'View Donations', 'give' );
280
					}
281
282
					foreach ( $report as $key => $value ) {
283
						if ( array_key_exists( $key, $report_html ) && ! empty( $value ) ) {
284
							?>
285
							<p>
286
								<?php echo esc_html( wp_sprintf( $report_html[ $key ][0], $value, _n( $report_html[ $key ][1], $report_html[ $key ][2], $value, 'give' ) ) ); ?>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$report_html'
Loading history...
287
							</p>
288
							<?php
289
						}
290
					}
291
					?>
292
293
					<p>
294
						<a class="button button-large button-secondary" href="<?php echo add_query_arg( $query_arg, admin_url( 'edit.php' ) ); ?>"><?php echo $text; ?></a>
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'add_query_arg'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$text'
Loading history...
295
					</p>
296
				</th>
297
			</tr>
298
			<?php
299
		}
300
301
		/**
302
		 * Will start Import
303
		 *
304
		 * @since 1.8.14
305
		 */
306
		public function start_import() {
307
			// Reset the donation form report.
308
			give_import_donation_report_reset();
309
310
			$csv         = (int) $_REQUEST['csv'];
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_REQUEST
Loading history...
311
			$index_start = 1;
312
			$index_end   = 1;
0 ignored issues
show
Unused Code introduced by
$index_end is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
313
			$next        = true;
314
			$total       = self::get_csv_total( $csv );
315
			if ( self::$per_page < $total ) {
316
				$total_ajax = ceil( $total / self::$per_page );
317
				$index_end  = self::$per_page;
318
			} else {
319
				$total_ajax = 1;
320
				$index_end  = $total;
321
				$next       = false;
322
			}
323
			$current_percentage = 100 / ( $total_ajax + 1 );
324
325
			?>
326
			<tr valign="top" class="give-import-dropdown">
327
				<th colspan="2">
328
					<h2 id="give-import-title"><?php esc_html_e( 'Importing', 'give' ) ?></h2>
329
					<p class="give-field-description"><?php esc_html_e( 'Your donations are now being imported...', 'give' ) ?></p>
330
				</th>
331
			</tr>
332
333
			<tr valign="top" class="give-import-dropdown">
334
				<th colspan="2">
335
					<span class="spinner is-active"></span>
336
					<div class="give-progress"
337
						 data-current="1"
338
						 data-total_ajax="<?php echo $total_ajax; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$total_ajax'
Loading history...
339
						 data-start="<?php echo $index_start; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$index_start'
Loading history...
340
						 data-end="<?php echo $index_end; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$index_end'
Loading history...
341
						 data-next="<?php echo $next; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$next'
Loading history...
342
						 data-total="<?php echo $total; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$total'
Loading history...
343
						 data-per_page="<?php echo self::$per_page; ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not 'self'
Loading history...
344
345
						<div style="width: <?php echo $current_percentage; ?>%"></div>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$current_percentage'
Loading history...
346
					</div>
347
					<input type="hidden" value="3" name="step">
348
					<input type="hidden" value='<?php echo maybe_serialize( $_REQUEST['mapto'] ); ?>' name="mapto"
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'maybe_serialize'
Loading history...
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_REQUEST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
349
						   class="mapto">
350
					<input type="hidden" value="<?php echo $_REQUEST['csv']; ?>" name="csv" class="csv">
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Expected next thing to be a escaping function, not '$_REQUEST'
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
351
					<input type="hidden" value="<?php echo $_REQUEST['mode']; ?>" name="mode" class="mode">
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Expected next thing to be a escaping function, not '$_REQUEST'
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
352
					<input type="hidden" value="<?php echo $_REQUEST['create_user']; ?>" name="create_user"
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Expected next thing to be a escaping function, not '$_REQUEST'
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
353
						   class="create_user">
354
					<input type="hidden" value="<?php echo $_REQUEST['delete_csv']; ?>" name="delete_csv"
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Expected next thing to be a escaping function, not '$_REQUEST'
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
355
						   class="delete_csv">
356
					<input type="hidden" value="<?php echo $_REQUEST['delimiter']; ?>" name="delimiter">
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Expected next thing to be a escaping function, not '$_REQUEST'
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
357
					<input type="hidden" value='<?php echo maybe_serialize( self::get_importer( $csv ) ); ?>'
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'maybe_serialize'
Loading history...
358
						   name="main_key"
359
						   class="main_key">
360
				</th>
361
			</tr>
362
363
			<script type="text/javascript">
364
				jQuery(document).ready(function () {
365
					give_on_donation_import_start();
366
				});
367
			</script>
368
			<?php
369
		}
370
371
		/**
372
		 * Will return true if importing can be started or not else false.
373
		 *
374
		 * @since 1.8.14
375
		 */
376
		public function check_for_dropdown_or_import() {
377
			$return = true;
378
			if ( isset( $_REQUEST['mapto'] ) ) {
379
				$mapto = (array) $_REQUEST['mapto'];
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
380
				if ( false === in_array( 'form_title', $mapto ) && false === in_array( 'form_id', $mapto ) ) {
381
					Give_Admin_Settings::add_error( 'give-import-csv-form', __( 'Please select Form ID or Form Name options from the dropdown.', 'give' ) );
382
					$return = false;
383
				}
384
385
				if ( false === in_array( 'amount', $mapto ) ) {
386
					Give_Admin_Settings::add_error( 'give-import-csv-amount', __( 'Please select Amount option from the dropdown.', 'give' ) );
387
					$return = false;
388
				}
389
390
				if ( false === in_array( 'email', $mapto ) && false === in_array( 'donor_id', $mapto ) ) {
391
					Give_Admin_Settings::add_error( 'give-import-csv-donor', __( 'Please select Email id or Customer ID options from the dropdown.', 'give' ) );
392
					$return = false;
393
				}
394
			} else {
395
				$return = false;
396
			}
397
398
			return $return;
399
		}
400
401
		/**
402
		 * Print the Dropdown option for CSV.
403
		 *
404
		 * @since 1.8.14
405
		 */
406
		public function render_dropdown() {
407
			$csv = (int) $_GET['csv'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
408
409
			// TO check if the CSV files that is being add is valid or not if not then redirect to first step again
410
			$has_error = $this->csv_check( $csv );
0 ignored issues
show
Documentation introduced by
$csv is of type integer, but the function expects a boolean.

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...
411
			if ( $has_error ) {
412
				$url = give_import_page_url();
413
				?>
414
				<script type="text/javascript">
415
					window.location = "<?php echo $url; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$url'
Loading history...
416
				</script>
417
				<?php
418
			} else {
419
				?>
420
				<tr valign="top" class="give-import-dropdown">
421
					<th colspan="2">
422
						<h2 id="give-import-title"><?php esc_html_e( 'Map CSV fields to donations', 'give' ) ?></h2>
423
						<p class="give-field-description"><?php esc_html_e( 'Select fields from your CSV file to map against donations fields or to ignore during import.', 'give' ) ?></p>
424
					</th>
425
				</tr>
426
427
				<tr valign="top" class="give-import-dropdown">
428
					<th><b><?php esc_html_e( 'Column name', 'give' ); ?></b></th>
429
					<th><b><?php esc_html_e( 'Map to field', 'give' ); ?></b></th>
430
				</tr>
431
432
				<?php
433
				$raw_key   = $this->get_importer( $csv );
434
				$donations = give_import_donations_options();
435
				$donors    = give_import_donor_options();
436
				$forms     = give_import_donation_form_options();
437
438
				foreach ( $raw_key as $index => $value ) {
0 ignored issues
show
Bug introduced by
The expression $raw_key of type array<integer,string|nul...":"string|null"}>|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
439
					?>
440
					<tr valign="top" class="give-import-option">
441
						<th><?php echo $value; ?></th>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$value'
Loading history...
442
						<th>
443
							<?php
444
							$this->get_columns( $index, $donations, $donors, $forms, $value );
445
							?>
446
						</th>
447
					</tr>
448
					<?php
449
				}
450
			}
451
		}
452
453
		/**
454
		 * @param $option_value
455
		 * @param $value
456
		 *
457
		 * @return string
458
		 */
459
		public function selected( $option_value, $value ) {
460
			$selected = '';
461
			if ( stristr( $value, $option_value ) ) {
462
				$selected = 'selected';
463
			} elseif ( strrpos( $value, '_' ) && stristr( $option_value, 'Import as Meta' ) ) {
464
				$selected = 'selected';
465
			}
466
467
			return $selected;
468
		}
469
470
		/**
471
		 * Print the columns from the CSV.
472
		 *
473
		 * @since 1.8.14
474
		 */
475
		public function get_columns( $index, $donations, $donors, $forms, $value = false ) {
476
			$default = give_import_default_options();
477
			?>
478
			<select name="mapto[<?php echo $index; ?>]">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$index'
Loading history...
479
				<?php
480 View Code Duplication
				foreach ( $default as $option => $option_value ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
481
					$checked = $this->selected( $option_value, $value );
482
					?>
483
					<option value="<?php echo $option; ?>" <?php echo $checked; ?> ><?php echo $option_value; ?></option>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$option'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$checked'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$option_value'
Loading history...
484
					<?php
485
				}
486
				?>
487
				<optgroup label="Donations">
488
					<?php
489 View Code Duplication
					foreach ( $donations as $option => $option_value ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
490
						$checked = $this->selected( $option_value, $value );
491
						?>
492
						<option value="<?php echo $option; ?>" <?php echo $checked; ?> ><?php echo $option_value; ?></option>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$option'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$checked'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$option_value'
Loading history...
493
						<?php
494
					}
495
					?>
496
				</optgroup>
497
498
				<optgroup label="Donors">
499
					<?php
500 View Code Duplication
					foreach ( $donors as $option => $option_value ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
501
						$checked = $this->selected( $option_value, $value );
502
						?>
503
						<option value="<?php echo $option; ?>" <?php echo $checked; ?> ><?php echo $option_value; ?></option>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$option'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$checked'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$option_value'
Loading history...
504
						<?php
505
					}
506
					?>
507
				</optgroup>
508
509
				<optgroup label="Forms">
510
					<?php
511 View Code Duplication
					foreach ( $forms as $option => $option_value ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
512
						$checked = $this->selected( $option_value, $value );
513
						?>
514
						<option value="<?php echo $option; ?>" <?php echo $checked; ?> ><?php echo $option_value; ?></option>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$option'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$checked'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$option_value'
Loading history...
515
						<?php
516
					}
517
					?>
518
				</optgroup>
519
520
				<?php
521
				do_action( 'give_import_dropdown_option', $index, $donations, $donors, $forms, $value );
522
				?>
523
			</select>
524
			<?php
525
		}
526
527
		/**
528
		 * Get column count of csv file.
529
		 *
530
		 * @since 1.8.14
531
		 *
532
		 * @param $file_id
533
		 *
534
		 * @return bool|int
535
		 */
536
		public function get_csv_total( $file_id ) {
537
			$total = false;
538
			if ( $file_id ) {
539
				$file_dir = get_attached_file( $file_id );
540
				if ( $file_dir ) {
541
					$file = new SplFileObject( $file_dir, 'r' );
542
					$file->seek( PHP_INT_MAX );
543
					$total = $file->key() + 1;
544
				}
545
			}
546
547
			return $total;
548
		}
549
550
		/**
551
		 * Get the CSV fields title from the CSV.
552
		 *
553
		 * @since 1.8.14
554
		 *
555
		 * @param (int) $file_id
556
		 * @param int    $index
557
		 * @param string $delimiter
558
		 *
559
		 * @return array|bool $raw_data title of the CSV file fields
560
		 */
561
		public function get_importer( $file_id, $index = 0, $delimiter = ',' ) {
562
			$raw_data = false;
563
			$file_dir = get_attached_file( $file_id );
564
			if ( $file_dir ) {
565
				if ( false !== ( $handle = fopen( $file_dir, 'r' ) ) ) {
566
					$raw_data = fgetcsv( $handle, $index, $delimiter );
567
					// Remove BOM signature from the first item.
568
					if ( isset( $raw_data[0] ) ) {
569
						$raw_data[0] = $this->remove_utf8_bom( $raw_data[0] );
570
					}
571
				}
572
			}
573
574
			return $raw_data;
575
		}
576
577
		/**
578
		 * Remove UTF-8 BOM signature.
579
		 *
580
		 * @since 1.8.14
581
		 *
582
		 * @param  string $string String to handle.
583
		 *
584
		 * @return string
585
		 */
586
		public function remove_utf8_bom( $string ) {
587
			if ( 'efbbbf' === substr( bin2hex( $string ), 0, 6 ) ) {
588
				$string = substr( $string, 3 );
589
			}
590
591
			return $string;
592
		}
593
594
595
		/**
596
		 * Is used to show the process when user upload the donor form.
597
		 *
598
		 * @since 1.8.14
599
		 */
600
		public function render_progress() {
601
			$step = $this->get_step();
602
			?>
603
			<ol class="give-progress-steps">
604
				<li class="<?php echo( 1 === $step ? 'active' : '' ); ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
605
					<?php esc_html_e( 'Upload CSV file', 'give' ); ?>
606
				</li>
607
				<li class="<?php echo( 2 === $step ? 'active' : '' ); ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
608
					<?php esc_html_e( 'Column mapping', 'give' ); ?>
609
				</li>
610
				<li class="<?php echo( 3 === $step ? 'active' : '' ); ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
611
					<?php esc_html_e( 'Import', 'give' ); ?>
612
				</li>
613
				<li class="<?php echo( 4 === $step ? 'active' : '' ); ?>">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
614
					<?php esc_html_e( 'Done!', 'give' ); ?>
615
				</li>
616
			</ol>
617
			<?php
618
		}
619
620
		/**
621
		 * Will return the import step.
622
		 *
623
		 * @since 1.8.14
624
		 *
625
		 * @return int $step on which step doest the import is on.
626
		 */
627
		public function get_step() {
628
			$step    = (int) ( isset( $_REQUEST['step'] ) ? give_clean( $_REQUEST['step'] ) : 0 );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
629
			$on_step = 1;
630
631
			if ( empty( $step ) || 1 === $step ) {
632
				$on_step = 1;
633
			} elseif ( $this->check_for_dropdown_or_import() ) {
634
				$on_step = 3;
635
			} elseif ( 2 === $step ) {
636
				$on_step = 2;
637
			} elseif ( 4 === $step ) {
638
				$on_step = 4;
639
			}
640
641
			return $on_step;
642
		}
643
644
		/**
645
		 * Render donations import page
646
		 *
647
		 * @since 1.8.14
648
		 */
649
		public function render_page() {
650
			include_once GIVE_PLUGIN_DIR . 'includes/admin/tools/views/html-admin-page-import-donations.php';
651
		}
652
653
		/**
654
		 * Add CSV upload HTMl
655
		 *
656
		 * Print the html of the file upload from which CSV will be uploaded.
657
		 *
658
		 * @since 1.8.14
659
		 * @return void
660
		 */
661
		public function render_media_csv() {
662
			?>
663
			<tr valign="top">
664
				<th colspan="2">
665
					<h2 id="give-import-title"><?php esc_html_e( 'Import donations from a CSV file', 'give' ) ?></h2>
666
					<p class="give-field-description"><?php esc_html_e( 'This tool allows you to import (or merge) donation data to give from a CSV file.', 'give' ) ?></p>
667
				</th>
668
			</tr>
669
			<?php
670
			$csv         = ( isset( $_REQUEST['csv'] ) ? give_clean( $_POST['csv'] ) : '' );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
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...
671
			$delimiter   = ( isset( $_REQUEST['delimiter'] ) ? give_clean( $_POST['delimiter'] ) : ',' );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
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...
672
			$mode        = ( ! empty( $_REQUEST['mode'] ) ? 'on' : '' );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
673
			$create_user = ( isset( $_REQUEST['create_user'] ) && isset( $_REQUEST['csv'] ) && 1 === absint( $_REQUEST['create_user'] ) ? 'on' : ( isset( $_REQUEST['csv'] ) ? '' : 'on' ) );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
674
			$delete_csv  = ( isset( $_REQUEST['delete_csv'] ) && isset( $_REQUEST['csv'] ) && 1 === absint( $_REQUEST['delete_csv'] ) ? 'on' : ( isset( $_REQUEST['csv'] ) ? '' : 'on' ) );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
675
676
			$settings = array(
677
				array(
678
					'id'         => 'csv',
679
					'name'       => __( 'Choose a CSV file:', 'give' ),
680
					'type'       => 'file',
681
					'attributes' => array( 'editing' => 'false', 'library' => 'text' ),
682
					'fvalue'     => 'id',
683
					'default'    => $csv,
684
				),
685
				array(
686
					'id'         => 'delimiter',
687
					'name'       => __( 'CSV Delimiter:', 'give' ),
688
					'type'       => 'text',
689
					'attributes' => array( 'placeholder' => ',', 'size' => '2' ),
690
					'default'    => $delimiter,
691
				),
692
				array(
693
					'id'      => 'mode',
694
					'name'    => __( 'Test Mode:', 'give' ),
695
					'type'    => 'checkbox',
696
					'default' => $mode,
697
				),
698
				array(
699
					'id'      => 'create_user',
700
					'name'    => __( 'Create WP users for new donors:', 'give' ),
701
					'type'    => 'checkbox',
702
					'default' => $create_user,
703
				),
704
				array(
705
					'id'      => 'delete_csv',
706
					'name'    => __( 'Delete CSV after import:', 'give' ),
707
					'type'    => 'checkbox',
708
					'default' => $delete_csv,
709
				),
710
			);
711
712
			$settings = apply_filters( 'give_import_file_upload_html', $settings );
713
714
			Give_Admin_Settings::output_fields( $settings, 'give_settings' );
715
		}
716
717
		/**
718
		 * Run when user click on the submit button.
719
		 *
720
		 * @since 1.8.14
721
		 */
722
		public function save() {
723
			// Get the current step.
724
			$step = Give_Import_Donations::get_step();
725
726
			// Validation for first step.
727
			if ( 1 === $step ) {
728
				$csv = absint( $_POST['csv'] );
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-validated input variable: $_POST
Loading history...
729
730
				$has_error = $this->csv_check( $csv );
731
732
				if ( false == $has_error ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
733
734
					$url = give_import_page_url( (array) apply_filters( 'give_import_step_two_url', array(
735
						'step'          => '2',
736
						'importer-type' => $this->importer_type,
737
						'csv'           => $csv,
738
						'delimiter'     => ( isset( $_REQUEST['delimiter'] ) ) ? give_clean( $_REQUEST['delimiter'] ) : ',',
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
739
						'mode'          => ( isset( $_REQUEST['mode'] ) ) ? give_clean( $_REQUEST['mode'] ) : '0',
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
740
						'create_user'   => ( isset( $_REQUEST['create_user'] ) ) ? give_clean( $_REQUEST['create_user'] ) : '0',
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
741
						'delete_csv'    => ( isset( $_REQUEST['delete_csv'] ) ) ? give_clean( $_REQUEST['delete_csv'] ) : '0',
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
742
					) ) );
743
					?>
744
					<script type="text/javascript">
745
						window.location = "<?php echo $url; ?>"
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$url'
Loading history...
746
					</script>
747
					<?php
748
				}
749
			}
750
		}
751
752
		/**
753
		 * Check if user uploaded csv is valid or not.
754
		 *
755
		 * @since 1.8.14
756
		 *
757
		 * param int $csv Id of the CSV files.
758
		 *
759
		 * return bool $has_error CSV is valid or not.
760
		 */
761
		public function csv_check( $csv = false ) {
762
			$has_error = false;
763
			if ( $csv ) {
764
				if ( ! wp_get_attachment_url( $csv ) ) {
765
					$has_error = true;
766
					Give_Admin_Settings::add_error( 'give-import-csv', __( 'Please upload or provide the ID to a valid CSV file.', 'give' ) );
767
				} elseif ( ( $mime_type = get_post_mime_type( $csv ) ) && ! strpos( $mime_type, 'csv' ) ) {
768
					$has_error = true;
769
					Give_Admin_Settings::add_error( 'give-import-csv', __( 'Please upload or provide the ID to a valid CSV file.', 'give' ) );
770
				}
771
			} else {
772
				$has_error = true;
773
				Give_Admin_Settings::add_error( 'give-import-csv', __( 'Please upload or provide the ID to a valid CSV file.', 'give' ) );
774
			}
775
776
			return $has_error;
777
		}
778
779
		/**
780
		 * Get settings array.
781
		 *
782
		 * @since  1.8.14
783
		 * @return array
784
		 */
785
		public function get_settings() {
786
			// Hide save button.
787
			$GLOBALS['give_hide_save_button'] = true;
788
789
			/**
790
			 * Filter the settings.
791
			 *
792
			 * @since  1.8.14
793
			 *
794
			 * @param  array $settings
795
			 */
796
			$settings = apply_filters(
797
				'give_get_settings_' . $this->id,
798
				array(
799
					array(
800
						'id'         => 'give_tools_import',
801
						'type'       => 'title',
802
						'table_html' => false,
803
					),
804
					array(
805
						'id'   => 'import',
806
						'name' => __( 'Import', 'give' ),
807
						'type' => 'tools_import',
808
					),
809
					array(
810
						'id'         => 'give_tools_import',
811
						'type'       => 'sectionend',
812
						'table_html' => false,
813
					),
814
				)
815
			);
816
817
			// Output.
818
			return $settings;
819
		}
820
821
		/**
822
		 * Render report import field
823
		 *
824
		 * @since  1.8.14
825
		 * @access public
826
		 *
827
		 * @param $field
828
		 * @param $option_value
829
		 */
830
		public function render_import_field( $field, $option_value ) {
831
			include_once GIVE_PLUGIN_DIR . 'includes/admin/tools/views/html-admin-page-imports.php';
832
		}
833
834
		/**
835
		 * Get if current page import donations page or not
836
		 *
837
		 * @since 1.8.14
838
		 * @return bool
839
		 */
840
		private function is_donations_import_page() {
841
			return 'import' === give_get_current_setting_tab() &&
842
			       isset( $_GET['importer-type'] ) &&
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
843
			       $this->importer_type === give_clean( $_GET['importer-type'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
844
		}
845
	}
846
847
	Give_Import_Donations::get_instance()->setup();
848
}