Passed
Push — master ( dafa5d...51f1c0 )
by Brian
05:09
created

GetPaid_Installer::add_capabilities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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