Passed
Push — master ( 9e37cd...7382ee )
by Brian
09:54
created

GetPaid_Installer::upgrade_from_207()   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
 * Contains the main installer class.
4
 *
5
 * @package GetPaid
6
 * @subpackage Admin
7
 * @version 2.0.2
8
 * @since   2.0.2
9
 */
10
11
defined( 'ABSPATH' ) || exit;
12
13
/**
14
 * The main installer/updater class.
15
 *
16
 * @package GetPaid
17
 * @subpackage Admin
18
 * @version 2.0.2
19
 * @since   2.0.2
20
 */
21
class GetPaid_Installer {
22
23
	/**
24
	 * Upgrades the install.
25
	 *
26
	 * @param string $upgrade_from The current invoicing version.
27
	 */
28
	public function upgrade_db( $upgrade_from ) {
29
30
		// Save the current invoicing version.
31
		update_option( 'wpinv_version', WPINV_VERSION );
32
33
		// Setup the invoice Custom Post Type.
34
		GetPaid_Post_Types::register_post_types();
35
36
		// Clear the permalinks
37
		flush_rewrite_rules();
38
39
		// Maybe create new/missing pages.
40
		$this->create_pages();
41
42
		// Maybe re(add) admin capabilities.
43
		$this->add_capabilities();
44
45
		// Maybe create the default payment form.
46
		wpinv_get_default_payment_form();
47
48
		// Create any missing database tables.
49
		$method = "upgrade_from_$upgrade_from";
50
51
		if ( method_exists( $this, $method ) ) {
52
			$this->$method();
53
		}
54
55
	}
56
57
	/**
58
	 * Do a fresh install.
59
	 *
60
	 */
61
	public function upgrade_from_0() {
62
		$this->create_subscriptions_table();
63
		$this->create_invoices_table();
64
		$this->create_invoice_items_table();
65
66
		// Save default tax rates.
67
		update_option( 'wpinv_tax_rates', wpinv_get_data( 'tax-rates' ) );
68
	}
69
70
	/**
71
	 * Upgrade to 0.0.5
72
	 *
73
	 */
74
	public function upgrade_from_004() {
75
		global $wpdb;
76
77
		// Invoices.
78
		$results = $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'wpi_invoice' AND post_status IN( 'pending', 'processing', 'onhold', 'refunded', 'cancelled', 'failed', 'renewal' )" );
79
		if ( ! empty( $results ) ) {
80
			$wpdb->query( "UPDATE {$wpdb->posts} SET post_status = CONCAT( 'wpi-', post_status ) WHERE post_type = 'wpi_invoice' AND post_status IN( 'pending', 'processing', 'onhold', 'refunded', 'cancelled', 'failed', 'renewal' )" );
81
82
			// Clean post cache
83
			foreach ( $results as $row ) {
84
				clean_post_cache( $row->ID );
85
			}
86
87
		}
88
89
		// Item meta key changes
90
		$query = "SELECT DISTINCT post_id FROM " . $wpdb->postmeta . " WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id', '_wpinv_cpt_name', '_wpinv_cpt_singular_name' )";
91
		$results = $wpdb->get_results( $query );
92
93
		if ( ! empty( $results ) ) {
94
			$wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_id' WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id' )" );
95
			$wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_name' WHERE meta_key = '_wpinv_cpt_name'" );
96
			$wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_singular_name' WHERE meta_key = '_wpinv_cpt_singular_name'" );
97
98
			foreach ( $results as $row ) {
99
				clean_post_cache( $row->post_id );
100
			}
101
102
		}
103
104
		$this->upgrade_from_102();
105
	}
106
107
	/**
108
	 * Upgrade to 1.0.3
109
	 *
110
	 */
111
	public function upgrade_from_102() {
112
		$this->create_subscriptions_table();
113
		$this->upgrade_from_118();
114
	}
115
116
	/**
117
	 * Upgrade to version 2.0.0.
118
	 *
119
	 */
120
	public function upgrade_from_118() {
121
		$this->create_invoices_table();
122
		$this->create_invoice_items_table();
123
		$this->migrate_old_invoices();
124
	}
125
126
	/**
127
	 * Upgrade to version 2.0.8.
128
	 *
129
	 */
130
	public function upgrade_from_207() {
131
		global $wpdb;
132
		$wpdb->query( "ALTER TABLE {$wpdb->prefix}getpaid_invoice_items MODIFY COLUMN quantity FLOAT(20);" );
133
	}
134
135
	/**
136
	 * Give administrators the capability to manage GetPaid.
137
	 *
138
	 */
139
	public function add_capabilities() {
140
		$GLOBALS['wp_roles']->add_cap( 'administrator', 'manage_invoicing' );
141
	}
142
143
	/**
144
	 * Retreives GetPaid pages.
145
	 *
146
	 */
147
	public static function get_pages() {
148
149
		return apply_filters(
150
			'wpinv_create_pages',
151
			array(
152
153
				// Checkout page.
154
				'checkout_page' => array(
155
					'name'      => _x( 'gp-checkout', 'Page slug', 'invoicing' ),
156
					'title'     => _x( 'Checkout', 'Page title', 'invoicing' ),
157
					'content'   => '
158
						<!-- wp:shortcode -->
159
						[wpinv_checkout]
160
						<!-- /wp:shortcode -->
161
					',
162
					'parent'    => '',
163
				),
164
165
				// Invoice history page.
166
				'invoice_history_page' => array(
167
					'name'    => _x( 'gp-invoices', 'Page slug', 'invoicing' ),
168
					'title'   => _x( 'My Invoices', 'Page title', 'invoicing' ),
169
					'content' => '
170
					<!-- wp:shortcode -->
171
					[wpinv_history]
172
					<!-- /wp:shortcode -->
173
				',
174
					'parent'  => '',
175
				),
176
177
				// Success page content.
178
				'success_page' => array(
179
					'name'     => _x( 'gp-receipt', 'Page slug', 'invoicing' ),
180
					'title'    => _x( 'Payment Confirmation', 'Page title', 'invoicing' ),
181
					'content'  => '
182
					<!-- wp:shortcode -->
183
					[wpinv_receipt]
184
					<!-- /wp:shortcode -->
185
				',
186
					'parent'   => 'gp-checkout',
187
				),
188
189
				// Failure page content.
190
				'failure_page' => array(
191
					'name'    => _x( 'gp-transaction-failed', 'Page slug', 'invoicing' ),
192
					'title'   => _x( 'Transaction Failed', 'Page title', 'invoicing' ),
193
					'content' => __( 'Your transaction failed, please try again or contact site support.', 'invoicing' ),
194
					'parent'  => 'gp-checkout',
195
				),
196
197
				// Subscriptions history page.
198
				'invoice_subscription_page' => array(
199
					'name'    => _x( 'gp-subscriptions', 'Page slug', 'invoicing' ),
200
					'title'   => _x( 'My Subscriptions', 'Page title', 'invoicing' ),
201
					'content' => '
202
					<!-- wp:shortcode -->
203
					[wpinv_subscriptions]
204
					<!-- /wp:shortcode -->
205
				',
206
					'parent' => '',
207
				),
208
209
			)
210
		);
211
212
	}
213
214
	/**
215
	 * Re-create GetPaid pages.
216
	 *
217
	 */
218
	public function create_pages() {
219
220
		foreach ( self::get_pages() as $key => $page ) {
221
			wpinv_create_page( esc_sql( $page['name'] ), $key, $page['title'], $page['content'], $page['parent'] );
222
		}
223
224
	}
225
226
	/**
227
	 * Create subscriptions table.
228
	 *
229
	 */
230
	public function create_subscriptions_table() {
231
232
		global $wpdb;
233
234
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
235
236
		// Create tables.
237
		$charset_collate = $wpdb->get_charset_collate();
238
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wpinv_subscriptions (
239
			id bigint(20) unsigned NOT NULL auto_increment,
240
			customer_id bigint(20) NOT NULL,
241
			frequency int(11) NOT NULL DEFAULT '1',
242
			period varchar(20) NOT NULL,
243
			initial_amount mediumtext NOT NULL,
244
			recurring_amount mediumtext NOT NULL,
245
			bill_times bigint(20) NOT NULL,
246
			transaction_id varchar(60) NOT NULL,
247
			parent_payment_id bigint(20) NOT NULL,
248
			product_id bigint(20) NOT NULL,
249
			created datetime NOT NULL,
250
			expiration datetime NOT NULL,
251
			trial_period varchar(20) NOT NULL,
252
			profile_id varchar(60) NOT NULL,
253
			status varchar(20) NOT NULL,
254
			PRIMARY KEY  (id),
255
			KEY profile_id (profile_id),
256
			KEY customer (customer_id),
257
			KEY transaction (transaction_id),
258
			KEY customer_and_status (customer_id, status)
259
		  ) $charset_collate;";
260
261
		dbDelta( $sql );
262
263
	}
264
265
	/**
266
	 * Create invoices table.
267
	 *
268
	 */
269
	public function create_invoices_table() {
270
		global $wpdb;
271
272
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
273
274
		// Create tables.
275
		$charset_collate = $wpdb->get_charset_collate();
276
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}getpaid_invoices (
277
			post_id BIGINT(20) NOT NULL,
278
            `number` VARCHAR(100),
279
            `key` VARCHAR(100),
280
            `type` VARCHAR(100) NOT NULL DEFAULT 'invoice',
281
            mode VARCHAR(100) NOT NULL DEFAULT 'live',
282
            user_ip VARCHAR(100),
283
            first_name VARCHAR(100),
284
            last_name VARCHAR(100),
285
            `address` VARCHAR(100),
286
            city VARCHAR(100),
287
            `state` VARCHAR(100),
288
            country VARCHAR(100),
289
            zip VARCHAR(100),
290
            adddress_confirmed INT(10),
291
            gateway VARCHAR(100),
292
            transaction_id VARCHAR(100),
293
            currency VARCHAR(10),
294
            subtotal FLOAT NOT NULL DEFAULT 0,
295
            tax FLOAT NOT NULL DEFAULT 0,
296
            fees_total FLOAT NOT NULL DEFAULT 0,
297
            total FLOAT NOT NULL DEFAULT 0,
298
            discount FLOAT NOT NULL DEFAULT 0,
299
            discount_code VARCHAR(100),
300
            disable_taxes INT(2) NOT NULL DEFAULT 0,
301
            due_date DATETIME,
302
            completed_date DATETIME,
303
            company VARCHAR(100),
304
            vat_number VARCHAR(100),
305
            vat_rate VARCHAR(100),
306
            custom_meta TEXT,
307
			PRIMARY KEY  (post_id),
308
			KEY number (number),
309
			KEY `key` (`key`)
310
		  ) $charset_collate;";
311
312
		dbDelta( $sql );
313
314
	}
315
316
	/**
317
	 * Create invoice items table.
318
	 *
319
	 */
320
	public function create_invoice_items_table() {
321
		global $wpdb;
322
323
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
324
325
		// Create tables.
326
		$charset_collate = $wpdb->get_charset_collate();
327
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}getpaid_invoice_items (
328
			ID BIGINT(20) NOT NULL AUTO_INCREMENT,
329
            post_id BIGINT(20) NOT NULL,
330
            item_id BIGINT(20) NOT NULL,
331
            item_name TEXT NOT NULL,
332
            item_description TEXT NOT NULL,
333
            vat_rate FLOAT NOT NULL DEFAULT 0,
334
            vat_class VARCHAR(100),
335
            tax FLOAT NOT NULL DEFAULT 0,
336
            item_price FLOAT NOT NULL DEFAULT 0,
337
            custom_price FLOAT NOT NULL DEFAULT 0,
338
            quantity FLOAT NOT NULL DEFAULT 1,
339
            discount FLOAT NOT NULL DEFAULT 0,
340
            subtotal FLOAT NOT NULL DEFAULT 0,
341
            price FLOAT NOT NULL DEFAULT 0,
342
            meta TEXT,
343
            fees TEXT,
344
			PRIMARY KEY  (ID),
345
			KEY item_id (item_id),
346
			KEY post_id (post_id)
347
		  ) $charset_collate;";
348
349
		dbDelta( $sql );
350
351
	}
352
353
	/**
354
	 * Migrates old invoices to new invoices.
355
	 *
356
	 */
357
	public function migrate_old_invoices() {
358
		global $wpdb;
359
360
		$invoices_table      = $wpdb->prefix . 'getpaid_invoices';
361
		$invoice_items_table = $wpdb->prefix . 'getpaid_invoice_items';
362
		$migrated            = $wpdb->get_col( "SELECT post_id FROM $invoices_table" );
363
		$invoices            = array_unique(
364
			get_posts(
365
				array(
366
					'post_type'      => array( 'wpi_invoice', 'wpi_quote' ),
367
					'posts_per_page' => -1,
368
					'fields'         => 'ids',
369
					'post_status'    => array_keys( get_post_stati() ),
370
					'exclude'        => (array) $migrated,
371
				)
372
			)
373
		);
374
375
		// Abort if we do not have any invoices.
376
		if ( empty( $invoices ) ) {
377
			return;
378
		}
379
380
		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-legacy-invoice.php' );
381
382
		$invoice_rows = array();
383
		foreach ( $invoices as $invoice ) {
384
385
			$invoice = new WPInv_Legacy_Invoice( $invoice );
386
387
			if ( empty( $invoice->ID ) ) {
388
				return;
389
			}
390
391
			$fields = array (
392
				'post_id'        => $invoice->ID,
393
				'number'         => $invoice->get_number(),
394
				'key'            => $invoice->get_key(),
395
				'type'           => str_replace( 'wpi_', '', $invoice->post_type ),
396
				'mode'           => $invoice->mode,
397
				'user_ip'        => $invoice->get_ip(),
398
				'first_name'     => $invoice->get_first_name(),
399
				'last_name'      => $invoice->get_last_name(),
400
				'address'        => $invoice->get_address(),
401
				'city'           => $invoice->city,
402
				'state'          => $invoice->state,
403
				'country'        => $invoice->country,
404
				'zip'            => $invoice->zip,
405
				'adddress_confirmed' => (int) $invoice->adddress_confirmed,
406
				'gateway'        => $invoice->get_gateway(),
407
				'transaction_id' => $invoice->get_transaction_id(),
408
				'currency'       => $invoice->get_currency(),
409
				'subtotal'       => $invoice->get_subtotal(),
410
				'tax'            => $invoice->get_tax(),
411
				'fees_total'     => $invoice->get_fees_total(),
412
				'total'          => $invoice->get_total(),
413
				'discount'       => $invoice->get_discount(),
414
				'discount_code'  => $invoice->get_discount_code(),
415
				'disable_taxes'  => $invoice->disable_taxes,
416
				'due_date'       => $invoice->get_due_date(),
417
				'completed_date' => $invoice->get_completed_date(),
418
				'company'        => $invoice->company,
419
				'vat_number'     => $invoice->vat_number,
420
				'vat_rate'       => $invoice->vat_rate,
421
				'custom_meta'    => $invoice->payment_meta
422
			);
423
424
			foreach ( $fields as $key => $val ) {
425
				if ( is_null( $val ) ) {
426
					$val = '';
427
				}
428
				$val = maybe_serialize( $val );
429
				$fields[ $key ] = $wpdb->prepare( '%s', $val );
430
			}
431
432
			$fields = implode( ', ', $fields );
433
			$invoice_rows[] = "($fields)";
434
435
			$item_rows    = array();
436
			$item_columns = array();
437
			foreach ( $invoice->get_cart_details() as $details ) {
438
				$fields = array(
439
					'post_id'          => $invoice->ID,
440
					'item_id'          => $details['id'],
441
					'item_name'        => $details['name'],
442
					'item_description' => empty( $details['meta']['description'] ) ? '' : $details['meta']['description'],
443
					'vat_rate'         => $details['vat_rate'],
444
					'vat_class'        => empty( $details['vat_class'] ) ? '_standard' : $details['vat_class'],
445
					'tax'              => $details['tax'],
446
					'item_price'       => $details['item_price'],
447
					'custom_price'     => $details['custom_price'],
448
					'quantity'         => $details['quantity'],
449
					'discount'         => $details['discount'],
450
					'subtotal'         => $details['subtotal'],
451
					'price'            => $details['price'],
452
					'meta'             => $details['meta'],
453
					'fees'             => $details['fees'],
454
				);
455
456
				$item_columns = array_keys ( $fields );
457
458
				foreach ( $fields as $key => $val ) {
459
					if ( is_null( $val ) ) {
460
						$val = '';
461
					}
462
					$val = maybe_serialize( $val );
463
					$fields[ $key ] = $wpdb->prepare( '%s', $val );
464
				}
465
466
				$fields = implode( ', ', $fields );
467
				$item_rows[] = "($fields)";
468
			}
469
470
			$item_rows    = implode( ', ', $item_rows );
471
			$item_columns = implode( ', ', $item_columns );
472
			$wpdb->query( "INSERT INTO $invoice_items_table ($item_columns) VALUES $item_rows" );
473
		}
474
475
		if ( empty( $invoice_rows ) ) {
476
			return;
477
		}
478
479
		$invoice_rows = implode( ', ', $invoice_rows );
480
		$wpdb->query( "INSERT INTO $invoices_table VALUES $invoice_rows" );
481
482
	}
483
484
	/**
485
	 * Migrates old invoices to new invoices.
486
	 *
487
	 */
488
	public static function rename_gateways_label() {
489
		global $wpdb;
490
491
		foreach ( array_keys( wpinv_get_payment_gateways() ) as $gateway ) {
492
493
			$wpdb->update(
494
				$wpdb->prefix . 'getpaid_invoices',
495
				array( 'gateway' => $gateway ),
496
				array( 'gateway' => wpinv_get_gateway_admin_label( $gateway ) ),
497
				'%s',
498
				'%s'
499
			);
500
501
		}
502
	}
503
504
}
505