Passed
Push — master ( 5faead...57234e )
by Brian
04:33
created

GetPaid_Installer::rename_gateways_label()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 0
dl 0
loc 11
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
	 * Re-create GetPaid pages.
145
	 *
146
	 */
147
	public function create_pages() {
148
149
		$pages = 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
		foreach ( $pages as $key => $page ) {
213
			wpinv_create_page( esc_sql( $page['name'] ), $key, $page['title'], $page['content'], $page['parent'] );
214
		}
215
216
	}
217
218
	/**
219
	 * Create subscriptions table.
220
	 *
221
	 */
222
	public function create_subscriptions_table() {
223
224
		global $wpdb;
225
226
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
227
228
		// Create tables.
229
		$charset_collate = $wpdb->get_charset_collate();
230
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wpinv_subscriptions (
231
			id bigint(20) unsigned NOT NULL auto_increment,
232
			customer_id bigint(20) NOT NULL,
233
			frequency int(11) NOT NULL DEFAULT '1',
234
			period varchar(20) NOT NULL,
235
			initial_amount mediumtext NOT NULL,
236
			recurring_amount mediumtext NOT NULL,
237
			bill_times bigint(20) NOT NULL,
238
			transaction_id varchar(60) NOT NULL,
239
			parent_payment_id bigint(20) NOT NULL,
240
			product_id bigint(20) NOT NULL,
241
			created datetime NOT NULL,
242
			expiration datetime NOT NULL,
243
			trial_period varchar(20) NOT NULL,
244
			profile_id varchar(60) NOT NULL,
245
			status varchar(20) NOT NULL,
246
			PRIMARY KEY  (id),
247
			KEY profile_id (profile_id),
248
			KEY customer (customer_id),
249
			KEY transaction (transaction_id),
250
			KEY customer_and_status (customer_id, status)
251
		  ) $charset_collate;";
252
253
		dbDelta( $sql );
254
255
	}
256
257
	/**
258
	 * Create invoices table.
259
	 *
260
	 */
261
	public function create_invoices_table() {
262
		global $wpdb;
263
264
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
265
266
		// Create tables.
267
		$charset_collate = $wpdb->get_charset_collate();
268
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}getpaid_invoices (
269
			post_id BIGINT(20) NOT NULL,
270
            `number` VARCHAR(100),
271
            `key` VARCHAR(100),
272
            `type` VARCHAR(100) NOT NULL DEFAULT 'invoice',
273
            mode VARCHAR(100) NOT NULL DEFAULT 'live',
274
            user_ip VARCHAR(100),
275
            first_name VARCHAR(100),
276
            last_name VARCHAR(100),
277
            `address` VARCHAR(100),
278
            city VARCHAR(100),
279
            `state` VARCHAR(100),
280
            country VARCHAR(100),
281
            zip VARCHAR(100),
282
            adddress_confirmed INT(10),
283
            gateway VARCHAR(100),
284
            transaction_id VARCHAR(100),
285
            currency VARCHAR(10),
286
            subtotal FLOAT NOT NULL DEFAULT 0,
287
            tax FLOAT NOT NULL DEFAULT 0,
288
            fees_total FLOAT NOT NULL DEFAULT 0,
289
            total FLOAT NOT NULL DEFAULT 0,
290
            discount FLOAT NOT NULL DEFAULT 0,
291
            discount_code VARCHAR(100),
292
            disable_taxes INT(2) NOT NULL DEFAULT 0,
293
            due_date DATETIME,
294
            completed_date DATETIME,
295
            company VARCHAR(100),
296
            vat_number VARCHAR(100),
297
            vat_rate VARCHAR(100),
298
            custom_meta TEXT,
299
			PRIMARY KEY  (post_id),
300
			KEY number (number),
301
			KEY `key` (`key`)
302
		  ) $charset_collate;";
303
304
		dbDelta( $sql );
305
306
	}
307
308
	/**
309
	 * Create invoice items table.
310
	 *
311
	 */
312
	public function create_invoice_items_table() {
313
		global $wpdb;
314
315
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
316
317
		// Create tables.
318
		$charset_collate = $wpdb->get_charset_collate();
319
		$sql             = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}getpaid_invoice_items (
320
			ID BIGINT(20) NOT NULL AUTO_INCREMENT,
321
            post_id BIGINT(20) NOT NULL,
322
            item_id BIGINT(20) NOT NULL,
323
            item_name TEXT NOT NULL,
324
            item_description TEXT NOT NULL,
325
            vat_rate FLOAT NOT NULL DEFAULT 0,
326
            vat_class VARCHAR(100),
327
            tax FLOAT NOT NULL DEFAULT 0,
328
            item_price FLOAT NOT NULL DEFAULT 0,
329
            custom_price FLOAT NOT NULL DEFAULT 0,
330
            quantity FLOAT NOT NULL DEFAULT 1,
331
            discount FLOAT NOT NULL DEFAULT 0,
332
            subtotal FLOAT NOT NULL DEFAULT 0,
333
            price FLOAT NOT NULL DEFAULT 0,
334
            meta TEXT,
335
            fees TEXT,
336
			PRIMARY KEY  (ID),
337
			KEY item_id (item_id),
338
			KEY post_id (post_id)
339
		  ) $charset_collate;";
340
341
		dbDelta( $sql );
342
343
	}
344
345
	/**
346
	 * Migrates old invoices to new invoices.
347
	 *
348
	 */
349
	public function migrate_old_invoices() {
350
		global $wpdb;
351
352
		$invoices_table      = $wpdb->prefix . 'getpaid_invoices';
353
		$invoice_items_table = $wpdb->prefix . 'getpaid_invoice_items';
354
		$migrated            = $wpdb->get_col( "SELECT post_id FROM $invoices_table" );
355
		$invoices            = array_unique(
356
			get_posts(
357
				array(
358
					'post_type'      => array( 'wpi_invoice', 'wpi_quote' ),
359
					'posts_per_page' => -1,
360
					'fields'         => 'ids',
361
					'post_status'    => array_keys( get_post_stati() ),
362
					'exclude'        => (array) $migrated,
363
				)
364
			)
365
		);
366
367
		// Abort if we do not have any invoices.
368
		if ( empty( $invoices ) ) {
369
			return;
370
		}
371
372
		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-legacy-invoice.php' );
373
374
		$invoice_rows = array();
375
		foreach ( $invoices as $invoice ) {
376
377
			$invoice = new WPInv_Legacy_Invoice( $invoice );
378
379
			if ( empty( $invoice->ID ) ) {
380
				return;
381
			}
382
383
			$fields = array (
384
				'post_id'        => $invoice->ID,
385
				'number'         => $invoice->get_number(),
386
				'key'            => $invoice->get_key(),
387
				'type'           => str_replace( 'wpi_', '', $invoice->post_type ),
388
				'mode'           => $invoice->mode,
389
				'user_ip'        => $invoice->get_ip(),
390
				'first_name'     => $invoice->get_first_name(),
391
				'last_name'      => $invoice->get_last_name(),
392
				'address'        => $invoice->get_address(),
393
				'city'           => $invoice->city,
394
				'state'          => $invoice->state,
395
				'country'        => $invoice->country,
396
				'zip'            => $invoice->zip,
397
				'adddress_confirmed' => (int) $invoice->adddress_confirmed,
398
				'gateway'        => $invoice->get_gateway(),
399
				'transaction_id' => $invoice->get_transaction_id(),
400
				'currency'       => $invoice->get_currency(),
401
				'subtotal'       => $invoice->get_subtotal(),
402
				'tax'            => $invoice->get_tax(),
403
				'fees_total'     => $invoice->get_fees_total(),
404
				'total'          => $invoice->get_total(),
405
				'discount'       => $invoice->get_discount(),
406
				'discount_code'  => $invoice->get_discount_code(),
407
				'disable_taxes'  => $invoice->disable_taxes,
408
				'due_date'       => $invoice->get_due_date(),
409
				'completed_date' => $invoice->get_completed_date(),
410
				'company'        => $invoice->company,
411
				'vat_number'     => $invoice->vat_number,
412
				'vat_rate'       => $invoice->vat_rate,
413
				'custom_meta'    => $invoice->payment_meta
414
			);
415
416
			foreach ( $fields as $key => $val ) {
417
				if ( is_null( $val ) ) {
418
					$val = '';
419
				}
420
				$val = maybe_serialize( $val );
421
				$fields[ $key ] = $wpdb->prepare( '%s', $val );
422
			}
423
424
			$fields = implode( ', ', $fields );
425
			$invoice_rows[] = "($fields)";
426
427
			$item_rows    = array();
428
			$item_columns = array();
429
			foreach ( $invoice->get_cart_details() as $details ) {
430
				$fields = array(
431
					'post_id'          => $invoice->ID,
432
					'item_id'          => $details['id'],
433
					'item_name'        => $details['name'],
434
					'item_description' => empty( $details['meta']['description'] ) ? '' : $details['meta']['description'],
435
					'vat_rate'         => $details['vat_rate'],
436
					'vat_class'        => empty( $details['vat_class'] ) ? '_standard' : $details['vat_class'],
437
					'tax'              => $details['tax'],
438
					'item_price'       => $details['item_price'],
439
					'custom_price'     => $details['custom_price'],
440
					'quantity'         => $details['quantity'],
441
					'discount'         => $details['discount'],
442
					'subtotal'         => $details['subtotal'],
443
					'price'            => $details['price'],
444
					'meta'             => $details['meta'],
445
					'fees'             => $details['fees'],
446
				);
447
448
				$item_columns = array_keys ( $fields );
449
450
				foreach ( $fields as $key => $val ) {
451
					if ( is_null( $val ) ) {
452
						$val = '';
453
					}
454
					$val = maybe_serialize( $val );
455
					$fields[ $key ] = $wpdb->prepare( '%s', $val );
456
				}
457
458
				$fields = implode( ', ', $fields );
459
				$item_rows[] = "($fields)";
460
			}
461
462
			$item_rows    = implode( ', ', $item_rows );
463
			$item_columns = implode( ', ', $item_columns );
464
			$wpdb->query( "INSERT INTO $invoice_items_table ($item_columns) VALUES $item_rows" );
465
		}
466
467
		if ( empty( $invoice_rows ) ) {
468
			return;
469
		}
470
471
		$invoice_rows = implode( ', ', $invoice_rows );
472
		$wpdb->query( "INSERT INTO $invoices_table VALUES $invoice_rows" );
473
474
	}
475
476
	/**
477
	 * Migrates old invoices to new invoices.
478
	 *
479
	 */
480
	public static function rename_gateways_label() {
481
		global $wpdb;
482
483
		foreach ( array_keys( wpinv_get_payment_gateways() ) as $gateway ) {
484
485
			$wpdb->update(
486
				$wpdb->prefix . 'getpaid_invoices',
487
				array( 'gateway' => $gateway ),
488
				array( 'gateway' => wpinv_get_gateway_admin_label( $gateway ) ),
489
				'%s',
490
				'%s'
491
			);
492
493
		}
494
	}
495
496
}
497