Completed
Pull Request — master (#664)
by Devin
19:01
created

Give_Tools_Reset_Stats::delete_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 23 and the first side effect is on line 15.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Recount income and stats
4
 *
5
 * This class handles batch processing of resetting donations and income stats
6
 *
7
 * @subpackage  Admin/Tools/Give_Tools_Reset_Stats
8
 * @copyright   Copyright (c) 2016, WordImpress
9
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
10
 * @since       1.5
11
 */
12
13
// Exit if accessed directly
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Give_Tools_Reset_Stats Class
20
 *
21
 * @since 1.5
22
 */
23
class Give_Tools_Reset_Stats extends Give_Batch_Export {
24
25
	/**
26
	 * Our export type. Used for export-type specific filters/actions
27
	 * @var string
28
	 * @since 1.5
29
	 */
30
	public $export_type = '';
31
32
	/**
33
	 * Allows for a non-form batch processing to be run.
34
	 * @since  1.5
35
	 * @var boolean
36
	 */
37
	public $is_void = true;
38
39
	/**
40
	 * Sets the number of items to pull on each step
41
	 * @since  1.5
42
	 * @var integer
43
	 */
44
	public $per_step = 30;
45
46
	/**
47
	 * Get the Export Data
48
	 *
49
	 * @access public
50
	 * @since 1.5
51
	 * @global object $wpdb Used to query the database using the WordPress
52
	 *   Database API
53
	 * @return array $data The data for the CSV file
54
	 */
55
	public function get_data() {
56
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
57
58
		$items = $this->get_stored_data( 'give_temp_reset_ids' );
59
60
		if ( ! is_array( $items ) ) {
61
			return false;
62
		}
63
64
		$offset     = ( $this->step - 1 ) * $this->per_step;
65
		$step_items = array_slice( $items, $offset, $this->per_step );
66
67
		if ( $step_items ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $step_items of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
68
69
			$step_ids = array(
70
				'customers'  => array(),
71
				'forms' => array(),
72
				'other'      => array(),
73
			);
74
75
			foreach ( $step_items as $item ) {
76
77
				switch ( $item['type'] ) {
78
					case 'customer':
79
						$step_ids['customers'][] = $item['id'];
80
						break;
81
					case 'forms':
82
						$step_ids['give_forms'][] = $item['id'];
83
						break;
84
					default:
85
						$item_type                = apply_filters( 'give_reset_item_type', 'other', $item );
86
						$step_ids[ $item_type ][] = $item['id'];
87
						break;
88
				}
89
90
			}
91
92
			$sql = array();
93
94
			foreach ( $step_ids as $type => $ids ) {
95
96
				if ( empty( $ids ) ) {
97
					continue;
98
				}
99
100
				$ids = implode( ',', $ids );
101
102
				switch ( $type ) {
103
					case 'customers':
104
						$table_name = $wpdb->prefix . 'give_customers';
105
						$sql[]      = "DELETE FROM $table_name WHERE id IN ($ids)";
106
						break;
107
					case 'forms':
108
						$sql[] = "UPDATE $wpdb->postmeta SET meta_value = 0 WHERE meta_key = '_give_form_sales' AND post_id IN ($ids)";
109
						$sql[] = "UPDATE $wpdb->postmeta SET meta_value = 0.00 WHERE meta_key = '_give_form_earnings' AND post_id IN ($ids)";
110
						break;
111
					case 'other':
112
						$sql[] = "DELETE FROM $wpdb->posts WHERE id IN ($ids)";
113
						$sql[] = "DELETE FROM $wpdb->postmeta WHERE post_id IN ($ids)";
114
						$sql[] = "DELETE FROM $wpdb->comments WHERE comment_post_ID IN ($ids)";
115
						$sql[] = "DELETE FROM $wpdb->commentmeta WHERE comment_id NOT IN (SELECT comment_ID FROM $wpdb->comments)";
116
						break;
117
				}
118
119
				if ( ! in_array( $type, array( 'customers', 'forms', 'other' ) ) ) {
120
					// Allows other types of custom post types to filter on their own post_type
121
					// and add items to the query list, for the IDs found in their post type.
122
					$sql = apply_filters( 'give_reset_add_queries_' . $type, $sql, $ids );
123
				}
124
125
		
126
			}
127
128
			if ( ! empty( $sql ) ) {
129
				foreach ( $sql as $query ) {
130
					$wpdb->query( $query );
131
				}
132
			}
133
134
			return true;
135
136
		}
137
138
		return false;
139
140
	}
141
142
	/**
143
	 * Return the calculated completion percentage
144
	 *
145
	 * @since 1.5
146
	 * @return int
147
	 */
148
	public function get_percentage_complete() {
149
150
		$items = $this->get_stored_data( 'give_temp_reset_ids', false );
0 ignored issues
show
Unused Code introduced by
The call to Give_Tools_Reset_Stats::get_stored_data() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
151
		$total = count( $items );
152
153
		$percentage = 100;
154
155
		if ( $total > 0 ) {
156
			$percentage = ( ( $this->per_step * $this->step ) / $total ) * 100;
157
		}
158
159
		if ( $percentage > 100 ) {
160
			$percentage = 100;
161
		}
162
163
		return $percentage;
164
	}
165
166
	/**
167
	 * Set the properties specific to the payments export
168
	 *
169
	 * @since 1.5
170
	 *
171
	 * @param array $request The Form Data passed into the batch processing
172
	 */
173
	public function set_properties( $request ) {
174
	}
175
176
	/**
177
	 * Process a step
178
	 *
179
	 * @since 1.5
180
	 * @return bool
181
	 */
182
	public function process_step() {
183
184
		if ( ! $this->can_export() ) {
185
			wp_die( __( 'You do not have permission to export data.', 'give' ), __( 'Error', 'give' ), array( 'response' => 403 ) );
186
		}
187
188
		$had_data = $this->get_data();
189
190
		if ( $had_data ) {
191
			$this->done = false;
0 ignored issues
show
Bug introduced by
The property done does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
192
193
			return true;
194
		} else {
195
			update_option( 'give_earnings_total', 0 );
196
			delete_transient( 'give_earnings_total' );
197
			delete_transient( 'give_estimated_monthly_stats' . true );
198
			delete_transient( 'give_estimated_monthly_stats' . false );
199
			$this->delete_data( 'give_temp_reset_ids' );
200
201
			// Reset the sequential order numbers
202
			if ( give_get_option( 'enable_sequential' ) ) {
203
				delete_option( 'give_last_payment_number' );
204
			}
205
206
			$this->done    = true;
207
			$this->message = __( 'Donation forms, income, donations counts, and logs successfully reset.', 'give' );
0 ignored issues
show
Bug introduced by
The property message does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
208
209
			return false;
210
		}
211
	}
212
213
	/**
214
	 * Headers
215
	 */
216
	public function headers() {
217
		ignore_user_abort( true );
218
219
		if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
220
			set_time_limit( 0 );
221
		}
222
	}
223
224
	/**
225
	 * Perform the export
226
	 *
227
	 * @access public
228
	 * @since 1.5
229
	 * @return void
230
	 */
231
	public function export() {
232
233
		// Set headers
234
		$this->headers();
235
236
		give_die();
237
	}
238
239
	/**
240
	 * Pre Fetch
241
	 */
242
	public function pre_fetch() {
243
244
		if ( $this->step == 1 ) {
245
			$this->delete_data( 'give_temp_reset_ids' );
246
		}
247
248
		$items = get_option( 'give_temp_reset_ids', false );
249
250
		if ( false === $items ) {
251
			$items = array();
252
253
			$give_types_for_reset = array( 'give_forms', 'give_log', 'give_payment' );
254
			$give_types_for_reset = apply_filters( 'give_reset_store_post_types', $give_types_for_reset );
255
256
			$args = apply_filters( 'give_tools_reset_stats_total_args', array(
257
				'post_type'      => $give_types_for_reset,
258
				'post_status'    => 'any',
259
				'posts_per_page' => - 1,
260
			) );
261
262
			$posts = get_posts( $args );
263
			foreach ( $posts as $post ) {
264
				$items[] = array(
265
					'id'   => (int) $post->ID,
266
					'type' => $post->post_type,
267
				);
268
			}
269
270
			$customer_args = array( 'number' => - 1 );
271
			$customers     = Give()->customers->get_customers( $customer_args );
272
			foreach ( $customers as $customer ) {
273
				$items[] = array(
274
					'id'   => (int) $customer->id,
275
					'type' => 'customer',
276
				);
277
			}
278
279
			// Allow filtering of items to remove with an unassociative array for each item
280
			// The array contains the unique ID of the item, and a 'type' for you to use in the execution of the get_data method
281
			$items = apply_filters( 'give_reset_store_items', $items );
282
283
			$this->store_data( 'give_temp_reset_ids', $items );
284
		}
285
286
	}
287
288
	/**
289
	 * Given a key, get the information from the Database Directly
290
	 *
291
	 * @since  1.5
292
	 *
293
	 * @param  string $key The option_name
294
	 *
295
	 * @return mixed       Returns the data from the database
296
	 */
297
	private function get_stored_data( $key ) {
298
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
299
		$value = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = '%s'", $key ) );
300
301
		return empty( $value ) ? false : maybe_unserialize( $value );
302
	}
303
304
	/**
305
	 * Give a key, store the value
306
	 *
307
	 * @since  1.5
308
	 *
309
	 * @param  string $key The option_name
310
	 * @param  mixed $value The value to store
311
	 *
312
	 * @return void
313
	 */
314
	private function store_data( $key, $value ) {
315
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
316
317
		$value = maybe_serialize( $value );
318
319
		$data = array(
320
			'option_name'  => $key,
321
			'option_value' => $value,
322
			'autoload'     => 'no',
323
		);
324
325
		$formats = array(
326
			'%s',
327
			'%s',
328
			'%s',
329
		);
330
331
		$wpdb->replace( $wpdb->options, $data, $formats );
332
	}
333
334
	/**
335
	 * Delete an option
336
	 *
337
	 * @since  1.5
338
	 *
339
	 * @param  string $key The option_name to delete
340
	 *
341
	 * @return void
342
	 */
343
	private function delete_data( $key ) {
344
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
345
		$wpdb->delete( $wpdb->options, array( 'option_name' => $key ) );
346
	}
347
348
}
349