Completed
Push — master ( bf7bd5...bd22db )
by Brian
17s queued 14s
created
includes/admin/subscriptions.php 3 patches
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -8,23 +8,23 @@  discard block
 block discarded – undo
8 8
  */
9 9
 function wpinv_subscriptions_page() {
10 10
 
11
-	if ( ! empty( $_GET['id'] ) ) {
11
+    if ( ! empty( $_GET['id'] ) ) {
12 12
 
13 13
         wpinv_recurring_subscription_details();
14 14
 
15
-		return;
15
+        return;
16 16
 
17
-	}
18
-	?>
17
+    }
18
+    ?>
19 19
 	<div class="wrap">
20 20
 
21 21
 		<h1>
22 22
 			<?php _e( 'Subscriptions', 'invoicing' ); ?>
23 23
 		</h1>
24 24
 		<?php
25
-		$subscribers_table = new WPInv_Subscription_Reports_Table();
26
-		$subscribers_table->prepare_items();
27
-		?>
25
+        $subscribers_table = new WPInv_Subscription_Reports_Table();
26
+        $subscribers_table->prepare_items();
27
+        ?>
28 28
 
29 29
 		<form id="subscribers-filter" method="get">
30 30
 
@@ -47,25 +47,25 @@  discard block
 block discarded – undo
47 47
  */
48 48
 function wpinv_recurring_subscription_details() {
49 49
 
50
-	$render = true;
50
+    $render = true;
51 51
 
52
-	if ( ! current_user_can( 'manage_invoicing' ) ) {
53
-		die( __( 'You are not permitted to view this data.', 'invoicing' ) );
54
-	}
52
+    if ( ! current_user_can( 'manage_invoicing' ) ) {
53
+        die( __( 'You are not permitted to view this data.', 'invoicing' ) );
54
+    }
55 55
 
56
-	if ( ! isset( $_GET['id'] ) || ! is_numeric( $_GET['id'] ) ) {
56
+    if ( ! isset( $_GET['id'] ) || ! is_numeric( $_GET['id'] ) ) {
57 57
         die( __( 'Invalid subscription ID Provided.', 'invoicing' ) );
58
-	}
58
+    }
59 59
 
60
-	$sub_id  = (int) $_GET['id'];
61
-	$sub     = new WPInv_Subscription( $sub_id );
62
-	$parent  = new WPInv_Invoice( $sub->parent_payment_id );
60
+    $sub_id  = (int) $_GET['id'];
61
+    $sub     = new WPInv_Subscription( $sub_id );
62
+    $parent  = new WPInv_Invoice( $sub->parent_payment_id );
63 63
 
64
-	if ( empty( $sub ) ) {
65
-		die( __( 'Invalid subscription ID Provided.', 'invoicing' ) );
66
-	}
64
+    if ( empty( $sub ) ) {
65
+        die( __( 'Invalid subscription ID Provided.', 'invoicing' ) );
66
+    }
67 67
 
68
-	?>
68
+    ?>
69 69
 	<div class="wrap">
70 70
 		<h2><?php _e( 'Subscription Details', 'invoicing' ); ?></h2>
71 71
 
@@ -89,11 +89,11 @@  discard block
 block discarded – undo
89 89
 										</td>
90 90
 										<td>
91 91
 											<?php
92
-											$frequency = WPInv_Subscriptions::wpinv_get_pretty_subscription_frequency( $sub->period, $sub->frequency );
93
-											$billing   = wpinv_price( wpinv_format_amount( $sub->recurring_amount ), $parent->get_currency() ) . ' / ' . $frequency;
94
-											$initial   = wpinv_price( wpinv_format_amount( $sub->initial_amount ), $parent->get_currency() );
95
-											printf( _x( '%s then %s', 'Initial subscription amount then billing cycle and amount', 'invoicing' ), $initial, $billing );
96
-											?>
92
+                                            $frequency = WPInv_Subscriptions::wpinv_get_pretty_subscription_frequency( $sub->period, $sub->frequency );
93
+                                            $billing   = wpinv_price( wpinv_format_amount( $sub->recurring_amount ), $parent->get_currency() ) . ' / ' . $frequency;
94
+                                            $initial   = wpinv_price( wpinv_format_amount( $sub->initial_amount ), $parent->get_currency() );
95
+                                            printf( _x( '%s then %s', 'Initial subscription amount then billing cycle and amount', 'invoicing' ), $initial, $billing );
96
+                                            ?>
97 97
 										</td>
98 98
 									</tr>
99 99
 									<tr>
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 
136 136
                                             ?>
137 137
 											<a href="<?php echo esc_url( add_query_arg( array(
138
-													'post'   => $sub->product_id,
139
-													'action' => 'edit'
140
-												), admin_url( 'post.php' ) ) ); ?>" target="_blank"><?php _e( 'View Item', 'invoicing' ) ; ?></a>
138
+                                                    'post'   => $sub->product_id,
139
+                                                    'action' => 'edit'
140
+                                                ), admin_url( 'post.php' ) ) ); ?>" target="_blank"><?php _e( 'View Item', 'invoicing' ) ; ?></a>
141 141
 										</td>
142 142
 									</tr>
143 143
 									<tr>
@@ -300,56 +300,56 @@  discard block
 block discarded – undo
300 300
  */
301 301
 function wpinv_recurring_process_subscription_update() {
302 302
 
303
-	if( empty( $_POST['sub_id'] ) ) {
304
-		return;
305
-	}
303
+    if( empty( $_POST['sub_id'] ) ) {
304
+        return;
305
+    }
306 306
 
307
-	if( empty( $_POST['wpinv_update_subscription'] ) ) {
308
-		return;
309
-	}
307
+    if( empty( $_POST['wpinv_update_subscription'] ) ) {
308
+        return;
309
+    }
310 310
 
311
-	if( ! current_user_can( 'manage_invoicing') ) {
312
-		return;
313
-	}
311
+    if( ! current_user_can( 'manage_invoicing') ) {
312
+        return;
313
+    }
314 314
 
315
-	if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
316
-		wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
317
-	}
315
+    if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
316
+        wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
317
+    }
318 318
 
319
-	$profile_id      = sanitize_text_field( $_POST['profile_id'] );
320
-	$transaction_id  = sanitize_text_field( $_POST['transaction_id'] );
321
-	$product_id      = absint( $_POST['product_id'] );
322
-	$subscription    = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
323
-	$subscription->update( array(
324
-		'status'         => sanitize_text_field( $_POST['status'] ),
325
-		'profile_id'     => $profile_id,
326
-		'product_id'     => $product_id,
327
-		'transaction_id' => $transaction_id,
328
-	) );
319
+    $profile_id      = sanitize_text_field( $_POST['profile_id'] );
320
+    $transaction_id  = sanitize_text_field( $_POST['transaction_id'] );
321
+    $product_id      = absint( $_POST['product_id'] );
322
+    $subscription    = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
323
+    $subscription->update( array(
324
+        'status'         => sanitize_text_field( $_POST['status'] ),
325
+        'profile_id'     => $profile_id,
326
+        'product_id'     => $product_id,
327
+        'transaction_id' => $transaction_id,
328
+    ) );
329 329
 
330
-	$status = sanitize_text_field( $_POST['status'] );
330
+    $status = sanitize_text_field( $_POST['status'] );
331 331
 
332
-	switch( $status ) {
332
+    switch( $status ) {
333 333
 
334
-		case 'cancelled' :
334
+        case 'cancelled' :
335 335
 
336
-			$subscription->cancel();
337
-			break;
336
+            $subscription->cancel();
337
+            break;
338 338
 
339
-		case 'expired' :
339
+        case 'expired' :
340 340
 
341
-			$subscription->expire();
342
-			break;
341
+            $subscription->expire();
342
+            break;
343 343
 
344
-		case 'completed' :
344
+        case 'completed' :
345 345
 
346
-			$subscription->complete();
347
-			break;
346
+            $subscription->complete();
347
+            break;
348 348
 
349
-	}
349
+    }
350 350
 
351
-	wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=updated&id=' . $subscription->id ) );
352
-	exit;
351
+    wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=updated&id=' . $subscription->id ) );
352
+    exit;
353 353
 
354 354
 }
355 355
 add_action( 'admin_init', 'wpinv_recurring_process_subscription_update', 1 );
@@ -363,30 +363,30 @@  discard block
 block discarded – undo
363 363
  */
364 364
 function wpinv_recurring_process_subscription_deletion() {
365 365
 
366
-	if( empty( $_POST['sub_id'] ) ) {
367
-		return;
368
-	}
366
+    if( empty( $_POST['sub_id'] ) ) {
367
+        return;
368
+    }
369 369
 
370
-	if( empty( $_POST['wpinv_delete_subscription'] ) ) {
371
-		return;
372
-	}
370
+    if( empty( $_POST['wpinv_delete_subscription'] ) ) {
371
+        return;
372
+    }
373 373
 
374
-	if( ! current_user_can( 'manage_invoicing') ) {
375
-		return;
376
-	}
374
+    if( ! current_user_can( 'manage_invoicing') ) {
375
+        return;
376
+    }
377 377
 
378
-	if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
379
-		wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
380
-	}
378
+    if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
379
+        wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
380
+    }
381 381
 
382
-	$subscription = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
382
+    $subscription = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
383 383
 
384
-	delete_post_meta( $subscription->parent_payment_id, '_wpinv_subscription_payment' );
384
+    delete_post_meta( $subscription->parent_payment_id, '_wpinv_subscription_payment' );
385 385
 
386
-	$subscription->delete();
386
+    $subscription->delete();
387 387
 
388
-	wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=deleted' ) );
389
-	exit;
388
+    wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=deleted' ) );
389
+    exit;
390 390
 
391 391
 }
392 392
 add_action( 'admin_init', 'wpinv_recurring_process_subscription_deletion', 2 );
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  */
9 9
 function wpinv_subscriptions_page() {
10 10
 
11
-	if ( ! empty( $_GET['id'] ) ) {
11
+	if (!empty($_GET['id'])) {
12 12
 
13 13
         wpinv_recurring_subscription_details();
14 14
 
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 	<div class="wrap">
20 20
 
21 21
 		<h1>
22
-			<?php _e( 'Subscriptions', 'invoicing' ); ?>
22
+			<?php _e('Subscriptions', 'invoicing'); ?>
23 23
 		</h1>
24 24
 		<?php
25 25
 		$subscribers_table = new WPInv_Subscription_Reports_Table();
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 			<input type="hidden" name="post_type" value="download" />
32 32
 			<input type="hidden" name="page" value="wpinv-subscriptions" />
33 33
 			<?php $subscribers_table->views(); ?>
34
-			<?php $subscribers_table->search_box( __( 'Search', 'wpinvoicing' ), 'subscriptions' ); ?>
34
+			<?php $subscribers_table->search_box(__('Search', 'wpinvoicing'), 'subscriptions'); ?>
35 35
 			<?php $subscribers_table->display(); ?>
36 36
 
37 37
 		</form>
@@ -49,35 +49,35 @@  discard block
 block discarded – undo
49 49
 
50 50
 	$render = true;
51 51
 
52
-	if ( ! current_user_can( 'manage_invoicing' ) ) {
53
-		die( __( 'You are not permitted to view this data.', 'invoicing' ) );
52
+	if (!current_user_can('manage_invoicing')) {
53
+		die(__('You are not permitted to view this data.', 'invoicing'));
54 54
 	}
55 55
 
56
-	if ( ! isset( $_GET['id'] ) || ! is_numeric( $_GET['id'] ) ) {
57
-        die( __( 'Invalid subscription ID Provided.', 'invoicing' ) );
56
+	if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
57
+        die(__('Invalid subscription ID Provided.', 'invoicing'));
58 58
 	}
59 59
 
60 60
 	$sub_id  = (int) $_GET['id'];
61
-	$sub     = new WPInv_Subscription( $sub_id );
62
-	$parent  = new WPInv_Invoice( $sub->parent_payment_id );
61
+	$sub     = new WPInv_Subscription($sub_id);
62
+	$parent  = new WPInv_Invoice($sub->parent_payment_id);
63 63
 
64
-	if ( empty( $sub ) ) {
65
-		die( __( 'Invalid subscription ID Provided.', 'invoicing' ) );
64
+	if (empty($sub)) {
65
+		die(__('Invalid subscription ID Provided.', 'invoicing'));
66 66
 	}
67 67
 
68 68
 	?>
69 69
 	<div class="wrap">
70
-		<h2><?php _e( 'Subscription Details', 'invoicing' ); ?></h2>
70
+		<h2><?php _e('Subscription Details', 'invoicing'); ?></h2>
71 71
 
72
-		<?php if ( $sub ) : ?>
72
+		<?php if ($sub) : ?>
73 73
 
74 74
 			<div id="wpinv-item-card-wrapper">
75 75
 
76
-				<?php do_action( 'wpinv_subscription_card_top', $sub ); ?>
76
+				<?php do_action('wpinv_subscription_card_top', $sub); ?>
77 77
 
78 78
 				<div class="info-wrapper item-section">
79 79
 
80
-					<form id="edit-item-info" method="post" action="<?php echo admin_url( 'admin.php?page=wpinv-subscriptions&id=' . $sub->id ); ?>">
80
+					<form id="edit-item-info" method="post" action="<?php echo admin_url('admin.php?page=wpinv-subscriptions&id=' . $sub->id); ?>">
81 81
 
82 82
 						<div class="item-info">
83 83
 
@@ -85,124 +85,124 @@  discard block
 block discarded – undo
85 85
 								<tbody>
86 86
 									<tr>
87 87
 										<td class="row-title">
88
-											<label for="tablecell"><?php _e( 'Billing Cycle:', 'invoicing' ); ?></label>
88
+											<label for="tablecell"><?php _e('Billing Cycle:', 'invoicing'); ?></label>
89 89
 										</td>
90 90
 										<td>
91 91
 											<?php
92
-											$frequency = WPInv_Subscriptions::wpinv_get_pretty_subscription_frequency( $sub->period, $sub->frequency );
93
-											$billing   = wpinv_price( wpinv_format_amount( $sub->recurring_amount ), $parent->get_currency() ) . ' / ' . $frequency;
94
-											$initial   = wpinv_price( wpinv_format_amount( $sub->initial_amount ), $parent->get_currency() );
95
-											printf( _x( '%s then %s', 'Initial subscription amount then billing cycle and amount', 'invoicing' ), $initial, $billing );
92
+											$frequency = WPInv_Subscriptions::wpinv_get_pretty_subscription_frequency($sub->period, $sub->frequency);
93
+											$billing   = wpinv_price(wpinv_format_amount($sub->recurring_amount), $parent->get_currency()) . ' / ' . $frequency;
94
+											$initial   = wpinv_price(wpinv_format_amount($sub->initial_amount), $parent->get_currency());
95
+											printf(_x('%s then %s', 'Initial subscription amount then billing cycle and amount', 'invoicing'), $initial, $billing);
96 96
 											?>
97 97
 										</td>
98 98
 									</tr>
99 99
 									<tr>
100 100
 										<td class="row-title">
101
-											<label for="tablecell"><?php _e( 'Times Billed:', 'invoicing' ); ?></label>
101
+											<label for="tablecell"><?php _e('Times Billed:', 'invoicing'); ?></label>
102 102
 										</td>
103
-										<td><?php echo $sub->get_times_billed() . ' / ' . ( ( $sub->bill_times == 0 ) ? __( 'Until Cancelled', 'invoicing' ) : $sub->bill_times ); ?></td>
103
+										<td><?php echo $sub->get_times_billed() . ' / ' . (($sub->bill_times == 0) ? __('Until Cancelled', 'invoicing') : $sub->bill_times); ?></td>
104 104
 									</tr>
105 105
 									<tr>
106 106
 										<td class="row-title">
107
-											<label for="tablecell"><?php _e( 'Customer:', 'invoicing' ); ?></label>
107
+											<label for="tablecell"><?php _e('Customer:', 'invoicing'); ?></label>
108 108
 										</td>
109 109
 										<td>
110
-											<?php $subscriber = get_userdata( $sub->customer_id ); ?>
111
-											<a href="<?php echo esc_url( get_edit_user_link( $sub->customer_id ) ); ?>" target="_blank"><?php echo ! empty( $subscriber->display_name ) ? $subscriber->display_name : $subscriber->user_email; ?></a>
110
+											<?php $subscriber = get_userdata($sub->customer_id); ?>
111
+											<a href="<?php echo esc_url(get_edit_user_link($sub->customer_id)); ?>" target="_blank"><?php echo !empty($subscriber->display_name) ? $subscriber->display_name : $subscriber->user_email; ?></a>
112 112
 										</td>
113 113
 									</tr>
114 114
 									<tr>
115 115
 										<td class="row-title">
116
-											<label for="tablecell"><?php _e( 'Initial Invoice:', 'invoicing' ); ?></label>
116
+											<label for="tablecell"><?php _e('Initial Invoice:', 'invoicing'); ?></label>
117 117
 										</td>
118 118
 										<td>
119
-                                            <a target="_blank" title="<?php _e( 'View invoice', 'invoicing' ); ?>" href="<?php echo esc_url( get_permalink( $sub->parent_payment_id ) ); ?>"><?php echo wpinv_clean( $parent->get_number() ); ?></a>&nbsp;&nbsp;&nbsp;<?php echo wp_sprintf( __( '( ID: %s )', 'invoicing' ), '<a title="' . esc_attr( __( 'View invoice details', 'invoicing' ) ) . '" href="' . esc_html( get_edit_post_link( $sub->parent_payment_id ) ) . '" target="_blank">' . wpinv_clean( $sub->parent_payment_id ) . '</a>' ); ?></td>
119
+                                            <a target="_blank" title="<?php _e('View invoice', 'invoicing'); ?>" href="<?php echo esc_url(get_permalink($sub->parent_payment_id)); ?>"><?php echo wpinv_clean($parent->get_number()); ?></a>&nbsp;&nbsp;&nbsp;<?php echo wp_sprintf(__('( ID: %s )', 'invoicing'), '<a title="' . esc_attr(__('View invoice details', 'invoicing')) . '" href="' . esc_html(get_edit_post_link($sub->parent_payment_id)) . '" target="_blank">' . wpinv_clean($sub->parent_payment_id) . '</a>'); ?></td>
120 120
 									</tr>
121 121
 									<tr>
122 122
 										<td class="row-title">
123
-											<label for="tablecell"><?php _e( 'Item:', 'invoicing' ); ?></label>
123
+											<label for="tablecell"><?php _e('Item:', 'invoicing'); ?></label>
124 124
 										</td>
125 125
 										<td>
126 126
 											<?php
127
-                                            echo wpinv_item_dropdown( array(
127
+                                            echo wpinv_item_dropdown(array(
128 128
                                                 'name'              => 'product_id',
129 129
                                                 'id'                => 'wpinv_invoice_item',
130 130
                                                 'with_packages'     => false,
131 131
                                                 'show_recurring'    => true,
132 132
                                                 'selected'          => $sub->product_id,
133 133
                                                 'class'             => 'wpinv-sub-product-id wpi_select2',
134
-                                            ) );
134
+                                            ));
135 135
 
136 136
                                             ?>
137
-											<a href="<?php echo esc_url( add_query_arg( array(
137
+											<a href="<?php echo esc_url(add_query_arg(array(
138 138
 													'post'   => $sub->product_id,
139 139
 													'action' => 'edit'
140
-												), admin_url( 'post.php' ) ) ); ?>" target="_blank"><?php _e( 'View Item', 'invoicing' ) ; ?></a>
140
+												), admin_url('post.php'))); ?>" target="_blank"><?php _e('View Item', 'invoicing'); ?></a>
141 141
 										</td>
142 142
 									</tr>
143 143
 									<tr>
144 144
 										<td class="row-title">
145
-											<label for="tablecell"><?php _e( 'Payment Method:', 'invoicing' ); ?></label>
145
+											<label for="tablecell"><?php _e('Payment Method:', 'invoicing'); ?></label>
146 146
 										</td>
147
-										<td><?php echo wpinv_get_gateway_admin_label( $parent->get_gateway() ); ?></td>
147
+										<td><?php echo wpinv_get_gateway_admin_label($parent->get_gateway()); ?></td>
148 148
 									</tr>
149 149
 									<tr>
150 150
 										<td class="row-title">
151
-											<label for="tablecell"><?php _e( 'Profile ID:', 'invoicing' ); ?></label>
151
+											<label for="tablecell"><?php _e('Profile ID:', 'invoicing'); ?></label>
152 152
 										</td>
153 153
 										<td>
154 154
 											<span class="wpinv-sub-profile-id">
155
-												<?php echo apply_filters( 'wpinv_subscription_profile_link_' . $sub->gateway, $sub->profile_id, $sub ); ?>
155
+												<?php echo apply_filters('wpinv_subscription_profile_link_' . $sub->gateway, $sub->profile_id, $sub); ?>
156 156
 											</span>
157
-											<input type="text" name="profile_id" class="hidden wpinv-sub-profile-id" value="<?php echo esc_attr( $sub->profile_id ); ?>" />
157
+											<input type="text" name="profile_id" class="hidden wpinv-sub-profile-id" value="<?php echo esc_attr($sub->profile_id); ?>" />
158 158
 											<span>&nbsp;&ndash;&nbsp;</span>
159
-											<a href="#" class="wpinv-edit-sub-profile-id"><?php _e( 'Edit', 'invoicing' ); ?></a>
159
+											<a href="#" class="wpinv-edit-sub-profile-id"><?php _e('Edit', 'invoicing'); ?></a>
160 160
 										</td>
161 161
 									</tr>
162 162
 									<tr>
163 163
 										<td class="row-title">
164
-											<label for="tablecell"><?php _e( 'Transaction ID:', 'invoicing' ); ?></label>
164
+											<label for="tablecell"><?php _e('Transaction ID:', 'invoicing'); ?></label>
165 165
 										</td>
166 166
 										<td>
167
-											<span class="wpinv-sub-transaction-id"><?php echo apply_filters( 'wpinv_subscription_transaction_link_' . $sub->gateway, $sub->get_transaction_id(), $sub ); ?></span>
168
-											<input type="text" name="transaction_id" class="hidden wpinv-sub-transaction-id" value="<?php echo esc_attr( $sub->get_transaction_id() ); ?>" />
167
+											<span class="wpinv-sub-transaction-id"><?php echo apply_filters('wpinv_subscription_transaction_link_' . $sub->gateway, $sub->get_transaction_id(), $sub); ?></span>
168
+											<input type="text" name="transaction_id" class="hidden wpinv-sub-transaction-id" value="<?php echo esc_attr($sub->get_transaction_id()); ?>" />
169 169
 											<span>&nbsp;&ndash;&nbsp;</span>
170
-											<a href="#" class="wpinv-edit-sub-transaction-id"><?php _e( 'Edit', 'invoicing' ); ?></a>
170
+											<a href="#" class="wpinv-edit-sub-transaction-id"><?php _e('Edit', 'invoicing'); ?></a>
171 171
 										</td>
172 172
 									</tr>
173 173
 									<tr>
174 174
 										<td class="row-title">
175
-											<label for="tablecell"><?php _e( 'Date Created:', 'invoicing' ); ?></label>
175
+											<label for="tablecell"><?php _e('Date Created:', 'invoicing'); ?></label>
176 176
 										</td>
177
-										<td><?php echo date_i18n( get_option( 'date_format' ), strtotime( $sub->created, current_time( 'timestamp' ) ) ); ?></td>
177
+										<td><?php echo date_i18n(get_option('date_format'), strtotime($sub->created, current_time('timestamp'))); ?></td>
178 178
 									</tr>
179 179
 									<tr>
180 180
 										<td class="row-title">
181 181
 											<label for="tablecell">
182
-												<?php if( 'trialling' == $sub->status ) : ?>
183
-													<?php _e( 'Trialling Until:', 'invoicing' ); ?>
182
+												<?php if ('trialling' == $sub->status) : ?>
183
+													<?php _e('Trialling Until:', 'invoicing'); ?>
184 184
 												<?php else: ?>
185
-													<?php _e( 'Expiration Date:', 'invoicing' ); ?>
185
+													<?php _e('Expiration Date:', 'invoicing'); ?>
186 186
 												<?php endif; ?>
187 187
 											</label>
188 188
 										</td>
189 189
 										<td>
190
-											<span class="wpinv-sub-expiration"><?php echo date_i18n( get_option( 'date_format' ), strtotime( $sub->expiration, current_time( 'timestamp' ) ) ); ?></span>
190
+											<span class="wpinv-sub-expiration"><?php echo date_i18n(get_option('date_format'), strtotime($sub->expiration, current_time('timestamp'))); ?></span>
191 191
 										</td>
192 192
 									</tr>
193 193
 									<tr>
194 194
 										<td class="row-title">
195
-											<label for="tablecell"><?php _e( 'Subscription Status:', 'invoicing' ); ?></label>
195
+											<label for="tablecell"><?php _e('Subscription Status:', 'invoicing'); ?></label>
196 196
 										</td>
197 197
 										<td>
198 198
 											<select name="status" class="wpi_select2">
199
-												<option value="pending"<?php selected( 'pending', $sub->status ); ?>><?php _e( 'Pending', 'invoicing' ); ?></option>
200
-												<option value="active"<?php selected( 'active', $sub->status ); ?>><?php _e( 'Active', 'invoicing' ); ?></option>
201
-												<option value="cancelled"<?php selected( 'cancelled', $sub->status ); ?>><?php _e( 'Cancelled', 'invoicing' ); ?></option>
202
-												<option value="expired"<?php selected( 'expired', $sub->status ); ?>><?php _e( 'Expired', 'invoicing' ); ?></option>
203
-												<option value="trialling"<?php selected( 'trialling', $sub->status ); ?>><?php _e( 'Trialling', 'invoicing' ); ?></option>
204
-												<option value="failing"<?php selected( 'failing', $sub->status ); ?>><?php _e( 'Failing', 'invoicing' ); ?></option>
205
-												<option value="completed"<?php selected( 'completed', $sub->status ); ?>><?php _e( 'Completed', 'invoicing' ); ?></option>
199
+												<option value="pending"<?php selected('pending', $sub->status); ?>><?php _e('Pending', 'invoicing'); ?></option>
200
+												<option value="active"<?php selected('active', $sub->status); ?>><?php _e('Active', 'invoicing'); ?></option>
201
+												<option value="cancelled"<?php selected('cancelled', $sub->status); ?>><?php _e('Cancelled', 'invoicing'); ?></option>
202
+												<option value="expired"<?php selected('expired', $sub->status); ?>><?php _e('Expired', 'invoicing'); ?></option>
203
+												<option value="trialling"<?php selected('trialling', $sub->status); ?>><?php _e('Trialling', 'invoicing'); ?></option>
204
+												<option value="failing"<?php selected('failing', $sub->status); ?>><?php _e('Failing', 'invoicing'); ?></option>
205
+												<option value="completed"<?php selected('completed', $sub->status); ?>><?php _e('Completed', 'invoicing'); ?></option>
206 206
 											</select>
207 207
 										</td>
208 208
 									</tr>
@@ -210,79 +210,79 @@  discard block
 block discarded – undo
210 210
 							</table>
211 211
 						</div>
212 212
 						<div id="wpinv-sub-notices">
213
-							<div class="notice notice-info inline hidden" id="wpinv-sub-product-update-notice"><p><?php _e( 'Changing the product assigned will not automatically adjust any pricing.', 'invoicing' ); ?></p></div>
214
-							<div class="notice notice-warning inline hidden" id="wpinv-sub-profile-id-update-notice"><p><?php _e( 'Changing the profile ID can result in renewals not being processed. Do this with caution.', 'invoicing' ); ?></p></div>
213
+							<div class="notice notice-info inline hidden" id="wpinv-sub-product-update-notice"><p><?php _e('Changing the product assigned will not automatically adjust any pricing.', 'invoicing'); ?></p></div>
214
+							<div class="notice notice-warning inline hidden" id="wpinv-sub-profile-id-update-notice"><p><?php _e('Changing the profile ID can result in renewals not being processed. Do this with caution.', 'invoicing'); ?></p></div>
215 215
 						</div>
216 216
 						<div id="item-edit-actions" class="edit-item" style="float:right; margin: 10px 0 0; display: block;">
217
-							<?php wp_nonce_field( 'wpinv-recurring-update', 'wpinv-recurring-update-nonce', false, true ); ?>
218
-							<input type="submit" name="wpinv_update_subscription" id="wpinv_update_subscription" class="button button-primary" value="<?php _e( 'Update Subscription', 'invoicing' ); ?>"/>
219
-							<input type="hidden" name="sub_id" value="<?php echo absint( $sub->id ); ?>" />
220
-							<?php if( $sub->can_cancel() ) : ?>
221
-								<a class="button button-primary" href="<?php echo $sub->get_cancel_url(); ?>" ><?php _e( 'Cancel Subscription', 'invoicing' ); ?></a>
217
+							<?php wp_nonce_field('wpinv-recurring-update', 'wpinv-recurring-update-nonce', false, true); ?>
218
+							<input type="submit" name="wpinv_update_subscription" id="wpinv_update_subscription" class="button button-primary" value="<?php _e('Update Subscription', 'invoicing'); ?>"/>
219
+							<input type="hidden" name="sub_id" value="<?php echo absint($sub->id); ?>" />
220
+							<?php if ($sub->can_cancel()) : ?>
221
+								<a class="button button-primary" href="<?php echo $sub->get_cancel_url(); ?>" ><?php _e('Cancel Subscription', 'invoicing'); ?></a>
222 222
 							<?php endif; ?>
223
-							&nbsp;<input type="submit" name="wpinv_delete_subscription" class="wpinv-delete-subscription button" value="<?php _e( 'Delete Subscription', 'invoicing' ); ?>"/>
223
+							&nbsp;<input type="submit" name="wpinv_delete_subscription" class="wpinv-delete-subscription button" value="<?php _e('Delete Subscription', 'invoicing'); ?>"/>
224 224
 						</div>
225 225
 
226 226
 					</form>
227 227
 				</div>
228 228
 
229
-				<?php do_action( 'wpinv_subscription_before_stats', $sub ); ?>
229
+				<?php do_action('wpinv_subscription_before_stats', $sub); ?>
230 230
 
231
-				<?php do_action( 'wpinv_subscription_before_tables_wrapper', $sub ); ?>
231
+				<?php do_action('wpinv_subscription_before_tables_wrapper', $sub); ?>
232 232
 
233 233
 				<div id="item-tables-wrapper" class="item-section">
234 234
 
235
-					<?php do_action( 'wpinv_subscription_before_tables', $sub ); ?>
235
+					<?php do_action('wpinv_subscription_before_tables', $sub); ?>
236 236
 
237
-					<h3><?php _e( 'Renewal Payments:', 'invoicing' ); ?></h3>
237
+					<h3><?php _e('Renewal Payments:', 'invoicing'); ?></h3>
238 238
 					<?php $payments = $sub->get_child_payments(); ?>
239
-					<?php if ( 'manual' == $sub->gateway ) : ?>
240
-						<p><strong><?php _e( 'Note:', 'invoicing' ); ?></strong> <?php _e( 'Subscriptions purchased with the Test Payment gateway will not renew automatically.', 'invoicing' ); ?></p>
239
+					<?php if ('manual' == $sub->gateway) : ?>
240
+						<p><strong><?php _e('Note:', 'invoicing'); ?></strong> <?php _e('Subscriptions purchased with the Test Payment gateway will not renew automatically.', 'invoicing'); ?></p>
241 241
 					<?php endif; ?>
242 242
 					<table class="wp-list-table widefat striped payments">
243 243
 						<thead>
244 244
 						<tr>
245
-							<th><?php _e( 'ID', 'invoicing' ); ?></th>
246
-							<th><?php _e( 'Amount', 'invoicing' ); ?></th>
247
-							<th><?php _e( 'Date', 'invoicing' ); ?></th>
248
-							<th><?php _e( 'Status', 'invoicing' ); ?></th>
249
-                            <th><?php _e( 'Invoice', 'invoicing' ); ?></th>
250
-							<th class="column-wpi_actions"><?php _e( 'Actions', 'invoicing' ); ?></th>
245
+							<th><?php _e('ID', 'invoicing'); ?></th>
246
+							<th><?php _e('Amount', 'invoicing'); ?></th>
247
+							<th><?php _e('Date', 'invoicing'); ?></th>
248
+							<th><?php _e('Status', 'invoicing'); ?></th>
249
+                            <th><?php _e('Invoice', 'invoicing'); ?></th>
250
+							<th class="column-wpi_actions"><?php _e('Actions', 'invoicing'); ?></th>
251 251
 						</tr>
252 252
 						</thead>
253 253
 						<tbody>
254
-						<?php if ( ! empty( $payments ) ) : ?>
255
-							<?php foreach ( $payments as $payment ) : $invoice = wpinv_get_invoice( $payment->ID ); if ( empty( $invoice->ID ) ) continue; ?>
254
+						<?php if (!empty($payments)) : ?>
255
+							<?php foreach ($payments as $payment) : $invoice = wpinv_get_invoice($payment->ID); if (empty($invoice->ID)) continue; ?>
256 256
 								<tr>
257 257
 									<td><?php echo $payment->ID; ?></td>
258
-									<td><?php echo wpinv_price( $invoice->get_total(), $invoice->get_currency() ); ?></td>
259
-									<td><?php echo wpinv_clean( $invoice->get_date_created() ); ?></td>
260
-									<td><?php echo wpinv_clean( $invoice->get_status_nicename() ); ?></td>
258
+									<td><?php echo wpinv_price($invoice->get_total(), $invoice->get_currency()); ?></td>
259
+									<td><?php echo wpinv_clean($invoice->get_date_created()); ?></td>
260
+									<td><?php echo wpinv_clean($invoice->get_status_nicename()); ?></td>
261 261
 									<td>
262
-										<a target="_blank" title="<?php _e( 'View invoice', 'invoicing' ); ?>" href="<?php echo esc_url( get_permalink( $payment->ID ) ); ?>"><?php echo $invoice->get_number(); ?></a>
263
-										<?php do_action( 'wpinv_subscription_payments_actions', $sub, $payment ); ?>
262
+										<a target="_blank" title="<?php _e('View invoice', 'invoicing'); ?>" href="<?php echo esc_url(get_permalink($payment->ID)); ?>"><?php echo $invoice->get_number(); ?></a>
263
+										<?php do_action('wpinv_subscription_payments_actions', $sub, $payment); ?>
264 264
 									</td>
265 265
 									<td class="column-wpi_actions">
266
-										<a title="<?php echo esc_attr( wp_sprintf( __( 'View details for invoice: %s', 'invoicing' ), $invoice->get_number() ) ); ?>" href="<?php echo get_edit_post_link( $payment->ID ); ?>"><?php _e( 'View Details', 'invoicing' ); ?>
266
+										<a title="<?php echo esc_attr(wp_sprintf(__('View details for invoice: %s', 'invoicing'), $invoice->get_number())); ?>" href="<?php echo get_edit_post_link($payment->ID); ?>"><?php _e('View Details', 'invoicing'); ?>
267 267
 										</a>
268
-										<?php do_action( 'wpinv_subscription_payments_actions', $sub, $payment ); ?>
268
+										<?php do_action('wpinv_subscription_payments_actions', $sub, $payment); ?>
269 269
 									</td>
270 270
 								</tr>
271 271
 							<?php endforeach; ?>
272 272
 						<?php else: ?>
273 273
 							<tr>
274
-								<td colspan="5"><?php _e( 'No Invoices Found.', 'invoicing' ); ?></td>
274
+								<td colspan="5"><?php _e('No Invoices Found.', 'invoicing'); ?></td>
275 275
 							</tr>
276 276
 						<?php endif; ?>
277 277
 						</tbody>
278 278
 						<tfoot></tfoot>
279 279
 					</table>
280 280
 
281
-					<?php do_action( 'wpinv_subscription_after_tables', $sub ); ?>
281
+					<?php do_action('wpinv_subscription_after_tables', $sub); ?>
282 282
 
283 283
 				</div>
284 284
 
285
-				<?php do_action( 'wpinv_subscription_card_bottom', $sub ); ?>
285
+				<?php do_action('wpinv_subscription_card_bottom', $sub); ?>
286 286
 			</div>
287 287
 
288 288
 		<?php endif; ?>
@@ -300,36 +300,36 @@  discard block
 block discarded – undo
300 300
  */
301 301
 function wpinv_recurring_process_subscription_update() {
302 302
 
303
-	if( empty( $_POST['sub_id'] ) ) {
303
+	if (empty($_POST['sub_id'])) {
304 304
 		return;
305 305
 	}
306 306
 
307
-	if( empty( $_POST['wpinv_update_subscription'] ) ) {
307
+	if (empty($_POST['wpinv_update_subscription'])) {
308 308
 		return;
309 309
 	}
310 310
 
311
-	if( ! current_user_can( 'manage_invoicing') ) {
311
+	if (!current_user_can('manage_invoicing')) {
312 312
 		return;
313 313
 	}
314 314
 
315
-	if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
316
-		wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
315
+	if (!wp_verify_nonce($_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update')) {
316
+		wp_die(__('Nonce verification failed', 'invoicing'), __('Error', 'invoicing'), array('response' => 403));
317 317
 	}
318 318
 
319
-	$profile_id      = sanitize_text_field( $_POST['profile_id'] );
320
-	$transaction_id  = sanitize_text_field( $_POST['transaction_id'] );
321
-	$product_id      = absint( $_POST['product_id'] );
322
-	$subscription    = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
323
-	$subscription->update( array(
324
-		'status'         => sanitize_text_field( $_POST['status'] ),
319
+	$profile_id      = sanitize_text_field($_POST['profile_id']);
320
+	$transaction_id  = sanitize_text_field($_POST['transaction_id']);
321
+	$product_id      = absint($_POST['product_id']);
322
+	$subscription    = new WPInv_Subscription(absint($_POST['sub_id']));
323
+	$subscription->update(array(
324
+		'status'         => sanitize_text_field($_POST['status']),
325 325
 		'profile_id'     => $profile_id,
326 326
 		'product_id'     => $product_id,
327 327
 		'transaction_id' => $transaction_id,
328
-	) );
328
+	));
329 329
 
330
-	$status = sanitize_text_field( $_POST['status'] );
330
+	$status = sanitize_text_field($_POST['status']);
331 331
 
332
-	switch( $status ) {
332
+	switch ($status) {
333 333
 
334 334
 		case 'cancelled' :
335 335
 
@@ -348,11 +348,11 @@  discard block
 block discarded – undo
348 348
 
349 349
 	}
350 350
 
351
-	wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=updated&id=' . $subscription->id ) );
351
+	wp_redirect(admin_url('admin.php?page=wpinv-subscriptions&wpinv-message=updated&id=' . $subscription->id));
352 352
 	exit;
353 353
 
354 354
 }
355
-add_action( 'admin_init', 'wpinv_recurring_process_subscription_update', 1 );
355
+add_action('admin_init', 'wpinv_recurring_process_subscription_update', 1);
356 356
 
357 357
 /**
358 358
  * Handles subscription deletion
@@ -363,30 +363,30 @@  discard block
 block discarded – undo
363 363
  */
364 364
 function wpinv_recurring_process_subscription_deletion() {
365 365
 
366
-	if( empty( $_POST['sub_id'] ) ) {
366
+	if (empty($_POST['sub_id'])) {
367 367
 		return;
368 368
 	}
369 369
 
370
-	if( empty( $_POST['wpinv_delete_subscription'] ) ) {
370
+	if (empty($_POST['wpinv_delete_subscription'])) {
371 371
 		return;
372 372
 	}
373 373
 
374
-	if( ! current_user_can( 'manage_invoicing') ) {
374
+	if (!current_user_can('manage_invoicing')) {
375 375
 		return;
376 376
 	}
377 377
 
378
-	if( ! wp_verify_nonce( $_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update' ) ) {
379
-		wp_die( __( 'Nonce verification failed', 'invoicing' ), __( 'Error', 'invoicing' ), array( 'response' => 403 ) );
378
+	if (!wp_verify_nonce($_POST['wpinv-recurring-update-nonce'], 'wpinv-recurring-update')) {
379
+		wp_die(__('Nonce verification failed', 'invoicing'), __('Error', 'invoicing'), array('response' => 403));
380 380
 	}
381 381
 
382
-	$subscription = new WPInv_Subscription( absint( $_POST['sub_id'] ) );
382
+	$subscription = new WPInv_Subscription(absint($_POST['sub_id']));
383 383
 
384
-	delete_post_meta( $subscription->parent_payment_id, '_wpinv_subscription_payment' );
384
+	delete_post_meta($subscription->parent_payment_id, '_wpinv_subscription_payment');
385 385
 
386 386
 	$subscription->delete();
387 387
 
388
-	wp_redirect( admin_url( 'admin.php?page=wpinv-subscriptions&wpinv-message=deleted' ) );
388
+	wp_redirect(admin_url('admin.php?page=wpinv-subscriptions&wpinv-message=deleted'));
389 389
 	exit;
390 390
 
391 391
 }
392
-add_action( 'admin_init', 'wpinv_recurring_process_subscription_deletion', 2 );
392
+add_action('admin_init', 'wpinv_recurring_process_subscription_deletion', 2);
Please login to merge, or discard this patch.
Braces   +14 added lines, -5 removed lines patch added patch discarded remove patch
@@ -181,8 +181,11 @@  discard block
 block discarded – undo
181 181
 											<label for="tablecell">
182 182
 												<?php if( 'trialling' == $sub->status ) : ?>
183 183
 													<?php _e( 'Trialling Until:', 'invoicing' ); ?>
184
-												<?php else: ?>
185
-													<?php _e( 'Expiration Date:', 'invoicing' ); ?>
184
+												<?php else {
185
+    : ?>
186
+													<?php _e( 'Expiration Date:', 'invoicing' );
187
+}
188
+?>
186 189
 												<?php endif; ?>
187 190
 											</label>
188 191
 										</td>
@@ -252,7 +255,10 @@  discard block
 block discarded – undo
252 255
 						</thead>
253 256
 						<tbody>
254 257
 						<?php if ( ! empty( $payments ) ) : ?>
255
-							<?php foreach ( $payments as $payment ) : $invoice = wpinv_get_invoice( $payment->ID ); if ( empty( $invoice->ID ) ) continue; ?>
258
+							<?php foreach ( $payments as $payment ) : $invoice = wpinv_get_invoice( $payment->ID ); if ( empty( $invoice->ID ) ) {
259
+    continue;
260
+}
261
+?>
256 262
 								<tr>
257 263
 									<td><?php echo $payment->ID; ?></td>
258 264
 									<td><?php echo wpinv_price( $invoice->get_total(), $invoice->get_currency() ); ?></td>
@@ -269,9 +275,12 @@  discard block
 block discarded – undo
269 275
 									</td>
270 276
 								</tr>
271 277
 							<?php endforeach; ?>
272
-						<?php else: ?>
278
+						<?php else {
279
+    : ?>
273 280
 							<tr>
274
-								<td colspan="5"><?php _e( 'No Invoices Found.', 'invoicing' ); ?></td>
281
+								<td colspan="5"><?php _e( 'No Invoices Found.', 'invoicing' );
282
+}
283
+?></td>
275 284
 							</tr>
276 285
 						<?php endif; ?>
277 286
 						</tbody>
Please login to merge, or discard this patch.
includes/class-wpinv-ajax.php 2 patches
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -14,70 +14,70 @@  discard block
 block discarded – undo
14 14
 class WPInv_Ajax {
15 15
 
16 16
     /**
17
-	 * Hook in ajax handlers.
18
-	 */
19
-	public static function init() {
20
-		add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
21
-		add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
22
-		self::add_ajax_events();
17
+     * Hook in ajax handlers.
18
+     */
19
+    public static function init() {
20
+        add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
21
+        add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
22
+        self::add_ajax_events();
23 23
     }
24 24
 
25 25
     /**
26
-	 * Set GetPaid AJAX constant and headers.
27
-	 */
28
-	public static function define_ajax() {
29
-
30
-		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
31
-			getpaid_maybe_define_constant( 'DOING_AJAX', true );
32
-			getpaid_maybe_define_constant( 'WPInv_DOING_AJAX', true );
33
-			if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
34
-				/** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
35
-			}
36
-			$GLOBALS['wpdb']->hide_errors();
37
-		}
26
+     * Set GetPaid AJAX constant and headers.
27
+     */
28
+    public static function define_ajax() {
29
+
30
+        if ( ! empty( $_GET['wpinv-ajax'] ) ) {
31
+            getpaid_maybe_define_constant( 'DOING_AJAX', true );
32
+            getpaid_maybe_define_constant( 'WPInv_DOING_AJAX', true );
33
+            if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
34
+                /** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
35
+            }
36
+            $GLOBALS['wpdb']->hide_errors();
37
+        }
38 38
 
39 39
     }
40 40
     
41 41
     /**
42
-	 * Send headers for GetPaid Ajax Requests.
43
-	 *
44
-	 * @since 1.0.18
45
-	 */
46
-	private static function wpinv_ajax_headers() {
47
-		if ( ! headers_sent() ) {
48
-			send_origin_headers();
49
-			send_nosniff_header();
50
-			nocache_headers();
51
-			header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
52
-			header( 'X-Robots-Tag: noindex' );
53
-			status_header( 200 );
54
-		}
42
+     * Send headers for GetPaid Ajax Requests.
43
+     *
44
+     * @since 1.0.18
45
+     */
46
+    private static function wpinv_ajax_headers() {
47
+        if ( ! headers_sent() ) {
48
+            send_origin_headers();
49
+            send_nosniff_header();
50
+            nocache_headers();
51
+            header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
52
+            header( 'X-Robots-Tag: noindex' );
53
+            status_header( 200 );
54
+        }
55 55
     }
56 56
     
57 57
     /**
58
-	 * Check for GetPaid Ajax request and fire action.
59
-	 */
60
-	public static function do_wpinv_ajax() {
61
-		global $wp_query;
58
+     * Check for GetPaid Ajax request and fire action.
59
+     */
60
+    public static function do_wpinv_ajax() {
61
+        global $wp_query;
62 62
 
63
-		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
64
-			$wp_query->set( 'wpinv-ajax', sanitize_text_field( wp_unslash( $_GET['wpinv-ajax'] ) ) );
65
-		}
63
+        if ( ! empty( $_GET['wpinv-ajax'] ) ) {
64
+            $wp_query->set( 'wpinv-ajax', sanitize_text_field( wp_unslash( $_GET['wpinv-ajax'] ) ) );
65
+        }
66 66
 
67
-		$action = $wp_query->get( 'wpinv-ajax' );
67
+        $action = $wp_query->get( 'wpinv-ajax' );
68 68
 
69
-		if ( $action ) {
70
-			self::wpinv_ajax_headers();
71
-			$action = sanitize_text_field( $action );
72
-			do_action( 'wpinv_ajax_' . $action );
73
-			wp_die();
74
-		}
69
+        if ( $action ) {
70
+            self::wpinv_ajax_headers();
71
+            $action = sanitize_text_field( $action );
72
+            do_action( 'wpinv_ajax_' . $action );
73
+            wp_die();
74
+        }
75 75
 
76 76
     }
77 77
 
78 78
     /**
79
-	 * Hook in ajax methods.
80
-	 */
79
+     * Hook in ajax methods.
80
+     */
81 81
     public static function add_ajax_events() {
82 82
 
83 83
         // array( 'event' => is_frontend )
@@ -260,24 +260,24 @@  discard block
 block discarded – undo
260 260
         }
261 261
 
262 262
         // Is the request set up correctly?
263
-		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
264
-			echo aui()->alert(
265
-				array(
266
-					'type'    => 'warning',
267
-					'content' => __( 'No payment form or item provided', 'invoicing' ),
268
-				)
263
+        if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
264
+            echo aui()->alert(
265
+                array(
266
+                    'type'    => 'warning',
267
+                    'content' => __( 'No payment form or item provided', 'invoicing' ),
268
+                )
269 269
             );
270 270
             exit;
271 271
         }
272 272
 
273 273
         // Payment form or button?
274
-		if ( ! empty( $_GET['form'] ) ) {
274
+        if ( ! empty( $_GET['form'] ) ) {
275 275
             getpaid_display_payment_form( $_GET['form'] );
276
-		} else if( $_GET['invoice'] ) {
277
-		    echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
276
+        } else if( $_GET['invoice'] ) {
277
+            echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
278 278
         } else {
279
-			$items = getpaid_convert_items_to_array( $_GET['item'] );
280
-		    getpaid_display_item_payment_form( $items );
279
+            $items = getpaid_convert_items_to_array( $_GET['item'] );
280
+            getpaid_display_item_payment_form( $items );
281 281
         }
282 282
 
283 283
         exit;
Please login to merge, or discard this patch.
Spacing   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
  * @package Invoicing
7 7
  */
8 8
  
9
-defined( 'ABSPATH' ) || exit;
9
+defined('ABSPATH') || exit;
10 10
 
11 11
 /**
12 12
  * WPInv_Ajax class.
@@ -17,8 +17,8 @@  discard block
 block discarded – undo
17 17
 	 * Hook in ajax handlers.
18 18
 	 */
19 19
 	public static function init() {
20
-		add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
21
-		add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
20
+		add_action('init', array(__CLASS__, 'define_ajax'), 0);
21
+		add_action('template_redirect', array(__CLASS__, 'do_wpinv_ajax'), 0);
22 22
 		self::add_ajax_events();
23 23
     }
24 24
 
@@ -27,11 +27,11 @@  discard block
 block discarded – undo
27 27
 	 */
28 28
 	public static function define_ajax() {
29 29
 
30
-		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
31
-			getpaid_maybe_define_constant( 'DOING_AJAX', true );
32
-			getpaid_maybe_define_constant( 'WPInv_DOING_AJAX', true );
33
-			if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
34
-				/** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
30
+		if (!empty($_GET['wpinv-ajax'])) {
31
+			getpaid_maybe_define_constant('DOING_AJAX', true);
32
+			getpaid_maybe_define_constant('WPInv_DOING_AJAX', true);
33
+			if (!WP_DEBUG || (WP_DEBUG && !WP_DEBUG_DISPLAY)) {
34
+				/** @scrutinizer ignore-unhandled */ @ini_set('display_errors', 0);
35 35
 			}
36 36
 			$GLOBALS['wpdb']->hide_errors();
37 37
 		}
@@ -44,13 +44,13 @@  discard block
 block discarded – undo
44 44
 	 * @since 1.0.18
45 45
 	 */
46 46
 	private static function wpinv_ajax_headers() {
47
-		if ( ! headers_sent() ) {
47
+		if (!headers_sent()) {
48 48
 			send_origin_headers();
49 49
 			send_nosniff_header();
50 50
 			nocache_headers();
51
-			header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
52
-			header( 'X-Robots-Tag: noindex' );
53
-			status_header( 200 );
51
+			header('Content-Type: text/html; charset=' . get_option('blog_charset'));
52
+			header('X-Robots-Tag: noindex');
53
+			status_header(200);
54 54
 		}
55 55
     }
56 56
     
@@ -60,16 +60,16 @@  discard block
 block discarded – undo
60 60
 	public static function do_wpinv_ajax() {
61 61
 		global $wp_query;
62 62
 
63
-		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
64
-			$wp_query->set( 'wpinv-ajax', sanitize_text_field( wp_unslash( $_GET['wpinv-ajax'] ) ) );
63
+		if (!empty($_GET['wpinv-ajax'])) {
64
+			$wp_query->set('wpinv-ajax', sanitize_text_field(wp_unslash($_GET['wpinv-ajax'])));
65 65
 		}
66 66
 
67
-		$action = $wp_query->get( 'wpinv-ajax' );
67
+		$action = $wp_query->get('wpinv-ajax');
68 68
 
69
-		if ( $action ) {
69
+		if ($action) {
70 70
 			self::wpinv_ajax_headers();
71
-			$action = sanitize_text_field( $action );
72
-			do_action( 'wpinv_ajax_' . $action );
71
+			$action = sanitize_text_field($action);
72
+			do_action('wpinv_ajax_' . $action);
73 73
 			wp_die();
74 74
 		}
75 75
 
@@ -103,36 +103,36 @@  discard block
 block discarded – undo
103 103
             'ip_geolocation'              => true,
104 104
         );
105 105
 
106
-        foreach ( $ajax_events as $ajax_event => $nopriv ) {
107
-            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
108
-            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
106
+        foreach ($ajax_events as $ajax_event => $nopriv) {
107
+            add_action('wp_ajax_wpinv_' . $ajax_event, array(__CLASS__, $ajax_event));
108
+            add_action('wp_ajax_getpaid_' . $ajax_event, array(__CLASS__, $ajax_event));
109 109
 
110
-            if ( $nopriv ) {
111
-                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
112
-                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
113
-                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
110
+            if ($nopriv) {
111
+                add_action('wp_ajax_nopriv_wpinv_' . $ajax_event, array(__CLASS__, $ajax_event));
112
+                add_action('wp_ajax_nopriv_getpaid_' . $ajax_event, array(__CLASS__, $ajax_event));
113
+                add_action('wpinv_ajax_' . $ajax_event, array(__CLASS__, $ajax_event));
114 114
             }
115 115
         }
116 116
     }
117 117
     
118 118
     public static function add_note() {
119
-        check_ajax_referer( 'add-invoice-note', '_nonce' );
119
+        check_ajax_referer('add-invoice-note', '_nonce');
120 120
 
121
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
121
+        if (!wpinv_current_user_can_manage_invoicing()) {
122 122
             die(-1);
123 123
         }
124 124
 
125
-        $post_id   = absint( $_POST['post_id'] );
126
-        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
127
-        $note_type = sanitize_text_field( $_POST['note_type'] );
125
+        $post_id   = absint($_POST['post_id']);
126
+        $note      = wp_kses_post(trim(stripslashes($_POST['note'])));
127
+        $note_type = sanitize_text_field($_POST['note_type']);
128 128
 
129 129
         $is_customer_note = $note_type == 'customer' ? 1 : 0;
130 130
 
131
-        if ( $post_id > 0 ) {
132
-            $note_id = wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
131
+        if ($post_id > 0) {
132
+            $note_id = wpinv_insert_payment_note($post_id, $note, $is_customer_note);
133 133
 
134
-            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
135
-                wpinv_get_invoice_note_line_item( $note_id );
134
+            if ($note_id > 0 && !is_wp_error($note_id)) {
135
+                wpinv_get_invoice_note_line_item($note_id);
136 136
             }
137 137
         }
138 138
 
@@ -140,16 +140,16 @@  discard block
 block discarded – undo
140 140
     }
141 141
 
142 142
     public static function delete_note() {
143
-        check_ajax_referer( 'delete-invoice-note', '_nonce' );
143
+        check_ajax_referer('delete-invoice-note', '_nonce');
144 144
 
145
-        if ( !wpinv_current_user_can_manage_invoicing() ) {
145
+        if (!wpinv_current_user_can_manage_invoicing()) {
146 146
             die(-1);
147 147
         }
148 148
 
149
-        $note_id = (int)$_POST['note_id'];
149
+        $note_id = (int) $_POST['note_id'];
150 150
 
151
-        if ( $note_id > 0 ) {
152
-            wp_delete_comment( $note_id, true );
151
+        if ($note_id > 0) {
152
+            wp_delete_comment($note_id, true);
153 153
         }
154 154
 
155 155
         die();
@@ -167,34 +167,34 @@  discard block
 block discarded – undo
167 167
     public static function get_billing_details() {
168 168
 
169 169
         // Verify nonce.
170
-        check_ajax_referer( 'wpinv-nonce' );
170
+        check_ajax_referer('wpinv-nonce');
171 171
 
172 172
         // Can the user manage the plugin?
173
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
173
+        if (!wpinv_current_user_can_manage_invoicing()) {
174 174
             die(-1);
175 175
         }
176 176
 
177 177
         // Do we have a user id?
178 178
         $user_id = $_GET['user_id'];
179 179
 
180
-        if ( empty( $user_id ) || ! is_numeric( $user_id ) ) {
180
+        if (empty($user_id) || !is_numeric($user_id)) {
181 181
             die(-1);
182 182
         }
183 183
 
184 184
         // Fetch the billing details.
185
-        $billing_details    = wpinv_get_user_address( $user_id );
186
-        $billing_details    = apply_filters( 'wpinv_ajax_billing_details', $billing_details, $user_id );
185
+        $billing_details    = wpinv_get_user_address($user_id);
186
+        $billing_details    = apply_filters('wpinv_ajax_billing_details', $billing_details, $user_id);
187 187
 
188 188
         // unset the user id and email.
189
-        $to_ignore = array( 'user_id', 'email' );
189
+        $to_ignore = array('user_id', 'email');
190 190
 
191
-        foreach ( $to_ignore as $key ) {
192
-            if ( isset( $billing_details[ $key ] ) ) {
193
-                unset( $billing_details[ $key ] );
191
+        foreach ($to_ignore as $key) {
192
+            if (isset($billing_details[$key])) {
193
+                unset($billing_details[$key]);
194 194
             }
195 195
         }
196 196
 
197
-        wp_send_json_success( $billing_details );
197
+        wp_send_json_success($billing_details);
198 198
 
199 199
     }
200 200
 
@@ -204,47 +204,47 @@  discard block
 block discarded – undo
204 204
     public static function check_new_user_email() {
205 205
 
206 206
         // Verify nonce.
207
-        check_ajax_referer( 'wpinv-nonce' );
207
+        check_ajax_referer('wpinv-nonce');
208 208
 
209 209
         // Can the user manage the plugin?
210
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
210
+        if (!wpinv_current_user_can_manage_invoicing()) {
211 211
             die(-1);
212 212
         }
213 213
 
214 214
         // We need an email address.
215
-        if ( empty( $_GET['email'] ) ) {
216
-            _e( "Provide the new user's email address", 'invoicing' );
215
+        if (empty($_GET['email'])) {
216
+            _e("Provide the new user's email address", 'invoicing');
217 217
             exit;
218 218
         }
219 219
 
220 220
         // Ensure the email is valid.
221
-        $email = sanitize_text_field( $_GET['email'] );
222
-        if ( ! is_email( $email ) ) {
223
-            _e( 'Invalid email address', 'invoicing' );
221
+        $email = sanitize_text_field($_GET['email']);
222
+        if (!is_email($email)) {
223
+            _e('Invalid email address', 'invoicing');
224 224
             exit;
225 225
         }
226 226
 
227 227
         // And it does not exist.
228
-        if ( email_exists( $email ) ) {
229
-            _e( 'A user with this email address already exists', 'invoicing' );
228
+        if (email_exists($email)) {
229
+            _e('A user with this email address already exists', 'invoicing');
230 230
             exit;
231 231
         }
232 232
 
233
-        wp_send_json_success( true );
233
+        wp_send_json_success(true);
234 234
     }
235 235
     
236 236
     public static function run_tool() {
237
-        check_ajax_referer( 'wpinv-nonce', '_nonce' );
238
-        if ( !wpinv_current_user_can_manage_invoicing() ) {
237
+        check_ajax_referer('wpinv-nonce', '_nonce');
238
+        if (!wpinv_current_user_can_manage_invoicing()) {
239 239
             die(-1);
240 240
         }
241 241
         
242
-        $tool = sanitize_text_field( $_POST['tool'] );
242
+        $tool = sanitize_text_field($_POST['tool']);
243 243
         
244
-        do_action( 'wpinv_run_tool' );
244
+        do_action('wpinv_run_tool');
245 245
         
246
-        if ( !empty( $tool ) ) {
247
-            do_action( 'wpinv_tool_' . $tool );
246
+        if (!empty($tool)) {
247
+            do_action('wpinv_tool_' . $tool);
248 248
         }
249 249
     }
250 250
 
@@ -254,30 +254,30 @@  discard block
 block discarded – undo
254 254
     public static function get_payment_form() {
255 255
 
256 256
         // Check nonce.
257
-        if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( $_GET['nonce'], 'getpaid_ajax_form' ) ) {
258
-            _e( 'Error: Reload the page and try again.', 'invoicing' );
257
+        if (!isset($_GET['nonce']) || !wp_verify_nonce($_GET['nonce'], 'getpaid_ajax_form')) {
258
+            _e('Error: Reload the page and try again.', 'invoicing');
259 259
             exit;
260 260
         }
261 261
 
262 262
         // Is the request set up correctly?
263
-		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
263
+		if (empty($_GET['form']) && empty($_GET['item'])) {
264 264
 			echo aui()->alert(
265 265
 				array(
266 266
 					'type'    => 'warning',
267
-					'content' => __( 'No payment form or item provided', 'invoicing' ),
267
+					'content' => __('No payment form or item provided', 'invoicing'),
268 268
 				)
269 269
             );
270 270
             exit;
271 271
         }
272 272
 
273 273
         // Payment form or button?
274
-		if ( ! empty( $_GET['form'] ) ) {
275
-            getpaid_display_payment_form( $_GET['form'] );
276
-		} else if( $_GET['invoice'] ) {
277
-		    echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
274
+		if (!empty($_GET['form'])) {
275
+            getpaid_display_payment_form($_GET['form']);
276
+		} else if ($_GET['invoice']) {
277
+		    echo getpaid_display_invoice_payment_form($_GET['invoice']);
278 278
         } else {
279
-			$items = getpaid_convert_items_to_array( $_GET['item'] );
280
-		    getpaid_display_item_payment_form( $items );
279
+			$items = getpaid_convert_items_to_array($_GET['item']);
280
+		    getpaid_display_item_payment_form($items);
281 281
         }
282 282
 
283 283
         exit;
@@ -293,11 +293,11 @@  discard block
 block discarded – undo
293 293
         global $invoicing;
294 294
 
295 295
         // Check nonce.
296
-        check_ajax_referer( 'getpaid_form_nonce' );
296
+        check_ajax_referer('getpaid_form_nonce');
297 297
 
298 298
         // ... form fields...
299
-        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
300
-            _e( 'Error: Reload the page and try again.', 'invoicing' );
299
+        if (empty($_POST['getpaid_payment_form_submission'])) {
300
+            _e('Error: Reload the page and try again.', 'invoicing');
301 301
             exit;
302 302
         }
303 303
 
@@ -305,66 +305,66 @@  discard block
 block discarded – undo
305 305
         $submission = new GetPaid_Payment_Form_Submission();
306 306
 
307 307
         // Do we have an error?
308
-        if ( ! empty( $submission->last_error ) ) {
308
+        if (!empty($submission->last_error)) {
309 309
             echo $submission->last_error;
310 310
             exit;
311 311
         }
312 312
 
313 313
         // We need a billing email.
314
-        if ( ! $submission->has_billing_email() || ! is_email( $submission->get_billing_email() ) ) {
315
-            wp_send_json_error( __( 'Provide a valid billing email.', 'invoicing' ) );
314
+        if (!$submission->has_billing_email() || !is_email($submission->get_billing_email())) {
315
+            wp_send_json_error(__('Provide a valid billing email.', 'invoicing'));
316 316
         }
317 317
 
318 318
         // Clear any checkout errors.
319 319
         wpinv_clear_errors();
320 320
 
321 321
         // Validate the gateway.
322
-        wpinv_checkout_validate_gateway( $submission );
322
+        wpinv_checkout_validate_gateway($submission);
323 323
 
324 324
         // Allow themes and plugins to hook to errors
325
-        do_action( 'getpaid_checkout_error_checks', $submission );
325
+        do_action('getpaid_checkout_error_checks', $submission);
326 326
 
327 327
         // Do we have any errors?
328
-        if ( wpinv_get_errors() ) {
329
-            wp_send_json_error( getpaid_get_errors_html() );
328
+        if (wpinv_get_errors()) {
329
+            wp_send_json_error(getpaid_get_errors_html());
330 330
         }
331 331
 
332 332
         // Prepare items.
333 333
         $items = $submission->get_items();
334 334
 
335 335
         // Ensure that we have items.
336
-        if ( empty( $items ) ) {
337
-            wp_send_json_error( __( 'You have not selected any items.', 'invoicing' ) );
336
+        if (empty($items)) {
337
+            wp_send_json_error(__('You have not selected any items.', 'invoicing'));
338 338
         }
339 339
 
340 340
         // Prepare the invoice.
341
-        if ( ! $submission->has_invoice() ) {
341
+        if (!$submission->has_invoice()) {
342 342
             $invoice = new WPInv_Invoice();
343 343
         } else {
344 344
             $invoice = $submission->get_invoice();
345 345
         }
346 346
 
347 347
         // Make sure that it is neither paid or refunded.
348
-        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
349
-            wp_send_json_error( __( 'This invoice has already been paid for.', 'invoicing' ) );
348
+        if ($invoice->is_paid() || $invoice->is_refunded()) {
349
+            wp_send_json_error(__('This invoice has already been paid for.', 'invoicing'));
350 350
         }
351 351
 
352 352
         // Set the billing email.
353
-        $invoice->set_email( sanitize_email( $submission->get_billing_email() ) );
353
+        $invoice->set_email(sanitize_email($submission->get_billing_email()));
354 354
 
355 355
         // Payment form.
356
-        $invoice->set_payment_form( absint( $submission->get_payment_form()->get_id() ) );
356
+        $invoice->set_payment_form(absint($submission->get_payment_form()->get_id()));
357 357
 
358 358
         // Discount code.
359
-        if ( $submission->has_discount_code() ) {
360
-            $invoice->set_discount_code( $submission->get_discount_code() );
359
+        if ($submission->has_discount_code()) {
360
+            $invoice->set_discount_code($submission->get_discount_code());
361 361
         }
362 362
 
363 363
         // Items, Fees, taxes and discounts.
364
-        $invoice->set_items( $items );
365
-        $invoice->set_fees( $submission->get_fees() );
366
-        $invoice->set_taxes( $submission->get_taxes() );
367
-        $invoice->set_discounts( $submission->get_discounts() );
364
+        $invoice->set_items($items);
365
+        $invoice->set_fees($submission->get_fees());
366
+        $invoice->set_taxes($submission->get_taxes());
367
+        $invoice->set_discounts($submission->get_discounts());
368 368
 
369 369
         // Prepared submission details.
370 370
         $prepared = array();
@@ -373,48 +373,48 @@  discard block
 block discarded – undo
373 373
         $data = $submission->get_data();
374 374
 
375 375
         // Loop throught the submitted details.
376
-        foreach ( $submission->get_payment_form()->get_elements() as $field ) {
376
+        foreach ($submission->get_payment_form()->get_elements() as $field) {
377 377
 
378
-            if ( ! empty( $field['premade'] ) ) {
378
+            if (!empty($field['premade'])) {
379 379
                 continue;
380 380
             }
381 381
 
382 382
             // If it is required and not set, abort.
383
-            if ( ! $submission->is_required_field_set( $field ) ) {
384
-                wp_send_json_error( __( 'Some required fields are not set.', 'invoicing' ) );
383
+            if (!$submission->is_required_field_set($field)) {
384
+                wp_send_json_error(__('Some required fields are not set.', 'invoicing'));
385 385
             }
386 386
 
387 387
             // Handle address fields.
388
-            if ( $field['type'] == 'address' ) {
388
+            if ($field['type'] == 'address') {
389 389
 
390
-                foreach ( $field['fields'] as $address_field ) {
390
+                foreach ($field['fields'] as $address_field) {
391 391
 
392 392
                     // skip if it is not visible.
393
-                    if ( empty( $address_field['visible'] ) ) {
393
+                    if (empty($address_field['visible'])) {
394 394
                         continue;
395 395
                     }
396 396
 
397 397
                     // If it is required and not set, abort
398
-                    if ( ! empty( $address_field['required'] ) && empty( $data[ $address_field['name'] ] ) ) {
399
-                        wp_send_json_error( __( 'Some required fields are not set.', 'invoicing' ) );
398
+                    if (!empty($address_field['required']) && empty($data[$address_field['name']])) {
399
+                        wp_send_json_error(__('Some required fields are not set.', 'invoicing'));
400 400
                     }
401 401
 
402
-                    if ( isset( $data[ $address_field['name'] ] ) ) {
403
-                        $name   = str_replace( 'wpinv_', '', $address_field['name'] );
402
+                    if (isset($data[$address_field['name']])) {
403
+                        $name   = str_replace('wpinv_', '', $address_field['name']);
404 404
                         $method = "set_$name";
405
-                        $invoice->$method( wpinv_clean( $data[ $address_field['name'] ] ) );
405
+                        $invoice->$method(wpinv_clean($data[$address_field['name']]));
406 406
                     }
407 407
 
408 408
                 }
409 409
 
410
-            } else if ( isset( $data[ $field['id'] ] ) ) {
410
+            } else if (isset($data[$field['id']])) {
411 411
                 $label = $field['id'];
412 412
 
413
-                if ( isset( $field['label'] ) ) {
413
+                if (isset($field['label'])) {
414 414
                     $label = $field['label'];
415 415
                 }
416 416
 
417
-                $prepared[ wpinv_clean( $label ) ] = wpinv_clean( $data[ $field['id'] ] );
417
+                $prepared[wpinv_clean($label)] = wpinv_clean($data[$field['id']]);
418 418
             }
419 419
 
420 420
         }
@@ -422,26 +422,26 @@  discard block
 block discarded – undo
422 422
         // (Maybe) create the user.
423 423
         $user = get_current_user_id();
424 424
 
425
-        if ( empty( $user ) ) {
426
-            $user = get_user_by( 'email', $submission->get_billing_email() );
425
+        if (empty($user)) {
426
+            $user = get_user_by('email', $submission->get_billing_email());
427 427
         }
428 428
 
429
-        if ( empty( $user ) ) {
430
-            $user = wpinv_create_user( $submission->get_billing_email() );
429
+        if (empty($user)) {
430
+            $user = wpinv_create_user($submission->get_billing_email());
431 431
         }
432 432
 
433
-        if ( is_wp_error( $user ) ) {
434
-            wp_send_json_error( $user->get_error_message() );
433
+        if (is_wp_error($user)) {
434
+            wp_send_json_error($user->get_error_message());
435 435
         }
436 436
 
437
-        if ( is_numeric( $user ) ) {
438
-            $user = get_user_by( 'id', $user );
437
+        if (is_numeric($user)) {
438
+            $user = get_user_by('id', $user);
439 439
         }
440 440
 
441
-        $invoice->set_user_id( $user->ID );
441
+        $invoice->set_user_id($user->ID);
442 442
 
443 443
         // Set gateway.
444
-        $invoice->set_gateway( $data['wpi-gateway'] );
444
+        $invoice->set_gateway($data['wpi-gateway']);
445 445
 
446 446
         $invoice->recalculate_total();
447 447
 
@@ -449,20 +449,20 @@  discard block
 block discarded – undo
449 449
         $invoice->save();
450 450
 
451 451
         // Was it saved successfully:
452
-        if ($invoice->get_id() == 0 ) {
453
-            wp_send_json_error( __( 'An error occured while saving your invoice.', 'invoicing' ) );
452
+        if ($invoice->get_id() == 0) {
453
+            wp_send_json_error(__('An error occured while saving your invoice.', 'invoicing'));
454 454
         }
455 455
 
456 456
         // Save payment form data.
457
-        if ( ! empty( $prepared ) ) {
458
-            update_post_meta( $invoice->get_id(), 'payment_form_data', $prepared );
457
+        if (!empty($prepared)) {
458
+            update_post_meta($invoice->get_id(), 'payment_form_data', $prepared);
459 459
         }
460 460
 
461 461
         // Process the checkout.
462
-        add_filter( 'wp_redirect', array( $invoicing->form_elements, 'send_redirect_response' ) );
463
-        add_action( 'wpinv_pre_send_back_to_checkout', array( $invoicing->form_elements, 'checkout_error' ) );
462
+        add_filter('wp_redirect', array($invoicing->form_elements, 'send_redirect_response'));
463
+        add_action('wpinv_pre_send_back_to_checkout', array($invoicing->form_elements, 'checkout_error'));
464 464
 
465
-        wpinv_process_checkout( $invoice, $submission );
465
+        wpinv_process_checkout($invoice, $submission);
466 466
 
467 467
         // If we are here, there was an error.
468 468
         $invoicing->form_elements->checkout_error();
@@ -478,51 +478,51 @@  discard block
 block discarded – undo
478 478
     public static function get_payment_form_states_field() {
479 479
         global $invoicing;
480 480
 
481
-        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
481
+        if (empty($_GET['country']) || empty($_GET['form'])) {
482 482
             exit;
483 483
         }
484 484
 
485
-        $elements = $invoicing->form_elements->get_form_elements( $_GET['form'] );
485
+        $elements = $invoicing->form_elements->get_form_elements($_GET['form']);
486 486
 
487
-        if ( empty( $elements ) ) {
487
+        if (empty($elements)) {
488 488
             exit;
489 489
         }
490 490
 
491 491
         $address_fields = array();
492
-        foreach ( $elements as $element ) {
493
-            if ( 'address' === $element['type'] ) {
492
+        foreach ($elements as $element) {
493
+            if ('address' === $element['type']) {
494 494
                 $address_fields = $element;
495 495
                 break;
496 496
             }
497 497
         }
498 498
 
499
-        if ( empty( $address_fields ) ) {
499
+        if (empty($address_fields)) {
500 500
             exit;
501 501
         }
502 502
 
503
-        foreach( $address_fields['fields'] as $address_field ) {
503
+        foreach ($address_fields['fields'] as $address_field) {
504 504
 
505
-            if ( 'wpinv_state' == $address_field['name'] ) {
505
+            if ('wpinv_state' == $address_field['name']) {
506 506
 
507 507
                 $label = $address_field['label'];
508 508
 
509
-                if ( ! empty( $address_field['required'] ) ) {
509
+                if (!empty($address_field['required'])) {
510 510
                     $label .= "<span class='text-danger'> *</span>";
511 511
                 }
512 512
 
513
-                $states = wpinv_get_country_states( $_GET['country'] );
513
+                $states = wpinv_get_country_states($_GET['country']);
514 514
 
515
-                if ( ! empty( $states ) ) {
515
+                if (!empty($states)) {
516 516
 
517 517
                     $html = aui()->select(
518 518
                             array(
519 519
                                 'options'          => $states,
520
-                                'name'             => esc_attr( $address_field['name'] ),
521
-                                'id'               => esc_attr( $address_field['name'] ),
522
-                                'placeholder'      => esc_attr( $address_field['placeholder'] ),
520
+                                'name'             => esc_attr($address_field['name']),
521
+                                'id'               => esc_attr($address_field['name']),
522
+                                'placeholder'      => esc_attr($address_field['placeholder']),
523 523
                                 'required'         => (bool) $address_field['required'],
524 524
                                 'no_wrap'          => true,
525
-                                'label'            => wp_kses_post( $label ),
525
+                                'label'            => wp_kses_post($label),
526 526
                                 'select2'          => false,
527 527
                             )
528 528
                         );
@@ -531,10 +531,10 @@  discard block
 block discarded – undo
531 531
 
532 532
                     $html = aui()->input(
533 533
                             array(
534
-                                'name'       => esc_attr( $address_field['name'] ),
535
-                                'id'         => esc_attr( $address_field['name'] ),
534
+                                'name'       => esc_attr($address_field['name']),
535
+                                'id'         => esc_attr($address_field['name']),
536 536
                                 'required'   => (bool) $address_field['required'],
537
-                                'label'      => wp_kses_post( $label ),
537
+                                'label'      => wp_kses_post($label),
538 538
                                 'no_wrap'    => true,
539 539
                                 'type'       => 'text',
540 540
                             )
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 
543 543
                 }
544 544
 
545
-                wp_send_json_success( str_replace( 'sr-only', '', $html ) );
545
+                wp_send_json_success(str_replace('sr-only', '', $html));
546 546
                 exit;
547 547
 
548 548
             }
@@ -558,56 +558,56 @@  discard block
 block discarded – undo
558 558
     public static function recalculate_invoice_totals() {
559 559
 
560 560
         // Verify nonce.
561
-        check_ajax_referer( 'wpinv-nonce' );
561
+        check_ajax_referer('wpinv-nonce');
562 562
 
563
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
563
+        if (!wpinv_current_user_can_manage_invoicing()) {
564 564
             exit;
565 565
         }
566 566
 
567 567
         // We need an invoice.
568
-        if ( empty( $_POST['post_id'] ) ) {
568
+        if (empty($_POST['post_id'])) {
569 569
             exit;
570 570
         }
571 571
 
572 572
         // Fetch the invoice.
573
-        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
573
+        $invoice = new WPInv_Invoice(trim($_POST['post_id']));
574 574
 
575 575
         // Ensure it exists.
576
-        if ( ! $invoice->get_id() ) {
576
+        if (!$invoice->get_id()) {
577 577
             exit;
578 578
         }
579 579
 
580 580
         // Maybe set the country, state, currency.
581
-        foreach ( array( 'country', 'state', 'currency' ) as $key ) {
582
-            if ( isset( $_POST[ $key ] ) ) {
581
+        foreach (array('country', 'state', 'currency') as $key) {
582
+            if (isset($_POST[$key])) {
583 583
                 $method = "set_$key";
584
-                $invoice->$method( $_POST[ $key ] );
584
+                $invoice->$method($_POST[$key]);
585 585
             }
586 586
         }
587 587
 
588 588
         // Maybe disable taxes.
589
-        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
589
+        $invoice->set_disable_taxes(!empty($_POST['taxes']));
590 590
 
591 591
         // Recalculate totals.
592 592
         $invoice->recalculate_total();
593 593
 
594
-        $total = wpinv_price( wpinv_format_amount( $invoice->get_total() ), $invoice->get_currency() );
594
+        $total = wpinv_price(wpinv_format_amount($invoice->get_total()), $invoice->get_currency());
595 595
 
596
-        if ( $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
597
-            $recurring_total = wpinv_price( wpinv_format_amount( $invoice->get_recurring_total() ), $invoice->get_currency() );
598
-            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
596
+        if ($invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total()) {
597
+            $recurring_total = wpinv_price(wpinv_format_amount($invoice->get_recurring_total()), $invoice->get_currency());
598
+            $total          .= '<small class="form-text text-muted">' . sprintf(__('Recurring Price: %s', 'invoicing'), $recurring_total) . '</small>';
599 599
         }
600 600
 
601 601
         $totals = array(
602
-            'subtotal' => wpinv_price( wpinv_format_amount( $invoice->get_subtotal() ), $invoice->get_currency() ),
603
-            'discount' => wpinv_price( wpinv_format_amount( $invoice->get_total_discount() ), $invoice->get_currency() ),
604
-            'tax'      => wpinv_price( wpinv_format_amount( $invoice->get_total_tax() ), $invoice->get_currency() ),
602
+            'subtotal' => wpinv_price(wpinv_format_amount($invoice->get_subtotal()), $invoice->get_currency()),
603
+            'discount' => wpinv_price(wpinv_format_amount($invoice->get_total_discount()), $invoice->get_currency()),
604
+            'tax'      => wpinv_price(wpinv_format_amount($invoice->get_total_tax()), $invoice->get_currency()),
605 605
             'total'    => $total,
606 606
         );
607 607
 
608
-        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
608
+        $totals = apply_filters('getpaid_invoice_totals', $totals, $invoice);
609 609
 
610
-        wp_send_json_success( compact( 'totals' ) );
610
+        wp_send_json_success(compact('totals'));
611 611
     }
612 612
 
613 613
     /**
@@ -616,33 +616,33 @@  discard block
 block discarded – undo
616 616
     public static function get_invoice_items() {
617 617
 
618 618
         // Verify nonce.
619
-        check_ajax_referer( 'wpinv-nonce' );
619
+        check_ajax_referer('wpinv-nonce');
620 620
 
621
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
621
+        if (!wpinv_current_user_can_manage_invoicing()) {
622 622
             exit;
623 623
         }
624 624
 
625 625
         // We need an invoice and items.
626
-        if ( empty( $_POST['post_id'] ) ) {
626
+        if (empty($_POST['post_id'])) {
627 627
             exit;
628 628
         }
629 629
 
630 630
         // Fetch the invoice.
631
-        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
631
+        $invoice = new WPInv_Invoice(trim($_POST['post_id']));
632 632
 
633 633
         // Ensure it exists.
634
-        if ( ! $invoice->get_id() ) {
634
+        if (!$invoice->get_id()) {
635 635
             exit;
636 636
         }
637 637
 
638 638
         // Return an array of invoice items.
639 639
         $items = array();
640 640
 
641
-        foreach ( $invoice->get_items() as $item_id => $item ) {
642
-            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
641
+        foreach ($invoice->get_items() as $item_id => $item) {
642
+            $items[$item_id] = $item->prepare_data_for_invoice_edit_ajax($invoice->get_currency());
643 643
         }
644 644
 
645
-        wp_send_json_success( compact( 'items' ) );
645
+        wp_send_json_success(compact('items'));
646 646
     }
647 647
 
648 648
     /**
@@ -651,50 +651,50 @@  discard block
 block discarded – undo
651 651
     public static function edit_invoice_item() {
652 652
 
653 653
         // Verify nonce.
654
-        check_ajax_referer( 'wpinv-nonce' );
654
+        check_ajax_referer('wpinv-nonce');
655 655
 
656
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
656
+        if (!wpinv_current_user_can_manage_invoicing()) {
657 657
             exit;
658 658
         }
659 659
 
660 660
         // We need an invoice and item details.
661
-        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
661
+        if (empty($_POST['post_id']) || empty($_POST['data'])) {
662 662
             exit;
663 663
         }
664 664
 
665 665
         // Fetch the invoice.
666
-        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
666
+        $invoice = new WPInv_Invoice(trim($_POST['post_id']));
667 667
 
668 668
         // Ensure it exists and its not been paid for.
669
-        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
669
+        if (!$invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded()) {
670 670
             exit;
671 671
         }
672 672
 
673 673
         // Format the data.
674
-        $data = wp_list_pluck( $_POST['data'], 'value', 'field' );
674
+        $data = wp_list_pluck($_POST['data'], 'value', 'field');
675 675
 
676 676
         // Ensure that we have an item id.
677
-        if ( empty( $data['id'] ) ) {
677
+        if (empty($data['id'])) {
678 678
             exit;
679 679
         }
680 680
 
681 681
         // Abort if the invoice does not have the specified item.
682
-        $item = $invoice->get_item( (int) $data['id'] );
682
+        $item = $invoice->get_item((int) $data['id']);
683 683
 
684
-        if ( empty( $item ) ) {
684
+        if (empty($item)) {
685 685
             exit;
686 686
         }
687 687
 
688 688
         // Update the item.
689
-        $item->set_price( $data['price'] );
690
-        $item->set_name( $data['name'] );
691
-        $item->set_description( $data['description'] );
692
-        $item->set_quantity( $data['quantity'] );
689
+        $item->set_price($data['price']);
690
+        $item->set_name($data['name']);
691
+        $item->set_description($data['description']);
692
+        $item->set_quantity($data['quantity']);
693 693
 
694 694
         // Add it to the invoice.
695
-        $error = $invoice->add_item( $item );
695
+        $error = $invoice->add_item($item);
696 696
         $alert = false;
697
-        if ( is_wp_error( $error ) ) {
697
+        if (is_wp_error($error)) {
698 698
             $alert = $error->get_error_message();
699 699
         }
700 700
 
@@ -707,11 +707,11 @@  discard block
 block discarded – undo
707 707
         // Return an array of invoice items.
708 708
         $items = array();
709 709
 
710
-        foreach ( $invoice->get_items() as $item_id => $item ) {
711
-            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
710
+        foreach ($invoice->get_items() as $item_id => $item) {
711
+            $items[$item_id] = $item->prepare_data_for_invoice_edit_ajax($invoice->get_currency());
712 712
         }
713 713
 
714
-        wp_send_json_success( compact( 'items', 'alert' ) );
714
+        wp_send_json_success(compact('items', 'alert'));
715 715
     }
716 716
 
717 717
     /**
@@ -720,33 +720,33 @@  discard block
 block discarded – undo
720 720
     public static function remove_invoice_item() {
721 721
 
722 722
         // Verify nonce.
723
-        check_ajax_referer( 'wpinv-nonce' );
723
+        check_ajax_referer('wpinv-nonce');
724 724
 
725
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
725
+        if (!wpinv_current_user_can_manage_invoicing()) {
726 726
             exit;
727 727
         }
728 728
 
729 729
         // We need an invoice and an item.
730
-        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
730
+        if (empty($_POST['post_id']) || empty($_POST['item_id'])) {
731 731
             exit;
732 732
         }
733 733
 
734 734
         // Fetch the invoice.
735
-        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
735
+        $invoice = new WPInv_Invoice(trim($_POST['post_id']));
736 736
 
737 737
         // Ensure it exists and its not been paid for.
738
-        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
738
+        if (!$invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded()) {
739 739
             exit;
740 740
         }
741 741
 
742 742
         // Abort if the invoice does not have the specified item.
743
-        $item = $invoice->get_item( (int) $_POST['item_id'] );
743
+        $item = $invoice->get_item((int) $_POST['item_id']);
744 744
 
745
-        if ( empty( $item ) ) {
745
+        if (empty($item)) {
746 746
             exit;
747 747
         }
748 748
 
749
-        $invoice->remove_item( (int) $_POST['item_id'] );
749
+        $invoice->remove_item((int) $_POST['item_id']);
750 750
 
751 751
         // Update totals.
752 752
         $invoice->recalculate_total();
@@ -757,11 +757,11 @@  discard block
 block discarded – undo
757 757
         // Return an array of invoice items.
758 758
         $items = array();
759 759
 
760
-        foreach ( $invoice->get_items() as $item_id => $item ) {
761
-            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
760
+        foreach ($invoice->get_items() as $item_id => $item) {
761
+            $items[$item_id] = $item->prepare_data_for_invoice_edit_ajax($invoice->get_currency());
762 762
         }
763 763
 
764
-        wp_send_json_success( compact( 'items' ) );
764
+        wp_send_json_success(compact('items'));
765 765
     }
766 766
 
767 767
     /**
@@ -770,39 +770,39 @@  discard block
 block discarded – undo
770 770
     public static function add_invoice_items() {
771 771
 
772 772
         // Verify nonce.
773
-        check_ajax_referer( 'wpinv-nonce' );
773
+        check_ajax_referer('wpinv-nonce');
774 774
 
775
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
775
+        if (!wpinv_current_user_can_manage_invoicing()) {
776 776
             exit;
777 777
         }
778 778
 
779 779
         // We need an invoice and items.
780
-        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
780
+        if (empty($_POST['post_id']) || empty($_POST['items'])) {
781 781
             exit;
782 782
         }
783 783
 
784 784
         // Fetch the invoice.
785
-        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
785
+        $invoice = new WPInv_Invoice(trim($_POST['post_id']));
786 786
         $alert   = false;
787 787
 
788 788
         // Ensure it exists and its not been paid for.
789
-        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
789
+        if (!$invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded()) {
790 790
             exit;
791 791
         }
792 792
 
793 793
         // Add the items.
794
-        foreach ( $_POST['items'] as $data ) {
794
+        foreach ($_POST['items'] as $data) {
795 795
 
796
-            $item = new GetPaid_Form_Item( $data[ 'id' ] );
796
+            $item = new GetPaid_Form_Item($data['id']);
797 797
 
798
-            if ( is_numeric( $data[ 'qty' ] ) && (int) $data[ 'qty' ] > 0 ) {
799
-                $item->set_quantity( $data[ 'qty' ] );
798
+            if (is_numeric($data['qty']) && (int) $data['qty'] > 0) {
799
+                $item->set_quantity($data['qty']);
800 800
             }
801 801
 
802
-            if ( $item->get_id() > 0 ) {
803
-                $error = $invoice->add_item( $item );
802
+            if ($item->get_id() > 0) {
803
+                $error = $invoice->add_item($item);
804 804
 
805
-                if ( is_wp_error( $error ) ) {
805
+                if (is_wp_error($error)) {
806 806
                     $alert = $error->get_error_message();
807 807
                 }
808 808
 
@@ -817,11 +817,11 @@  discard block
 block discarded – undo
817 817
         // Return an array of invoice items.
818 818
         $items = array();
819 819
 
820
-        foreach ( $invoice->get_items() as $item_id => $item ) {
821
-            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
820
+        foreach ($invoice->get_items() as $item_id => $item) {
821
+            $items[$item_id] = $item->prepare_data_for_invoice_edit_ajax($invoice->get_currency());
822 822
         }
823 823
 
824
-        wp_send_json_success( compact( 'items', 'alert' ) );
824
+        wp_send_json_success(compact('items', 'alert'));
825 825
     }
826 826
 
827 827
     /**
@@ -830,15 +830,15 @@  discard block
 block discarded – undo
830 830
     public static function get_invoicing_items() {
831 831
 
832 832
         // Verify nonce.
833
-        check_ajax_referer( 'wpinv-nonce' );
833
+        check_ajax_referer('wpinv-nonce');
834 834
 
835
-        if ( ! wpinv_current_user_can_manage_invoicing() ) {
835
+        if (!wpinv_current_user_can_manage_invoicing()) {
836 836
             exit;
837 837
         }
838 838
 
839 839
         // We need a search term.
840
-        if ( empty( $_GET['search'] ) ) {
841
-            wp_send_json_success( array() );
840
+        if (empty($_GET['search'])) {
841
+            wp_send_json_success(array());
842 842
         }
843 843
 
844 844
         // Retrieve items.
@@ -847,8 +847,8 @@  discard block
 block discarded – undo
847 847
             'orderby'        => 'title',
848 848
             'order'          => 'ASC',
849 849
             'posts_per_page' => -1,
850
-            'post_status'    => array( 'publish' ),
851
-            's'              => trim( $_GET['search'] ),
850
+            'post_status'    => array('publish'),
851
+            's'              => trim($_GET['search']),
852 852
             'meta_query'     => array(
853 853
                 array(
854 854
                     'key'       => '_wpinv_type',
@@ -858,18 +858,18 @@  discard block
 block discarded – undo
858 858
             )
859 859
         );
860 860
 
861
-        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
861
+        $items = get_posts(apply_filters('getpaid_ajax_invoice_items_query_args', $item_args));
862 862
         $data  = array();
863 863
 
864
-        foreach ( $items as $item ) {
865
-            $item      = new GetPaid_Form_Item( $item );
864
+        foreach ($items as $item) {
865
+            $item = new GetPaid_Form_Item($item);
866 866
             $data[] = array(
867 867
                 'id'   => $item->get_id(),
868 868
                 'text' => $item->get_name()
869 869
             );
870 870
         }
871 871
 
872
-        wp_send_json_success( $data );
872
+        wp_send_json_success($data);
873 873
 
874 874
     }
875 875
 
@@ -879,24 +879,24 @@  discard block
 block discarded – undo
879 879
     public static function get_aui_states_field() {
880 880
 
881 881
         // Verify nonce.
882
-        check_ajax_referer( 'wpinv-nonce' );
882
+        check_ajax_referer('wpinv-nonce');
883 883
 
884 884
         // We need a country.
885
-        if ( empty( $_GET['country'] ) ) {
885
+        if (empty($_GET['country'])) {
886 886
             exit;
887 887
         }
888 888
 
889
-        $states = wpinv_get_country_states( trim( $_GET['country'] ) );
890
-        $state  = isset( $_GET['state'] ) ? trim( $_GET['state'] ) : wpinv_get_default_state();
889
+        $states = wpinv_get_country_states(trim($_GET['country']));
890
+        $state  = isset($_GET['state']) ? trim($_GET['state']) : wpinv_get_default_state();
891 891
 
892
-        if ( empty( $states ) ) {
892
+        if (empty($states)) {
893 893
 
894 894
             $html = aui()->input(
895 895
                 array(
896 896
                     'type'        => 'text',
897 897
                     'id'          => 'wpinv_state',
898 898
                     'name'        => 'wpinv_state',
899
-                    'label'       => __( 'State', 'invoicing' ),
899
+                    'label'       => __('State', 'invoicing'),
900 900
                     'label_type'  => 'vertical',
901 901
                     'placeholder' => 'Liège',
902 902
                     'class'       => 'form-control-sm',
@@ -910,9 +910,9 @@  discard block
 block discarded – undo
910 910
                 array(
911 911
                     'id'          => 'wpinv_state',
912 912
                     'name'        => 'wpinv_state',
913
-                    'label'       => __( 'State', 'invoicing' ),
913
+                    'label'       => __('State', 'invoicing'),
914 914
                     'label_type'  => 'vertical',
915
-                    'placeholder' => __( 'Select a state', 'invoicing' ),
915
+                    'placeholder' => __('Select a state', 'invoicing'),
916 916
                     'class'       => 'form-control-sm',
917 917
                     'value'       => $state,
918 918
                     'options'     => $states,
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
         wp_send_json_success(
927 927
             array(
928 928
                 'html'   => $html,
929
-                'select' => ! empty ( $states )
929
+                'select' => !empty ($states)
930 930
             )
931 931
         );
932 932
 
@@ -940,46 +940,46 @@  discard block
 block discarded – undo
940 940
     public static function ip_geolocation() {
941 941
 
942 942
         // Check nonce.
943
-        check_ajax_referer( 'getpaid-ip-location' );
943
+        check_ajax_referer('getpaid-ip-location');
944 944
 
945 945
         // IP address.
946
-        if ( empty( $_GET['ip'] ) || ! rest_is_ip_address( $_GET['ip'] ) ) {
947
-            _e( 'Invalid IP Address.', 'invoicing' );
946
+        if (empty($_GET['ip']) || !rest_is_ip_address($_GET['ip'])) {
947
+            _e('Invalid IP Address.', 'invoicing');
948 948
             exit;
949 949
         }
950 950
 
951 951
         // Retrieve location info.
952
-        $location = getpaid_geolocate_ip_address( $_GET['ip'] );
952
+        $location = getpaid_geolocate_ip_address($_GET['ip']);
953 953
 
954
-        if ( empty( $location ) ) {
955
-            _e( 'Unable to find geolocation for the IP Address.', 'invoicing' );
954
+        if (empty($location)) {
955
+            _e('Unable to find geolocation for the IP Address.', 'invoicing');
956 956
             exit;
957 957
         }
958 958
 
959 959
         // Sorry.
960
-        extract( $location );
960
+        extract($location);
961 961
 
962 962
         // Prepare the address.
963 963
         $content = '';
964 964
 
965
-        if ( ! empty( $location['city'] ) ) {
966
-            $content .=  $location['city']  . ', ';
965
+        if (!empty($location['city'])) {
966
+            $content .= $location['city'] . ', ';
967 967
         }
968 968
         
969
-        if ( ! empty( $location['region'] ) ) {
970
-            $content .=  $location['region']  . ', ';
969
+        if (!empty($location['region'])) {
970
+            $content .= $location['region'] . ', ';
971 971
         }
972 972
         
973
-        $content .=  $location['country'] . ' (' . $location['iso'] . ')';
973
+        $content .= $location['country'] . ' (' . $location['iso'] . ')';
974 974
 
975 975
         $location['address'] = $content;
976 976
 
977
-        $content  = '<p>'. sprintf( __( '<b>Address:</b> %s', 'invoicing' ), $content ) . '</p>';
978
-        $content .= '<p>'. $location['credit'] . '</p>';
977
+        $content  = '<p>' . sprintf(__('<b>Address:</b> %s', 'invoicing'), $content) . '</p>';
978
+        $content .= '<p>' . $location['credit'] . '</p>';
979 979
 
980 980
         $location['content'] = $content;
981 981
 
982
-        wpinv_get_template( 'geolocation.php', $location );
982
+        wpinv_get_template('geolocation.php', $location);
983 983
 
984 984
         exit;
985 985
     }
@@ -992,11 +992,11 @@  discard block
 block discarded – undo
992 992
     public static function payment_form_refresh_prices() {
993 993
 
994 994
         // Check nonce.
995
-        check_ajax_referer( 'getpaid_form_nonce' );
995
+        check_ajax_referer('getpaid_form_nonce');
996 996
 
997 997
         // ... form fields...
998
-        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
999
-            _e( 'Error: Reload the page and try again.', 'invoicing' );
998
+        if (empty($_POST['getpaid_payment_form_submission'])) {
999
+            _e('Error: Reload the page and try again.', 'invoicing');
1000 1000
             exit;
1001 1001
         }
1002 1002
 
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
         $submission = new GetPaid_Payment_Form_Submission();
1005 1005
 
1006 1006
         // Do we have an error?
1007
-        if ( ! empty( $submission->last_error ) ) {
1007
+        if (!empty($submission->last_error)) {
1008 1008
             echo $submission->last_error;
1009 1009
             exit;
1010 1010
         }
@@ -1017,43 +1017,43 @@  discard block
 block discarded – undo
1017 1017
             'is_free'       => $submission->get_payment_details(),
1018 1018
 
1019 1019
             'totals'        => array(
1020
-                'subtotal'  => wpinv_price( wpinv_format_amount( $submission->subtotal_amount ), $submission->get_currency() ),
1021
-                'discount'  => wpinv_price( wpinv_format_amount( $submission->get_total_discount() ), $submission->get_currency() ),
1022
-                'fees'      => wpinv_price( wpinv_format_amount( $submission->get_total_fees() ), $submission->get_currency() ),
1023
-                'tax'       => wpinv_price( wpinv_format_amount( $submission->get_total_tax() ), $submission->get_currency() ),
1024
-                'total'     => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
1020
+                'subtotal'  => wpinv_price(wpinv_format_amount($submission->subtotal_amount), $submission->get_currency()),
1021
+                'discount'  => wpinv_price(wpinv_format_amount($submission->get_total_discount()), $submission->get_currency()),
1022
+                'fees'      => wpinv_price(wpinv_format_amount($submission->get_total_fees()), $submission->get_currency()),
1023
+                'tax'       => wpinv_price(wpinv_format_amount($submission->get_total_tax()), $submission->get_currency()),
1024
+                'total'     => wpinv_price(wpinv_format_amount($submission->get_total()), $submission->get_currency()),
1025 1025
             ),
1026 1026
 
1027 1027
             'texts'         => array(
1028
-                '.getpaid-checkout-total-payable' => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
1028
+                '.getpaid-checkout-total-payable' => wpinv_price(wpinv_format_amount($submission->get_total()), $submission->get_currency()),
1029 1029
             )
1030 1030
 
1031 1031
         );
1032 1032
 
1033 1033
         // Add items.
1034 1034
         $items = $submission->get_items();
1035
-        if ( ! empty( $items ) ) {
1035
+        if (!empty($items)) {
1036 1036
             $result['items'] = array();
1037 1037
 
1038
-            foreach( $items as $item_id => $item ) {
1039
-                $result['items']["$item_id"] = wpinv_price( wpinv_format_amount( $item->get_price() * $item->get_quantity() ) );
1038
+            foreach ($items as $item_id => $item) {
1039
+                $result['items']["$item_id"] = wpinv_price(wpinv_format_amount($item->get_price() * $item->get_quantity()));
1040 1040
             }
1041 1041
         }
1042 1042
 
1043 1043
         // Add invoice.
1044
-        if ( $submission->has_invoice() ) {
1044
+        if ($submission->has_invoice()) {
1045 1045
             $result['invoice'] = $submission->get_invoice()->ID;
1046 1046
         }
1047 1047
 
1048 1048
         // Add discount code.
1049
-        if ( $submission->has_discount_code() ) {
1049
+        if ($submission->has_discount_code()) {
1050 1050
             $result['discount_code'] = $submission->get_discount_code();
1051 1051
         }
1052 1052
 
1053 1053
         // Filter the result.
1054
-        $result = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $result, $submission );
1054
+        $result = apply_filters('getpaid_payment_form_ajax_refresh_prices', $result, $submission);
1055 1055
 
1056
-        wp_send_json_success( $result );
1056
+        wp_send_json_success($result);
1057 1057
     }
1058 1058
 
1059 1059
     /**
@@ -1064,53 +1064,53 @@  discard block
 block discarded – undo
1064 1064
     public static function buy_items() {
1065 1065
         $user_id = get_current_user_id();
1066 1066
 
1067
-        if ( empty( $user_id ) ) { // If not logged in then lets redirect to the login page
1068
-            wp_send_json( array(
1069
-                'success' => wp_login_url( wp_get_referer() )
1070
-            ) );
1067
+        if (empty($user_id)) { // If not logged in then lets redirect to the login page
1068
+            wp_send_json(array(
1069
+                'success' => wp_login_url(wp_get_referer())
1070
+            ));
1071 1071
         } else {
1072 1072
             // Only check nonce if logged in as it could be cached when logged out.
1073
-            if ( ! isset( $_POST['wpinv_buy_nonce'] ) || ! wp_verify_nonce( $_POST['wpinv_buy_nonce'], 'wpinv_buy_items' ) ) {
1074
-                wp_send_json( array(
1075
-                    'error' => __( 'Security checks failed.', 'invoicing' )
1076
-                ) );
1073
+            if (!isset($_POST['wpinv_buy_nonce']) || !wp_verify_nonce($_POST['wpinv_buy_nonce'], 'wpinv_buy_items')) {
1074
+                wp_send_json(array(
1075
+                    'error' => __('Security checks failed.', 'invoicing')
1076
+                ));
1077 1077
                 wp_die();
1078 1078
             }
1079 1079
 
1080 1080
             // allow to set a custom price through post_id
1081 1081
             $items = $_POST['items'];
1082
-            $related_post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : 0;
1083
-            $custom_item_price = $related_post_id ? abs( get_post_meta( $related_post_id, '_wpi_custom_price', true ) ) : 0;
1082
+            $related_post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
1083
+            $custom_item_price = $related_post_id ? abs(get_post_meta($related_post_id, '_wpi_custom_price', true)) : 0;
1084 1084
 
1085 1085
             $cart_items = array();
1086
-            if ( $items ) {
1087
-                $items = explode( ',', $items );
1086
+            if ($items) {
1087
+                $items = explode(',', $items);
1088 1088
 
1089
-                foreach( $items as $item ) {
1089
+                foreach ($items as $item) {
1090 1090
                     $item_id = $item;
1091 1091
                     $quantity = 1;
1092 1092
 
1093
-                    if ( strpos( $item, '|' ) !== false ) {
1094
-                        $item_parts = explode( '|', $item );
1093
+                    if (strpos($item, '|') !== false) {
1094
+                        $item_parts = explode('|', $item);
1095 1095
                         $item_id = $item_parts[0];
1096 1096
                         $quantity = $item_parts[1];
1097 1097
                     }
1098 1098
 
1099
-                    if ( $item_id && $quantity ) {
1099
+                    if ($item_id && $quantity) {
1100 1100
                         $cart_items_arr = array(
1101
-                            'id'            => (int)$item_id,
1102
-                            'quantity'      => (int)$quantity
1101
+                            'id'            => (int) $item_id,
1102
+                            'quantity'      => (int) $quantity
1103 1103
                         );
1104 1104
 
1105 1105
                         // If there is a related post id then add it to meta
1106
-                        if ( $related_post_id ) {
1106
+                        if ($related_post_id) {
1107 1107
                             $cart_items_arr['meta'] = array(
1108 1108
                                 'post_id'   => $related_post_id
1109 1109
                             );
1110 1110
                         }
1111 1111
 
1112 1112
                         // If there is a custom price then set it.
1113
-                        if ( $custom_item_price ) {
1113
+                        if ($custom_item_price) {
1114 1114
                             $cart_items_arr['custom_price'] = $custom_item_price;
1115 1115
                         }
1116 1116
 
@@ -1126,37 +1126,37 @@  discard block
 block discarded – undo
1126 1126
              * @param int $related_post_id The related post id if any.
1127 1127
              * @since 1.0.0
1128 1128
              */
1129
-            $cart_items = apply_filters( 'wpinv_buy_cart_items', $cart_items, $related_post_id );
1129
+            $cart_items = apply_filters('wpinv_buy_cart_items', $cart_items, $related_post_id);
1130 1130
 
1131 1131
             // Make sure its not in the cart already, if it is then redirect to checkout.
1132 1132
             $cart_invoice = wpinv_get_invoice_cart();
1133 1133
 
1134
-            if ( isset( $cart_invoice->items ) && !empty( $cart_invoice->items ) && !empty( $cart_items ) && serialize( $cart_invoice->items ) == serialize( $cart_items ) ) {
1135
-                wp_send_json( array(
1134
+            if (isset($cart_invoice->items) && !empty($cart_invoice->items) && !empty($cart_items) && serialize($cart_invoice->items) == serialize($cart_items)) {
1135
+                wp_send_json(array(
1136 1136
                     'success' =>  $cart_invoice->get_checkout_payment_url()
1137
-                ) );
1137
+                ));
1138 1138
                 wp_die();
1139 1139
             }
1140 1140
 
1141 1141
             // Check if user has invoice with same items waiting to be paid.
1142
-            $user_invoices = wpinv_get_users_invoices( $user_id , 10 , false , 'wpi-pending' );
1143
-            if ( !empty( $user_invoices ) ) {
1144
-                foreach( $user_invoices as $user_invoice ) {
1142
+            $user_invoices = wpinv_get_users_invoices($user_id, 10, false, 'wpi-pending');
1143
+            if (!empty($user_invoices)) {
1144
+                foreach ($user_invoices as $user_invoice) {
1145 1145
                     $user_cart_details = array();
1146
-                    $invoice  = wpinv_get_invoice( $user_invoice->ID );
1146
+                    $invoice = wpinv_get_invoice($user_invoice->ID);
1147 1147
                     $cart_details = $invoice->get_cart_details();
1148 1148
 
1149
-                    if ( !empty( $cart_details ) ) {
1150
-                        foreach ( $cart_details as $invoice_item ) {
1149
+                    if (!empty($cart_details)) {
1150
+                        foreach ($cart_details as $invoice_item) {
1151 1151
                             $ii_arr = array();
1152
-                            $ii_arr['id'] = (int)$invoice_item['id'];
1153
-                            $ii_arr['quantity'] = (int)$invoice_item['quantity'];
1152
+                            $ii_arr['id'] = (int) $invoice_item['id'];
1153
+                            $ii_arr['quantity'] = (int) $invoice_item['quantity'];
1154 1154
 
1155
-                            if (isset( $invoice_item['meta'] ) && !empty( $invoice_item['meta'] ) ) {
1155
+                            if (isset($invoice_item['meta']) && !empty($invoice_item['meta'])) {
1156 1156
                                 $ii_arr['meta'] = $invoice_item['meta'];
1157 1157
                             }
1158 1158
 
1159
-                            if ( isset( $invoice_item['custom_price'] ) && !empty( $invoice_item['custom_price'] ) ) {
1159
+                            if (isset($invoice_item['custom_price']) && !empty($invoice_item['custom_price'])) {
1160 1160
                                 $ii_arr['custom_price'] = $invoice_item['custom_price'];
1161 1161
                             }
1162 1162
 
@@ -1164,17 +1164,17 @@  discard block
 block discarded – undo
1164 1164
                         }
1165 1165
                     }
1166 1166
 
1167
-                    if ( !empty( $user_cart_details ) && serialize( $cart_items ) == serialize( $user_cart_details ) ) {
1168
-                        wp_send_json( array(
1167
+                    if (!empty($user_cart_details) && serialize($cart_items) == serialize($user_cart_details)) {
1168
+                        wp_send_json(array(
1169 1169
                             'success' =>  $invoice->get_checkout_payment_url()
1170
-                        ) );
1170
+                        ));
1171 1171
                         wp_die();
1172 1172
                     }
1173 1173
                 }
1174 1174
             }
1175 1175
 
1176 1176
             // Create invoice and send user to checkout
1177
-            if ( !empty( $cart_items ) ) {
1177
+            if (!empty($cart_items)) {
1178 1178
                 $invoice_data = array(
1179 1179
                     'status'        =>  'wpi-pending',
1180 1180
                     'created_via'   =>  'wpi',
@@ -1182,21 +1182,21 @@  discard block
 block discarded – undo
1182 1182
                     'cart_details'  =>  $cart_items,
1183 1183
                 );
1184 1184
 
1185
-                $invoice = wpinv_insert_invoice( $invoice_data, true );
1185
+                $invoice = wpinv_insert_invoice($invoice_data, true);
1186 1186
 
1187
-                if ( !empty( $invoice ) && isset( $invoice->ID ) ) {
1188
-                    wp_send_json( array(
1187
+                if (!empty($invoice) && isset($invoice->ID)) {
1188
+                    wp_send_json(array(
1189 1189
                         'success' =>  $invoice->get_checkout_payment_url()
1190
-                    ) );
1190
+                    ));
1191 1191
                 } else {
1192
-                    wp_send_json( array(
1193
-                        'error' => __( 'Invoice failed to create', 'invoicing' )
1194
-                    ) );
1192
+                    wp_send_json(array(
1193
+                        'error' => __('Invoice failed to create', 'invoicing')
1194
+                    ));
1195 1195
                 }
1196 1196
             } else {
1197
-                wp_send_json( array(
1198
-                    'error' => __( 'Items not valid.', 'invoicing' )
1199
-                ) );
1197
+                wp_send_json(array(
1198
+                    'error' => __('Items not valid.', 'invoicing')
1199
+                ));
1200 1200
             }
1201 1201
         }
1202 1202
 
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-controller.php 2 patches
Indentation   +542 added lines, -542 removed lines patch added patch discarded remove patch
@@ -21,570 +21,570 @@
 block discarded – undo
21 21
  */
22 22
 class GetPaid_REST_Controller extends WP_REST_Controller {
23 23
 
24
-	/**
24
+    /**
25 25
      * The namespaces of this controller's route.
26 26
      *
27 27
      * @since 1.0.19
28 28
      * @var array
29 29
      */
30
-	protected $namespaces;
30
+    protected $namespaces;
31 31
 
32
-	/**
32
+    /**
33 33
      * The official namespace of this controller's route.
34 34
      *
35 35
      * @since 1.0.19
36 36
      * @var string
37 37
      */
38
-	protected $namespace = 'getpaid/v1';
38
+    protected $namespace = 'getpaid/v1';
39 39
 
40
-	/**
40
+    /**
41 41
      * Cached results of get_item_schema.
42 42
      *
43 43
      * @since 1.0.19
44 44
      * @var array
45 45
      */
46
-	protected $schema;
46
+    protected $schema;
47 47
 
48 48
     /**
49
-	 * Constructor.
50
-	 *
51
-	 * @since 1.0.19
52
-	 *
53
-	 */
54
-	public function __construct() {
55
-
56
-		// Offer several namespaces for backwards compatibility.
57
-		$this->namespaces = apply_filters(
58
-			'getpaid_rest_api_namespaces',
59
-			array(
60
-				'getpaid/v1',
61
-				'invoicing/v1',
62
-				'wpi/v1'
63
-			)
64
-		);
65
-
66
-		// Register REST routes.
49
+     * Constructor.
50
+     *
51
+     * @since 1.0.19
52
+     *
53
+     */
54
+    public function __construct() {
55
+
56
+        // Offer several namespaces for backwards compatibility.
57
+        $this->namespaces = apply_filters(
58
+            'getpaid_rest_api_namespaces',
59
+            array(
60
+                'getpaid/v1',
61
+                'invoicing/v1',
62
+                'wpi/v1'
63
+            )
64
+        );
65
+
66
+        // Register REST routes.
67 67
         add_action( 'rest_api_init', array( $this, 'register_routes' ) );
68 68
 
69
-	}
70
-
71
-	/**
72
-	 * Registers routes for each namespace.
73
-	 *
74
-	 * @since 1.0.19
75
-	 *
76
-	 */
77
-	public function register_routes() {
78
-
79
-		foreach ( $this->namespaces as $namespace ) {
80
-			$this->register_namespace_routes( $namespace );
81
-		}
82
-
83
-	}
84
-
85
-	/**
86
-	 * Registers routes for a namespace.
87
-	 *
88
-	 * @since 1.0.19
89
-	 *
90
-	 * @param string $namespace
91
-	 */
92
-	public function register_namespace_routes( /** @scrutinizer ignore-unused */ $namespace ) {
93
-
94
-		getpaid_doing_it_wrong(
95
-			__CLASS__ . '::' .__METHOD__,
96
-			/* translators: %s: register_namespace_routes() */
97
-			sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ),
98
-			'1.0.19'
99
-		);
100
-
101
-	}
102
-
103
-	/**
104
-	 * Get normalized rest base.
105
-	 *
106
-	 * @return string
107
-	 */
108
-	protected function get_normalized_rest_base() {
109
-		return preg_replace( '/\(.*\)\//i', '', $this->rest_base );
110
-	}
111
-
112
-	/**
113
-	 * Fill batches.
114
-	 *
115
-	 * @param array array of request items.
116
-	 * @return array
117
-	 */
118
-	protected function fill_batch_keys( $items ) {
119
-
120
-		$items['create'] = empty( $items['create'] ) ? array() : $items['create'];
121
-		$items['update'] = empty( $items['update'] ) ? array() : $items['update'];
122
-		$items['delete'] = empty( $items['delete'] ) ? array() : wp_parse_id_list( $items['delete'] );
123
-		return $items;
124
-
125
-	}
126
-
127
-	/**
128
-	 * Check batch limit.
129
-	 *
130
-	 * @param array $items Request items.
131
-	 * @return bool|WP_Error
132
-	 */
133
-	protected function check_batch_limit( $items ) {
134
-		$limit = apply_filters( 'getpaid_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
135
-		$total = count( $items['create'] ) + count( $items['update'] ) + count( $items['delete'] );
136
-
137
-		if ( $total > $limit ) {
138
-			/* translators: %s: items limit */
139
-			return new WP_Error( 'getpaid_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'invoicing' ), $limit ), array( 'status' => 413 ) );
140
-		}
141
-
142
-		return true;
143
-	}
144
-
145
-	/**
146
-	 * Bulk create items.
147
-	 *
148
-	 * @param array $items Array of items to create.
149
-	 * @param WP_REST_Request $request Full details about the request.
150
-	 * @param WP_REST_Server $wp_rest_server
151
-	 * @return array()
152
-	 */
153
-	protected function batch_create_items( $items, $request, $wp_rest_server ) {
154
-
155
-		$query  = $request->get_query_params();
156
-		$create = array();
157
-
158
-		foreach ( $items as $item ) {
159
-			$_item = new WP_REST_Request( 'POST' );
160
-
161
-			// Default parameters.
162
-			$defaults = array();
163
-			$schema   = $this->get_public_item_schema();
164
-			foreach ( $schema['properties'] as $arg => $options ) {
165
-				if ( isset( $options['default'] ) ) {
166
-					$defaults[ $arg ] = $options['default'];
167
-				}
168
-			}
169
-			$_item->set_default_params( $defaults );
170
-
171
-			// Set request parameters.
172
-			$_item->set_body_params( $item );
173
-
174
-			// Set query (GET) parameters.
175
-			$_item->set_query_params( $query );
176
-
177
-			// Create the item.
178
-			$_response = $this->create_item( $_item );
179
-
180
-			// If an error occured...
181
-			if ( is_wp_error( $_response ) ) {
182
-
183
-				$create[]   = array(
184
-					'id'    => 0,
185
-					'error' => array(
186
-						'code'    => $_response->get_error_code(),
187
-						'message' => $_response->get_error_message(),
188
-						'data'    => $_response->get_error_data(),
189
-					),
190
-				);
191
-
192
-				continue;
193
-			}
194
-
195
-			$create[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
196
-
197
-		}
198
-
199
-		return $create;
69
+    }
70
+
71
+    /**
72
+     * Registers routes for each namespace.
73
+     *
74
+     * @since 1.0.19
75
+     *
76
+     */
77
+    public function register_routes() {
78
+
79
+        foreach ( $this->namespaces as $namespace ) {
80
+            $this->register_namespace_routes( $namespace );
81
+        }
82
+
83
+    }
84
+
85
+    /**
86
+     * Registers routes for a namespace.
87
+     *
88
+     * @since 1.0.19
89
+     *
90
+     * @param string $namespace
91
+     */
92
+    public function register_namespace_routes( /** @scrutinizer ignore-unused */ $namespace ) {
93
+
94
+        getpaid_doing_it_wrong(
95
+            __CLASS__ . '::' .__METHOD__,
96
+            /* translators: %s: register_namespace_routes() */
97
+            sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ),
98
+            '1.0.19'
99
+        );
100
+
101
+    }
102
+
103
+    /**
104
+     * Get normalized rest base.
105
+     *
106
+     * @return string
107
+     */
108
+    protected function get_normalized_rest_base() {
109
+        return preg_replace( '/\(.*\)\//i', '', $this->rest_base );
110
+    }
111
+
112
+    /**
113
+     * Fill batches.
114
+     *
115
+     * @param array array of request items.
116
+     * @return array
117
+     */
118
+    protected function fill_batch_keys( $items ) {
119
+
120
+        $items['create'] = empty( $items['create'] ) ? array() : $items['create'];
121
+        $items['update'] = empty( $items['update'] ) ? array() : $items['update'];
122
+        $items['delete'] = empty( $items['delete'] ) ? array() : wp_parse_id_list( $items['delete'] );
123
+        return $items;
124
+
125
+    }
126
+
127
+    /**
128
+     * Check batch limit.
129
+     *
130
+     * @param array $items Request items.
131
+     * @return bool|WP_Error
132
+     */
133
+    protected function check_batch_limit( $items ) {
134
+        $limit = apply_filters( 'getpaid_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
135
+        $total = count( $items['create'] ) + count( $items['update'] ) + count( $items['delete'] );
136
+
137
+        if ( $total > $limit ) {
138
+            /* translators: %s: items limit */
139
+            return new WP_Error( 'getpaid_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'invoicing' ), $limit ), array( 'status' => 413 ) );
140
+        }
141
+
142
+        return true;
143
+    }
144
+
145
+    /**
146
+     * Bulk create items.
147
+     *
148
+     * @param array $items Array of items to create.
149
+     * @param WP_REST_Request $request Full details about the request.
150
+     * @param WP_REST_Server $wp_rest_server
151
+     * @return array()
152
+     */
153
+    protected function batch_create_items( $items, $request, $wp_rest_server ) {
154
+
155
+        $query  = $request->get_query_params();
156
+        $create = array();
157
+
158
+        foreach ( $items as $item ) {
159
+            $_item = new WP_REST_Request( 'POST' );
160
+
161
+            // Default parameters.
162
+            $defaults = array();
163
+            $schema   = $this->get_public_item_schema();
164
+            foreach ( $schema['properties'] as $arg => $options ) {
165
+                if ( isset( $options['default'] ) ) {
166
+                    $defaults[ $arg ] = $options['default'];
167
+                }
168
+            }
169
+            $_item->set_default_params( $defaults );
170
+
171
+            // Set request parameters.
172
+            $_item->set_body_params( $item );
173
+
174
+            // Set query (GET) parameters.
175
+            $_item->set_query_params( $query );
176
+
177
+            // Create the item.
178
+            $_response = $this->create_item( $_item );
179
+
180
+            // If an error occured...
181
+            if ( is_wp_error( $_response ) ) {
182
+
183
+                $create[]   = array(
184
+                    'id'    => 0,
185
+                    'error' => array(
186
+                        'code'    => $_response->get_error_code(),
187
+                        'message' => $_response->get_error_message(),
188
+                        'data'    => $_response->get_error_data(),
189
+                    ),
190
+                );
191
+
192
+                continue;
193
+            }
194
+
195
+            $create[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
196
+
197
+        }
198
+
199
+        return $create;
200
+
201
+    }
202
+
203
+    /**
204
+     * Bulk update items.
205
+     *
206
+     * @param array $items Array of items to update.
207
+     * @param WP_REST_Request $request Full details about the request.
208
+     * @param WP_REST_Server $wp_rest_server
209
+     * @return array()
210
+     */
211
+    protected function batch_update_items( $items, $request, $wp_rest_server ) {
212
+
213
+        $query  = $request->get_query_params();
214
+        $update = array();
215
+
216
+        foreach ( $items as $item ) {
217
+
218
+            // Create a dummy request.
219
+            $_item = new WP_REST_Request( 'PUT' );
220
+
221
+            // Add body params.
222
+            $_item->set_body_params( $item );
223
+
224
+            // Set query (GET) parameters.
225
+            $_item->set_query_params( $query );
226
+
227
+            // Update the item.
228
+            $_response = $this->update_item( $_item );
229
+
230
+            // If an error occured...
231
+            if ( is_wp_error( $_response ) ) {
232
+
233
+                $update[] = array(
234
+                    'id'    => $item['id'],
235
+                    'error' => array(
236
+                        'code'    => $_response->get_error_code(),
237
+                        'message' => $_response->get_error_message(),
238
+                        'data'    => $_response->get_error_data(),
239
+                    ),
240
+                );
241
+
242
+                continue;
243
+
244
+            }
245
+
246
+            $update[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
247
+
248
+        }
249
+
250
+        return $update;
251
+
252
+    }
253
+
254
+    /**
255
+     * Bulk delete items.
256
+     *
257
+     * @param array $items Array of items to delete.
258
+     * @param WP_REST_Server $wp_rest_server
259
+     * @return array()
260
+     */
261
+    protected function batch_delete_items( $items, $wp_rest_server ) {
262
+
263
+        $delete = array();
264
+
265
+        foreach ( array_filter( $items ) as $id ) {
266
+
267
+            // Prepare the request.
268
+            $_item = new WP_REST_Request( 'DELETE' );
269
+            $_item->set_query_params(
270
+                array(
271
+                    'id'    => $id,
272
+                    'force' => true,
273
+                )
274
+            );
275
+
276
+            // Delete the item.
277
+            $_response = $this->delete_item( $_item );
278
+
279
+            if ( is_wp_error( $_response ) ) {
280
+
281
+                $delete[] = array(
282
+                    'id'    => $id,
283
+                    'error' => array(
284
+                        'code'    => $_response->get_error_code(),
285
+                        'message' => $_response->get_error_message(),
286
+                        'data'    => $_response->get_error_data(),
287
+                    ),
288
+                );
289
+
290
+                continue;
291
+            }
200 292
 
201
-	}
202
-
203
-	/**
204
-	 * Bulk update items.
205
-	 *
206
-	 * @param array $items Array of items to update.
207
-	 * @param WP_REST_Request $request Full details about the request.
208
-	 * @param WP_REST_Server $wp_rest_server
209
-	 * @return array()
210
-	 */
211
-	protected function batch_update_items( $items, $request, $wp_rest_server ) {
212
-
213
-		$query  = $request->get_query_params();
214
-		$update = array();
215
-
216
-		foreach ( $items as $item ) {
217
-
218
-			// Create a dummy request.
219
-			$_item = new WP_REST_Request( 'PUT' );
220
-
221
-			// Add body params.
222
-			$_item->set_body_params( $item );
223
-
224
-			// Set query (GET) parameters.
225
-			$_item->set_query_params( $query );
226
-
227
-			// Update the item.
228
-			$_response = $this->update_item( $_item );
229
-
230
-			// If an error occured...
231
-			if ( is_wp_error( $_response ) ) {
232
-
233
-				$update[] = array(
234
-					'id'    => $item['id'],
235
-					'error' => array(
236
-						'code'    => $_response->get_error_code(),
237
-						'message' => $_response->get_error_message(),
238
-						'data'    => $_response->get_error_data(),
239
-					),
240
-				);
241
-
242
-				continue;
243
-
244
-			}
245
-
246
-			$update[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
247
-
248
-		}
249
-
250
-		return $update;
251
-
252
-	}
293
+            $delete[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
253 294
 
254
-	/**
255
-	 * Bulk delete items.
256
-	 *
257
-	 * @param array $items Array of items to delete.
258
-	 * @param WP_REST_Server $wp_rest_server
259
-	 * @return array()
260
-	 */
261
-	protected function batch_delete_items( $items, $wp_rest_server ) {
262
-
263
-		$delete = array();
264
-
265
-		foreach ( array_filter( $items ) as $id ) {
266
-
267
-			// Prepare the request.
268
-			$_item = new WP_REST_Request( 'DELETE' );
269
-			$_item->set_query_params(
270
-				array(
271
-					'id'    => $id,
272
-					'force' => true,
273
-				)
274
-			);
275
-
276
-			// Delete the item.
277
-			$_response = $this->delete_item( $_item );
278
-
279
-			if ( is_wp_error( $_response ) ) {
280
-
281
-				$delete[] = array(
282
-					'id'    => $id,
283
-					'error' => array(
284
-						'code'    => $_response->get_error_code(),
285
-						'message' => $_response->get_error_message(),
286
-						'data'    => $_response->get_error_data(),
287
-					),
288
-				);
289
-
290
-				continue;
291
-			}
292
-
293
-			$delete[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
294
-
295
-		}
296
-
297
-		return $delete;
298
-
299
-	}
300
-
301
-	/**
302
-	 * Bulk create, update and delete items.
303
-	 *
304
-	 * @param WP_REST_Request $request Full details about the request.
305
-	 * @return WP_Error|array.
306
-	 */
307
-	public function batch_items( $request ) {
308
-		global $wp_rest_server;
309
-
310
-		// Prepare the batch items.
311
-		$items = $this->fill_batch_keys( array_filter( $request->get_params() ) );
312
-
313
-		// Ensure that the batch has not exceeded the limit to prevent abuse.
314
-		$limit = $this->check_batch_limit( $items );
315
-		if ( is_wp_error( $limit ) ) {
316
-			return $limit;
317
-		}
318
-
319
-		// Process the items.
320
-		return array(
321
-			'create' => $this->batch_create_items( $items['create'], $request, $wp_rest_server ),
322
-			'update' => $this->batch_update_items( $items['update'], $request, $wp_rest_server ),
323
-			'delete' => $this->batch_delete_items( $items['delete'], $wp_rest_server ),
324
-		);
325
-
326
-	}
327
-
328
-	/**
329
-	 * Add meta query.
330
-	 *
331
-	 * @since 1.0.19
332
-	 * @param array $args       Query args.
333
-	 * @param array $meta_query Meta query.
334
-	 * @return array
335
-	 */
336
-	protected function add_meta_query( $args, $meta_query ) {
337
-		if ( empty( $args['meta_query'] ) ) {
338
-			$args['meta_query'] = array();
339
-		}
340
-
341
-		$args['meta_query'][] = $meta_query;
342
-
343
-		return $args['meta_query'];
344
-	}
345
-
346
-	/**
347
-	 * Get the batch schema, conforming to JSON Schema.
348
-	 *
349
-	 * @return array
350
-	 */
351
-	public function get_public_batch_schema() {
352
-
353
-		return array(
354
-			'$schema'    => 'http://json-schema.org/draft-04/schema#',
355
-			'title'      => 'batch',
356
-			'type'       => 'object',
357
-			'properties' => array(
358
-				'create' => array(
359
-					'description' => __( 'List of created resources.', 'invoicing' ),
360
-					'type'        => 'array',
361
-					'context'     => array( 'view', 'edit' ),
362
-					'items'       => array(
363
-						'type'    => 'object',
364
-					),
365
-				),
366
-				'update' => array(
367
-					'description' => __( 'List of updated resources.', 'invoicing' ),
368
-					'type'        => 'array',
369
-					'context'     => array( 'view', 'edit' ),
370
-					'items'       => array(
371
-						'type'    => 'object',
372
-					),
373
-				),
374
-				'delete' => array(
375
-					'description' => __( 'List of deleted resources.', 'invoicing' ),
376
-					'type'        => 'array',
377
-					'context'     => array( 'view', 'edit' ),
378
-					'items'       => array(
379
-						'type'    => 'integer',
380
-					),
381
-				),
382
-			),
383
-		);
384
-
385
-	}
386
-
387
-	/**
388
-	 * Returns the value of schema['properties']
389
-	 * 
390
-	 * i.e Schema fields.
391
-	 *
392
-	 * @since 1.0.19
393
-	 * @return array
394
-	 */
395
-	protected function get_schema_properties() {
396
-
397
-		$schema     = $this->get_item_schema();
398
-		$properties = isset( $schema['properties'] ) ? $schema['properties'] : array();
399
-
400
-		// For back-compat, include any field with an empty schema
401
-		// because it won't be present in $this->get_item_schema().
402
-		foreach ( $this->get_additional_fields() as $field_name => $field_options ) {
403
-			if ( is_null( $field_options['schema'] ) ) {
404
-				$properties[ $field_name ] = $field_options;
405
-			}
406
-		}
407
-
408
-		return $properties;
409
-	}
410
-
411
-	/**
412
-	 * Filters fields by context.
413
-	 *
414
-	 * @param array $fields Array of fields
415
-	 * @param string|null context view, edit or embed
416
-	 * @since 1.0.19
417
-	 * @return array
418
-	 */
419
-	protected function filter_response_fields_by_context( $fields, $context ) {
420
-
421
-		if ( empty( $context ) ) {
422
-			return $fields;
423
-		}
424
-
425
-		foreach ( $fields as $name => $options ) {
426
-			if ( ! empty( $options['context'] ) && ! in_array( $context, $options['context'], true ) ) {
427
-				unset( $fields[ $name ] );
428
-			}
429
-		}
430
-
431
-		return $fields;
432
-
433
-	}
434
-
435
-	/**
436
-	 * Filters fields by an array of requested fields.
437
-	 *
438
-	 * @param array $fields Array of available fields
439
-	 * @param array $requested array of requested fields.
440
-	 * @since 1.0.19
441
-	 * @return array
442
-	 */
443
-	protected function filter_response_fields_by_array( $fields, $requested ) {
444
-
445
-		// Trim off any whitespace from the list array.
446
-		$requested = array_map( 'trim', $requested );
447
-
448
-		// Always persist 'id', because it can be needed for add_additional_fields_to_object().
449
-		if ( in_array( 'id', $fields, true ) ) {
450
-			$requested[] = 'id';
451
-		}
452
-
453
-		// Get rid of duplicate fields.
454
-		$requested = array_unique( $requested );
455
-
456
-		// Return the list of all included fields which are available.
457
-		return array_reduce(
458
-			$requested,
459
-			function( $response_fields, $field ) use ( $fields ) {
460
-
461
-				if ( in_array( $field, $fields, true ) ) {
462
-					$response_fields[] = $field;
463
-					return $response_fields;
464
-				}
465
-
466
-				// Check for nested fields if $field is not a direct match.
467
-				$nested_fields = explode( '.', $field );
468
-
469
-				// A nested field is included so long as its top-level property is
470
-				// present in the schema.
471
-				if ( in_array( $nested_fields[0], $fields, true ) ) {
472
-					$response_fields[] = $field;
473
-				}
474
-
475
-				return $response_fields;
476
-			},
477
-			array()
478
-		);
479
-
480
-	}
481
-
482
-	/**
483
-	 * Gets an array of fields to be included on the response.
484
-	 *
485
-	 * Included fields are based on item schema and `_fields=` request argument.
486
-	 * Copied from WordPress 5.3 to support old versions.
487
-	 *
488
-	 * @since 1.0.19
489
-	 * @param WP_REST_Request $request Full details about the request.
490
-	 * @return array Fields to be included in the response.
491
-	 */
492
-	public function get_fields_for_response( $request ) {
493
-
494
-		// Retrieve fields in the schema.
495
-		$properties = $this->get_schema_properties();
496
-
497
-		// Exclude fields that specify a different context than the request context.
498
-		$properties = $this->filter_response_fields_by_context( $properties, $request['context'] );
499
-
500
-		// We only need the field keys.
501
-		$fields = array_keys( $properties );
502
-
503
-		// Is the user filtering the response fields??
504
-		if ( empty( $request['_fields'] ) ) {
505
-			return $fields;
506
-		}
507
-
508
-		return $this->filter_response_fields_by_array( $fields, wpinv_parse_list( $request['_fields'] ) );
509
-
510
-	}
511
-
512
-	/**
513
-	 * Limits an object to the requested fields.
514
-	 *
515
-	 * Included fields are based on the `_fields` request argument.
516
-	 *
517
-	 * @since 1.0.19
518
-	 * @param array $data Fields to include in the response.
519
-	 * @param array $fields Requested fields.
520
-	 * @return array Fields to be included in the response.
521
-	 */
522
-	public function limit_object_to_requested_fields( $data, $fields, $prefix = '' ) {
523
-
524
-		// Is the user filtering the response fields??
525
-		if ( empty( $fields ) ) {
526
-			return $data;
527
-		}
528
-
529
-		foreach ( $data as $key => $value ) {
530
-
531
-			// Numeric arrays.
532
-			if ( is_numeric( $key ) && is_array( $value ) ) {
533
-				$data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $prefix );
534
-				continue;
535
-			}
536
-
537
-			// Generate a new prefix.
538
-			$new_prefix = empty( $prefix ) ? $key : "$prefix.$key";
539
-
540
-			// Check if it was requested.
541
-			if ( ! empty( $key ) && ! $this->is_field_included( $new_prefix, $fields ) ) {
542
-				unset( $data[ $key ] );
543
-				continue;
544
-			}
545
-
546
-			if ( $key != 'meta_data' && is_array( $value ) ) {
547
-				$data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $new_prefix );
548
-			}
549
-
550
-		}
551
-
552
-		return $data;
553
-	}
554
-
555
-	/**
556
-	 * Given an array of fields to include in a response, some of which may be
557
-	 * `nested.fields`, determine whether the provided field should be included
558
-	 * in the response body.
559
-	 *
560
-	 * Copied from WordPress 5.3 to support old versions.
561
-	 *
562
-	 * @since 1.0.19
563
-	 *
564
-	 * @param string $field  A field to test for inclusion in the response body.
565
-	 * @param array  $fields An array of string fields supported by the endpoint.
566
-	 * @return bool Whether to include the field or not.
567
-	 * @see rest_is_field_included()
568
-	 */
569
-	public function is_field_included( $field, $fields ) {
570
-		if ( in_array( $field, $fields, true ) ) {
571
-			return true;
572
-		}
573
-
574
-		foreach ( $fields as $accepted_field ) {
575
-			// Check to see if $field is the parent of any item in $fields.
576
-			// A field "parent" should be accepted if "parent.child" is accepted.
577
-			if ( strpos( $accepted_field, "$field." ) === 0 ) {
578
-				return true;
579
-			}
580
-			// Conversely, if "parent" is accepted, all "parent.child" fields
581
-			// should also be accepted.
582
-			if ( strpos( $field, "$accepted_field." ) === 0 ) {
583
-				return true;
584
-			}
585
-		}
586
-
587
-		return false;
588
-	}
295
+        }
296
+
297
+        return $delete;
298
+
299
+    }
300
+
301
+    /**
302
+     * Bulk create, update and delete items.
303
+     *
304
+     * @param WP_REST_Request $request Full details about the request.
305
+     * @return WP_Error|array.
306
+     */
307
+    public function batch_items( $request ) {
308
+        global $wp_rest_server;
309
+
310
+        // Prepare the batch items.
311
+        $items = $this->fill_batch_keys( array_filter( $request->get_params() ) );
312
+
313
+        // Ensure that the batch has not exceeded the limit to prevent abuse.
314
+        $limit = $this->check_batch_limit( $items );
315
+        if ( is_wp_error( $limit ) ) {
316
+            return $limit;
317
+        }
318
+
319
+        // Process the items.
320
+        return array(
321
+            'create' => $this->batch_create_items( $items['create'], $request, $wp_rest_server ),
322
+            'update' => $this->batch_update_items( $items['update'], $request, $wp_rest_server ),
323
+            'delete' => $this->batch_delete_items( $items['delete'], $wp_rest_server ),
324
+        );
325
+
326
+    }
327
+
328
+    /**
329
+     * Add meta query.
330
+     *
331
+     * @since 1.0.19
332
+     * @param array $args       Query args.
333
+     * @param array $meta_query Meta query.
334
+     * @return array
335
+     */
336
+    protected function add_meta_query( $args, $meta_query ) {
337
+        if ( empty( $args['meta_query'] ) ) {
338
+            $args['meta_query'] = array();
339
+        }
340
+
341
+        $args['meta_query'][] = $meta_query;
342
+
343
+        return $args['meta_query'];
344
+    }
345
+
346
+    /**
347
+     * Get the batch schema, conforming to JSON Schema.
348
+     *
349
+     * @return array
350
+     */
351
+    public function get_public_batch_schema() {
352
+
353
+        return array(
354
+            '$schema'    => 'http://json-schema.org/draft-04/schema#',
355
+            'title'      => 'batch',
356
+            'type'       => 'object',
357
+            'properties' => array(
358
+                'create' => array(
359
+                    'description' => __( 'List of created resources.', 'invoicing' ),
360
+                    'type'        => 'array',
361
+                    'context'     => array( 'view', 'edit' ),
362
+                    'items'       => array(
363
+                        'type'    => 'object',
364
+                    ),
365
+                ),
366
+                'update' => array(
367
+                    'description' => __( 'List of updated resources.', 'invoicing' ),
368
+                    'type'        => 'array',
369
+                    'context'     => array( 'view', 'edit' ),
370
+                    'items'       => array(
371
+                        'type'    => 'object',
372
+                    ),
373
+                ),
374
+                'delete' => array(
375
+                    'description' => __( 'List of deleted resources.', 'invoicing' ),
376
+                    'type'        => 'array',
377
+                    'context'     => array( 'view', 'edit' ),
378
+                    'items'       => array(
379
+                        'type'    => 'integer',
380
+                    ),
381
+                ),
382
+            ),
383
+        );
384
+
385
+    }
386
+
387
+    /**
388
+     * Returns the value of schema['properties']
389
+     * 
390
+     * i.e Schema fields.
391
+     *
392
+     * @since 1.0.19
393
+     * @return array
394
+     */
395
+    protected function get_schema_properties() {
396
+
397
+        $schema     = $this->get_item_schema();
398
+        $properties = isset( $schema['properties'] ) ? $schema['properties'] : array();
399
+
400
+        // For back-compat, include any field with an empty schema
401
+        // because it won't be present in $this->get_item_schema().
402
+        foreach ( $this->get_additional_fields() as $field_name => $field_options ) {
403
+            if ( is_null( $field_options['schema'] ) ) {
404
+                $properties[ $field_name ] = $field_options;
405
+            }
406
+        }
407
+
408
+        return $properties;
409
+    }
410
+
411
+    /**
412
+     * Filters fields by context.
413
+     *
414
+     * @param array $fields Array of fields
415
+     * @param string|null context view, edit or embed
416
+     * @since 1.0.19
417
+     * @return array
418
+     */
419
+    protected function filter_response_fields_by_context( $fields, $context ) {
420
+
421
+        if ( empty( $context ) ) {
422
+            return $fields;
423
+        }
424
+
425
+        foreach ( $fields as $name => $options ) {
426
+            if ( ! empty( $options['context'] ) && ! in_array( $context, $options['context'], true ) ) {
427
+                unset( $fields[ $name ] );
428
+            }
429
+        }
430
+
431
+        return $fields;
432
+
433
+    }
434
+
435
+    /**
436
+     * Filters fields by an array of requested fields.
437
+     *
438
+     * @param array $fields Array of available fields
439
+     * @param array $requested array of requested fields.
440
+     * @since 1.0.19
441
+     * @return array
442
+     */
443
+    protected function filter_response_fields_by_array( $fields, $requested ) {
444
+
445
+        // Trim off any whitespace from the list array.
446
+        $requested = array_map( 'trim', $requested );
447
+
448
+        // Always persist 'id', because it can be needed for add_additional_fields_to_object().
449
+        if ( in_array( 'id', $fields, true ) ) {
450
+            $requested[] = 'id';
451
+        }
452
+
453
+        // Get rid of duplicate fields.
454
+        $requested = array_unique( $requested );
455
+
456
+        // Return the list of all included fields which are available.
457
+        return array_reduce(
458
+            $requested,
459
+            function( $response_fields, $field ) use ( $fields ) {
460
+
461
+                if ( in_array( $field, $fields, true ) ) {
462
+                    $response_fields[] = $field;
463
+                    return $response_fields;
464
+                }
465
+
466
+                // Check for nested fields if $field is not a direct match.
467
+                $nested_fields = explode( '.', $field );
468
+
469
+                // A nested field is included so long as its top-level property is
470
+                // present in the schema.
471
+                if ( in_array( $nested_fields[0], $fields, true ) ) {
472
+                    $response_fields[] = $field;
473
+                }
474
+
475
+                return $response_fields;
476
+            },
477
+            array()
478
+        );
479
+
480
+    }
481
+
482
+    /**
483
+     * Gets an array of fields to be included on the response.
484
+     *
485
+     * Included fields are based on item schema and `_fields=` request argument.
486
+     * Copied from WordPress 5.3 to support old versions.
487
+     *
488
+     * @since 1.0.19
489
+     * @param WP_REST_Request $request Full details about the request.
490
+     * @return array Fields to be included in the response.
491
+     */
492
+    public function get_fields_for_response( $request ) {
493
+
494
+        // Retrieve fields in the schema.
495
+        $properties = $this->get_schema_properties();
496
+
497
+        // Exclude fields that specify a different context than the request context.
498
+        $properties = $this->filter_response_fields_by_context( $properties, $request['context'] );
499
+
500
+        // We only need the field keys.
501
+        $fields = array_keys( $properties );
502
+
503
+        // Is the user filtering the response fields??
504
+        if ( empty( $request['_fields'] ) ) {
505
+            return $fields;
506
+        }
507
+
508
+        return $this->filter_response_fields_by_array( $fields, wpinv_parse_list( $request['_fields'] ) );
509
+
510
+    }
511
+
512
+    /**
513
+     * Limits an object to the requested fields.
514
+     *
515
+     * Included fields are based on the `_fields` request argument.
516
+     *
517
+     * @since 1.0.19
518
+     * @param array $data Fields to include in the response.
519
+     * @param array $fields Requested fields.
520
+     * @return array Fields to be included in the response.
521
+     */
522
+    public function limit_object_to_requested_fields( $data, $fields, $prefix = '' ) {
523
+
524
+        // Is the user filtering the response fields??
525
+        if ( empty( $fields ) ) {
526
+            return $data;
527
+        }
528
+
529
+        foreach ( $data as $key => $value ) {
530
+
531
+            // Numeric arrays.
532
+            if ( is_numeric( $key ) && is_array( $value ) ) {
533
+                $data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $prefix );
534
+                continue;
535
+            }
536
+
537
+            // Generate a new prefix.
538
+            $new_prefix = empty( $prefix ) ? $key : "$prefix.$key";
539
+
540
+            // Check if it was requested.
541
+            if ( ! empty( $key ) && ! $this->is_field_included( $new_prefix, $fields ) ) {
542
+                unset( $data[ $key ] );
543
+                continue;
544
+            }
545
+
546
+            if ( $key != 'meta_data' && is_array( $value ) ) {
547
+                $data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $new_prefix );
548
+            }
549
+
550
+        }
551
+
552
+        return $data;
553
+    }
554
+
555
+    /**
556
+     * Given an array of fields to include in a response, some of which may be
557
+     * `nested.fields`, determine whether the provided field should be included
558
+     * in the response body.
559
+     *
560
+     * Copied from WordPress 5.3 to support old versions.
561
+     *
562
+     * @since 1.0.19
563
+     *
564
+     * @param string $field  A field to test for inclusion in the response body.
565
+     * @param array  $fields An array of string fields supported by the endpoint.
566
+     * @return bool Whether to include the field or not.
567
+     * @see rest_is_field_included()
568
+     */
569
+    public function is_field_included( $field, $fields ) {
570
+        if ( in_array( $field, $fields, true ) ) {
571
+            return true;
572
+        }
573
+
574
+        foreach ( $fields as $accepted_field ) {
575
+            // Check to see if $field is the parent of any item in $fields.
576
+            // A field "parent" should be accepted if "parent.child" is accepted.
577
+            if ( strpos( $accepted_field, "$field." ) === 0 ) {
578
+                return true;
579
+            }
580
+            // Conversely, if "parent" is accepted, all "parent.child" fields
581
+            // should also be accepted.
582
+            if ( strpos( $field, "$accepted_field." ) === 0 ) {
583
+                return true;
584
+            }
585
+        }
586
+
587
+        return false;
588
+    }
589 589
 
590 590
 }
Please login to merge, or discard this patch.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  * @version 1.0.19
9 9
  */
10 10
 
11
-defined( 'ABSPATH' ) || exit;
11
+defined('ABSPATH') || exit;
12 12
 
13 13
 /**
14 14
  * Core class to access posts via the REST API.
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		);
65 65
 
66 66
 		// Register REST routes.
67
-        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
67
+        add_action('rest_api_init', array($this, 'register_routes'));
68 68
 
69 69
 	}
70 70
 
@@ -76,8 +76,8 @@  discard block
 block discarded – undo
76 76
 	 */
77 77
 	public function register_routes() {
78 78
 
79
-		foreach ( $this->namespaces as $namespace ) {
80
-			$this->register_namespace_routes( $namespace );
79
+		foreach ($this->namespaces as $namespace) {
80
+			$this->register_namespace_routes($namespace);
81 81
 		}
82 82
 
83 83
 	}
@@ -89,12 +89,12 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @param string $namespace
91 91
 	 */
92
-	public function register_namespace_routes( /** @scrutinizer ignore-unused */ $namespace ) {
92
+	public function register_namespace_routes(/** @scrutinizer ignore-unused */ $namespace) {
93 93
 
94 94
 		getpaid_doing_it_wrong(
95
-			__CLASS__ . '::' .__METHOD__,
95
+			__CLASS__ . '::' . __METHOD__,
96 96
 			/* translators: %s: register_namespace_routes() */
97
-			sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ),
97
+			sprintf(__("Method '%s' must be overridden."), __METHOD__),
98 98
 			'1.0.19'
99 99
 		);
100 100
 
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	 * @return string
107 107
 	 */
108 108
 	protected function get_normalized_rest_base() {
109
-		return preg_replace( '/\(.*\)\//i', '', $this->rest_base );
109
+		return preg_replace('/\(.*\)\//i', '', $this->rest_base);
110 110
 	}
111 111
 
112 112
 	/**
@@ -115,11 +115,11 @@  discard block
 block discarded – undo
115 115
 	 * @param array array of request items.
116 116
 	 * @return array
117 117
 	 */
118
-	protected function fill_batch_keys( $items ) {
118
+	protected function fill_batch_keys($items) {
119 119
 
120
-		$items['create'] = empty( $items['create'] ) ? array() : $items['create'];
121
-		$items['update'] = empty( $items['update'] ) ? array() : $items['update'];
122
-		$items['delete'] = empty( $items['delete'] ) ? array() : wp_parse_id_list( $items['delete'] );
120
+		$items['create'] = empty($items['create']) ? array() : $items['create'];
121
+		$items['update'] = empty($items['update']) ? array() : $items['update'];
122
+		$items['delete'] = empty($items['delete']) ? array() : wp_parse_id_list($items['delete']);
123 123
 		return $items;
124 124
 
125 125
 	}
@@ -130,13 +130,13 @@  discard block
 block discarded – undo
130 130
 	 * @param array $items Request items.
131 131
 	 * @return bool|WP_Error
132 132
 	 */
133
-	protected function check_batch_limit( $items ) {
134
-		$limit = apply_filters( 'getpaid_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
135
-		$total = count( $items['create'] ) + count( $items['update'] ) + count( $items['delete'] );
133
+	protected function check_batch_limit($items) {
134
+		$limit = apply_filters('getpaid_rest_batch_items_limit', 100, $this->get_normalized_rest_base());
135
+		$total = count($items['create']) + count($items['update']) + count($items['delete']);
136 136
 
137
-		if ( $total > $limit ) {
137
+		if ($total > $limit) {
138 138
 			/* translators: %s: items limit */
139
-			return new WP_Error( 'getpaid_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'invoicing' ), $limit ), array( 'status' => 413 ) );
139
+			return new WP_Error('getpaid_rest_request_entity_too_large', sprintf(__('Unable to accept more than %s items for this request.', 'invoicing'), $limit), array('status' => 413));
140 140
 		}
141 141
 
142 142
 		return true;
@@ -150,37 +150,37 @@  discard block
 block discarded – undo
150 150
 	 * @param WP_REST_Server $wp_rest_server
151 151
 	 * @return array()
152 152
 	 */
153
-	protected function batch_create_items( $items, $request, $wp_rest_server ) {
153
+	protected function batch_create_items($items, $request, $wp_rest_server) {
154 154
 
155 155
 		$query  = $request->get_query_params();
156 156
 		$create = array();
157 157
 
158
-		foreach ( $items as $item ) {
159
-			$_item = new WP_REST_Request( 'POST' );
158
+		foreach ($items as $item) {
159
+			$_item = new WP_REST_Request('POST');
160 160
 
161 161
 			// Default parameters.
162 162
 			$defaults = array();
163 163
 			$schema   = $this->get_public_item_schema();
164
-			foreach ( $schema['properties'] as $arg => $options ) {
165
-				if ( isset( $options['default'] ) ) {
166
-					$defaults[ $arg ] = $options['default'];
164
+			foreach ($schema['properties'] as $arg => $options) {
165
+				if (isset($options['default'])) {
166
+					$defaults[$arg] = $options['default'];
167 167
 				}
168 168
 			}
169
-			$_item->set_default_params( $defaults );
169
+			$_item->set_default_params($defaults);
170 170
 
171 171
 			// Set request parameters.
172
-			$_item->set_body_params( $item );
172
+			$_item->set_body_params($item);
173 173
 
174 174
 			// Set query (GET) parameters.
175
-			$_item->set_query_params( $query );
175
+			$_item->set_query_params($query);
176 176
 
177 177
 			// Create the item.
178
-			$_response = $this->create_item( $_item );
178
+			$_response = $this->create_item($_item);
179 179
 
180 180
 			// If an error occured...
181
-			if ( is_wp_error( $_response ) ) {
181
+			if (is_wp_error($_response)) {
182 182
 
183
-				$create[]   = array(
183
+				$create[] = array(
184 184
 					'id'    => 0,
185 185
 					'error' => array(
186 186
 						'code'    => $_response->get_error_code(),
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 				continue;
193 193
 			}
194 194
 
195
-			$create[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
195
+			$create[] = $wp_rest_server->response_to_data(/** @scrutinizer ignore-type */ $_response, false);
196 196
 
197 197
 		}
198 198
 
@@ -208,27 +208,27 @@  discard block
 block discarded – undo
208 208
 	 * @param WP_REST_Server $wp_rest_server
209 209
 	 * @return array()
210 210
 	 */
211
-	protected function batch_update_items( $items, $request, $wp_rest_server ) {
211
+	protected function batch_update_items($items, $request, $wp_rest_server) {
212 212
 
213 213
 		$query  = $request->get_query_params();
214 214
 		$update = array();
215 215
 
216
-		foreach ( $items as $item ) {
216
+		foreach ($items as $item) {
217 217
 
218 218
 			// Create a dummy request.
219
-			$_item = new WP_REST_Request( 'PUT' );
219
+			$_item = new WP_REST_Request('PUT');
220 220
 
221 221
 			// Add body params.
222
-			$_item->set_body_params( $item );
222
+			$_item->set_body_params($item);
223 223
 
224 224
 			// Set query (GET) parameters.
225
-			$_item->set_query_params( $query );
225
+			$_item->set_query_params($query);
226 226
 
227 227
 			// Update the item.
228
-			$_response = $this->update_item( $_item );
228
+			$_response = $this->update_item($_item);
229 229
 
230 230
 			// If an error occured...
231
-			if ( is_wp_error( $_response ) ) {
231
+			if (is_wp_error($_response)) {
232 232
 
233 233
 				$update[] = array(
234 234
 					'id'    => $item['id'],
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 
244 244
 			}
245 245
 
246
-			$update[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
246
+			$update[] = $wp_rest_server->response_to_data(/** @scrutinizer ignore-type */ $_response, false);
247 247
 
248 248
 		}
249 249
 
@@ -258,14 +258,14 @@  discard block
 block discarded – undo
258 258
 	 * @param WP_REST_Server $wp_rest_server
259 259
 	 * @return array()
260 260
 	 */
261
-	protected function batch_delete_items( $items, $wp_rest_server ) {
261
+	protected function batch_delete_items($items, $wp_rest_server) {
262 262
 
263 263
 		$delete = array();
264 264
 
265
-		foreach ( array_filter( $items ) as $id ) {
265
+		foreach (array_filter($items) as $id) {
266 266
 
267 267
 			// Prepare the request.
268
-			$_item = new WP_REST_Request( 'DELETE' );
268
+			$_item = new WP_REST_Request('DELETE');
269 269
 			$_item->set_query_params(
270 270
 				array(
271 271
 					'id'    => $id,
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
 			);
275 275
 
276 276
 			// Delete the item.
277
-			$_response = $this->delete_item( $_item );
277
+			$_response = $this->delete_item($_item);
278 278
 
279
-			if ( is_wp_error( $_response ) ) {
279
+			if (is_wp_error($_response)) {
280 280
 
281 281
 				$delete[] = array(
282 282
 					'id'    => $id,
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 				continue;
291 291
 			}
292 292
 
293
-			$delete[] = $wp_rest_server->response_to_data( /** @scrutinizer ignore-type */ $_response, false );
293
+			$delete[] = $wp_rest_server->response_to_data(/** @scrutinizer ignore-type */ $_response, false);
294 294
 
295 295
 		}
296 296
 
@@ -304,23 +304,23 @@  discard block
 block discarded – undo
304 304
 	 * @param WP_REST_Request $request Full details about the request.
305 305
 	 * @return WP_Error|array.
306 306
 	 */
307
-	public function batch_items( $request ) {
307
+	public function batch_items($request) {
308 308
 		global $wp_rest_server;
309 309
 
310 310
 		// Prepare the batch items.
311
-		$items = $this->fill_batch_keys( array_filter( $request->get_params() ) );
311
+		$items = $this->fill_batch_keys(array_filter($request->get_params()));
312 312
 
313 313
 		// Ensure that the batch has not exceeded the limit to prevent abuse.
314
-		$limit = $this->check_batch_limit( $items );
315
-		if ( is_wp_error( $limit ) ) {
314
+		$limit = $this->check_batch_limit($items);
315
+		if (is_wp_error($limit)) {
316 316
 			return $limit;
317 317
 		}
318 318
 
319 319
 		// Process the items.
320 320
 		return array(
321
-			'create' => $this->batch_create_items( $items['create'], $request, $wp_rest_server ),
322
-			'update' => $this->batch_update_items( $items['update'], $request, $wp_rest_server ),
323
-			'delete' => $this->batch_delete_items( $items['delete'], $wp_rest_server ),
321
+			'create' => $this->batch_create_items($items['create'], $request, $wp_rest_server),
322
+			'update' => $this->batch_update_items($items['update'], $request, $wp_rest_server),
323
+			'delete' => $this->batch_delete_items($items['delete'], $wp_rest_server),
324 324
 		);
325 325
 
326 326
 	}
@@ -333,8 +333,8 @@  discard block
 block discarded – undo
333 333
 	 * @param array $meta_query Meta query.
334 334
 	 * @return array
335 335
 	 */
336
-	protected function add_meta_query( $args, $meta_query ) {
337
-		if ( empty( $args['meta_query'] ) ) {
336
+	protected function add_meta_query($args, $meta_query) {
337
+		if (empty($args['meta_query'])) {
338 338
 			$args['meta_query'] = array();
339 339
 		}
340 340
 
@@ -356,25 +356,25 @@  discard block
 block discarded – undo
356 356
 			'type'       => 'object',
357 357
 			'properties' => array(
358 358
 				'create' => array(
359
-					'description' => __( 'List of created resources.', 'invoicing' ),
359
+					'description' => __('List of created resources.', 'invoicing'),
360 360
 					'type'        => 'array',
361
-					'context'     => array( 'view', 'edit' ),
361
+					'context'     => array('view', 'edit'),
362 362
 					'items'       => array(
363 363
 						'type'    => 'object',
364 364
 					),
365 365
 				),
366 366
 				'update' => array(
367
-					'description' => __( 'List of updated resources.', 'invoicing' ),
367
+					'description' => __('List of updated resources.', 'invoicing'),
368 368
 					'type'        => 'array',
369
-					'context'     => array( 'view', 'edit' ),
369
+					'context'     => array('view', 'edit'),
370 370
 					'items'       => array(
371 371
 						'type'    => 'object',
372 372
 					),
373 373
 				),
374 374
 				'delete' => array(
375
-					'description' => __( 'List of deleted resources.', 'invoicing' ),
375
+					'description' => __('List of deleted resources.', 'invoicing'),
376 376
 					'type'        => 'array',
377
-					'context'     => array( 'view', 'edit' ),
377
+					'context'     => array('view', 'edit'),
378 378
 					'items'       => array(
379 379
 						'type'    => 'integer',
380 380
 					),
@@ -395,13 +395,13 @@  discard block
 block discarded – undo
395 395
 	protected function get_schema_properties() {
396 396
 
397 397
 		$schema     = $this->get_item_schema();
398
-		$properties = isset( $schema['properties'] ) ? $schema['properties'] : array();
398
+		$properties = isset($schema['properties']) ? $schema['properties'] : array();
399 399
 
400 400
 		// For back-compat, include any field with an empty schema
401 401
 		// because it won't be present in $this->get_item_schema().
402
-		foreach ( $this->get_additional_fields() as $field_name => $field_options ) {
403
-			if ( is_null( $field_options['schema'] ) ) {
404
-				$properties[ $field_name ] = $field_options;
402
+		foreach ($this->get_additional_fields() as $field_name => $field_options) {
403
+			if (is_null($field_options['schema'])) {
404
+				$properties[$field_name] = $field_options;
405 405
 			}
406 406
 		}
407 407
 
@@ -416,15 +416,15 @@  discard block
 block discarded – undo
416 416
 	 * @since 1.0.19
417 417
 	 * @return array
418 418
 	 */
419
-	protected function filter_response_fields_by_context( $fields, $context ) {
419
+	protected function filter_response_fields_by_context($fields, $context) {
420 420
 
421
-		if ( empty( $context ) ) {
421
+		if (empty($context)) {
422 422
 			return $fields;
423 423
 		}
424 424
 
425
-		foreach ( $fields as $name => $options ) {
426
-			if ( ! empty( $options['context'] ) && ! in_array( $context, $options['context'], true ) ) {
427
-				unset( $fields[ $name ] );
425
+		foreach ($fields as $name => $options) {
426
+			if (!empty($options['context']) && !in_array($context, $options['context'], true)) {
427
+				unset($fields[$name]);
428 428
 			}
429 429
 		}
430 430
 
@@ -440,35 +440,35 @@  discard block
 block discarded – undo
440 440
 	 * @since 1.0.19
441 441
 	 * @return array
442 442
 	 */
443
-	protected function filter_response_fields_by_array( $fields, $requested ) {
443
+	protected function filter_response_fields_by_array($fields, $requested) {
444 444
 
445 445
 		// Trim off any whitespace from the list array.
446
-		$requested = array_map( 'trim', $requested );
446
+		$requested = array_map('trim', $requested);
447 447
 
448 448
 		// Always persist 'id', because it can be needed for add_additional_fields_to_object().
449
-		if ( in_array( 'id', $fields, true ) ) {
449
+		if (in_array('id', $fields, true)) {
450 450
 			$requested[] = 'id';
451 451
 		}
452 452
 
453 453
 		// Get rid of duplicate fields.
454
-		$requested = array_unique( $requested );
454
+		$requested = array_unique($requested);
455 455
 
456 456
 		// Return the list of all included fields which are available.
457 457
 		return array_reduce(
458 458
 			$requested,
459
-			function( $response_fields, $field ) use ( $fields ) {
459
+			function($response_fields, $field) use ($fields) {
460 460
 
461
-				if ( in_array( $field, $fields, true ) ) {
461
+				if (in_array($field, $fields, true)) {
462 462
 					$response_fields[] = $field;
463 463
 					return $response_fields;
464 464
 				}
465 465
 
466 466
 				// Check for nested fields if $field is not a direct match.
467
-				$nested_fields = explode( '.', $field );
467
+				$nested_fields = explode('.', $field);
468 468
 
469 469
 				// A nested field is included so long as its top-level property is
470 470
 				// present in the schema.
471
-				if ( in_array( $nested_fields[0], $fields, true ) ) {
471
+				if (in_array($nested_fields[0], $fields, true)) {
472 472
 					$response_fields[] = $field;
473 473
 				}
474 474
 
@@ -489,23 +489,23 @@  discard block
 block discarded – undo
489 489
 	 * @param WP_REST_Request $request Full details about the request.
490 490
 	 * @return array Fields to be included in the response.
491 491
 	 */
492
-	public function get_fields_for_response( $request ) {
492
+	public function get_fields_for_response($request) {
493 493
 
494 494
 		// Retrieve fields in the schema.
495 495
 		$properties = $this->get_schema_properties();
496 496
 
497 497
 		// Exclude fields that specify a different context than the request context.
498
-		$properties = $this->filter_response_fields_by_context( $properties, $request['context'] );
498
+		$properties = $this->filter_response_fields_by_context($properties, $request['context']);
499 499
 
500 500
 		// We only need the field keys.
501
-		$fields = array_keys( $properties );
501
+		$fields = array_keys($properties);
502 502
 
503 503
 		// Is the user filtering the response fields??
504
-		if ( empty( $request['_fields'] ) ) {
504
+		if (empty($request['_fields'])) {
505 505
 			return $fields;
506 506
 		}
507 507
 
508
-		return $this->filter_response_fields_by_array( $fields, wpinv_parse_list( $request['_fields'] ) );
508
+		return $this->filter_response_fields_by_array($fields, wpinv_parse_list($request['_fields']));
509 509
 
510 510
 	}
511 511
 
@@ -519,32 +519,32 @@  discard block
 block discarded – undo
519 519
 	 * @param array $fields Requested fields.
520 520
 	 * @return array Fields to be included in the response.
521 521
 	 */
522
-	public function limit_object_to_requested_fields( $data, $fields, $prefix = '' ) {
522
+	public function limit_object_to_requested_fields($data, $fields, $prefix = '') {
523 523
 
524 524
 		// Is the user filtering the response fields??
525
-		if ( empty( $fields ) ) {
525
+		if (empty($fields)) {
526 526
 			return $data;
527 527
 		}
528 528
 
529
-		foreach ( $data as $key => $value ) {
529
+		foreach ($data as $key => $value) {
530 530
 
531 531
 			// Numeric arrays.
532
-			if ( is_numeric( $key ) && is_array( $value ) ) {
533
-				$data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $prefix );
532
+			if (is_numeric($key) && is_array($value)) {
533
+				$data[$key] = $this->limit_object_to_requested_fields($value, $fields, $prefix);
534 534
 				continue;
535 535
 			}
536 536
 
537 537
 			// Generate a new prefix.
538
-			$new_prefix = empty( $prefix ) ? $key : "$prefix.$key";
538
+			$new_prefix = empty($prefix) ? $key : "$prefix.$key";
539 539
 
540 540
 			// Check if it was requested.
541
-			if ( ! empty( $key ) && ! $this->is_field_included( $new_prefix, $fields ) ) {
542
-				unset( $data[ $key ] );
541
+			if (!empty($key) && !$this->is_field_included($new_prefix, $fields)) {
542
+				unset($data[$key]);
543 543
 				continue;
544 544
 			}
545 545
 
546
-			if ( $key != 'meta_data' && is_array( $value ) ) {
547
-				$data[ $key ] = $this->limit_object_to_requested_fields( $value, $fields, $new_prefix );
546
+			if ($key != 'meta_data' && is_array($value)) {
547
+				$data[$key] = $this->limit_object_to_requested_fields($value, $fields, $new_prefix);
548 548
 			}
549 549
 
550 550
 		}
@@ -566,20 +566,20 @@  discard block
 block discarded – undo
566 566
 	 * @return bool Whether to include the field or not.
567 567
 	 * @see rest_is_field_included()
568 568
 	 */
569
-	public function is_field_included( $field, $fields ) {
570
-		if ( in_array( $field, $fields, true ) ) {
569
+	public function is_field_included($field, $fields) {
570
+		if (in_array($field, $fields, true)) {
571 571
 			return true;
572 572
 		}
573 573
 
574
-		foreach ( $fields as $accepted_field ) {
574
+		foreach ($fields as $accepted_field) {
575 575
 			// Check to see if $field is the parent of any item in $fields.
576 576
 			// A field "parent" should be accepted if "parent.child" is accepted.
577
-			if ( strpos( $accepted_field, "$field." ) === 0 ) {
577
+			if (strpos($accepted_field, "$field.") === 0) {
578 578
 				return true;
579 579
 			}
580 580
 			// Conversely, if "parent" is accepted, all "parent.child" fields
581 581
 			// should also be accepted.
582
-			if ( strpos( $field, "$accepted_field." ) === 0 ) {
582
+			if (strpos($field, "$accepted_field.") === 0) {
583 583
 				return true;
584 584
 			}
585 585
 		}
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-posts-controller.php 2 patches
Indentation   +1009 added lines, -1009 removed lines patch added patch discarded remove patch
@@ -18,1018 +18,1018 @@
 block discarded – undo
18 18
 class GetPaid_REST_Posts_Controller extends GetPaid_REST_Controller {
19 19
 
20 20
     /**
21
-	 * Post type.
22
-	 *
23
-	 * @var string
24
-	 */
25
-	protected $post_type;
26
-
27
-	/**
28
-	 * Controls visibility on frontend.
29
-	 *
30
-	 * @var string
31
-	 */
32
-	public $public = false;
33
-
34
-	/**
35
-	 * Contains this controller's class name.
36
-	 *
37
-	 * @var string
38
-	 */
39
-	public $crud_class;
40
-
41
-	/**
42
-	 * Registers the routes for the objects of the controller.
43
-	 *
44
-	 * @since 1.0.19
45
-	 *
46
-	 * @see register_rest_route()
47
-	 */
48
-	public function register_namespace_routes( $namespace ) {
49
-
50
-		register_rest_route(
51
-			$namespace,
52
-			'/' . $this->rest_base,
53
-			array(
54
-				array(
55
-					'methods'             => WP_REST_Server::READABLE,
56
-					'callback'            => array( $this, 'get_items' ),
57
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
58
-					'args'                => $this->get_collection_params(),
59
-				),
60
-				array(
61
-					'methods'             => WP_REST_Server::CREATABLE,
62
-					'callback'            => array( $this, 'create_item' ),
63
-					'permission_callback' => array( $this, 'create_item_permissions_check' ),
64
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
65
-				),
66
-				'schema' => array( $this, 'get_public_item_schema' ),
67
-			)
68
-		);
69
-
70
-		$get_item_args = array(
71
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
72
-		);
73
-
74
-		register_rest_route(
75
-			$namespace,
76
-			'/' . $this->rest_base . '/(?P<id>[\d]+)',
77
-			array(
78
-				'args'   => array(
79
-					'id' => array(
80
-						'description' => __( 'Unique identifier for the object.', 'invoicing' ),
81
-						'type'        => 'integer',
82
-					),
83
-				),
84
-				array(
85
-					'methods'             => WP_REST_Server::READABLE,
86
-					'callback'            => array( $this, 'get_item' ),
87
-					'permission_callback' => array( $this, 'get_item_permissions_check' ),
88
-					'args'                => $get_item_args,
89
-				),
90
-				array(
91
-					'methods'             => WP_REST_Server::EDITABLE,
92
-					'callback'            => array( $this, 'update_item' ),
93
-					'permission_callback' => array( $this, 'update_item_permissions_check' ),
94
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
95
-				),
96
-				array(
97
-					'methods'             => WP_REST_Server::DELETABLE,
98
-					'callback'            => array( $this, 'delete_item' ),
99
-					'permission_callback' => array( $this, 'delete_item_permissions_check' ),
100
-					'args'                => array(
101
-						'force' => array(
102
-							'type'        => 'boolean',
103
-							'default'     => false,
104
-							'description' => __( 'Whether to bypass Trash and force deletion.', 'invoicing' ),
105
-						),
106
-					),
107
-				),
108
-				'schema' => array( $this, 'get_public_item_schema' ),
109
-			)
110
-		);
111
-
112
-		register_rest_route(
113
-			$namespace,
114
-			'/' . $this->rest_base . '/batch',
115
-			array(
116
-				array(
117
-					'methods'             => WP_REST_Server::EDITABLE,
118
-					'callback'            => array( $this, 'batch_items' ),
119
-					'permission_callback' => array( $this, 'batch_items_permissions_check' ),
120
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
121
-				),
122
-				'schema' => array( $this, 'get_public_batch_schema' ),
123
-			)
124
-		);
125
-
126
-	}
127
-
128
-	/**
129
-	 * Check permissions of items on REST API.
130
-	 *
131
-	 * @since 1.0.19
132
-	 * @param string $context   Request context.
133
-	 * @param int    $object_id Post ID.
134
-	 * @return bool
135
-	 */
136
-	public function check_post_permissions( $context = 'read', $object_id = 0 ) {
137
-
138
-		$contexts = array(
139
-			'read'   => 'read_private_posts',
140
-			'create' => 'publish_posts',
141
-			'edit'   => 'edit_post',
142
-			'delete' => 'delete_post',
143
-			'batch'  => 'edit_others_posts',
144
-		);
145
-
146
-		if ( 'revision' === $this->post_type ) {
147
-			$permission = false;
148
-		} else {
149
-			$cap              = $contexts[ $context ];
150
-			$post_type_object = get_post_type_object( $this->post_type );
151
-			$permission       = current_user_can( $post_type_object->cap->$cap, $object_id );
152
-		}
153
-
154
-		return apply_filters( 'getpaid_rest_check_permissions', $permission, $context, $object_id, $this->post_type );
155
-	}
156
-
157
-	/**
158
-	 * Check if a given request has access to read items.
159
-	 *
160
-	 * @param  WP_REST_Request $request Full details about the request.
161
-	 * @return WP_Error|boolean
162
-	 */
163
-	public function get_items_permissions_check( $request ) {
164
-		return $this->check_post_permissions() ? true : new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
165
-	}
166
-
167
-	/**
168
-	 * Check if a given request has access to create an item.
169
-	 *
170
-	 * @param  WP_REST_Request $request Full details about the request.
171
-	 * @return WP_Error|boolean
172
-	 */
173
-	public function create_item_permissions_check( $request ) {
174
-		return $this->check_post_permissions( 'create' ) ? true : new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
175
-	}
176
-
177
-	/**
178
-	 * Check if a given request has access to read an item.
179
-	 *
180
-	 * @param  WP_REST_Request $request Full details about the request.
181
-	 * @return WP_Error|boolean
182
-	 */
183
-	public function get_item_permissions_check( $request ) {
184
-		$post = get_post( (int) $request['id'] );
185
-
186
-		if ( $post && ! $this->check_post_permissions( 'read', $post->ID ) ) {
187
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
188
-		}
189
-
190
-		return true;
191
-	}
192
-
193
-	/**
194
-	 * Check if a given request has access to update an item.
195
-	 *
196
-	 * @param  WP_REST_Request $request Full details about the request.
197
-	 * @return WP_Error|boolean
198
-	 */
199
-	public function update_item_permissions_check( $request ) {
200
-		$post = get_post( (int) $request['id'] );
201
-
202
-		if ( $post && ! $this->check_post_permissions( 'edit', $post->ID ) ) {
203
-			return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
204
-		}
205
-
206
-		return true;
207
-	}
208
-
209
-	/**
210
-	 * Check if a given request has access to delete an item.
211
-	 *
212
-	 * @param  WP_REST_Request $request Full details about the request.
213
-	 * @return bool|WP_Error
214
-	 */
215
-	public function delete_item_permissions_check( $request ) {
216
-		$post = get_post( (int) $request['id'] );
217
-
218
-		if ( $post && ! $this->check_post_permissions( 'delete', $post->ID ) ) {
219
-			return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
220
-		}
221
-
222
-		return true;
223
-	}
224
-
225
-	/**
226
-	 * Check if a given request has access batch create, update and delete items.
227
-	 *
228
-	 * @param  WP_REST_Request $request Full details about the request.
229
-	 *
230
-	 * @return boolean|WP_Error
231
-	 */
232
-	public function batch_items_permissions_check( $request ) {
233
-		return $this->check_post_permissions( 'batch' ) ? true : new WP_Error( 'rest_cannot_batch', __( 'Sorry, you are not allowed to batch manipulate this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
234
-	}
235
-
236
-	/**
237
-	 * Saves a single object.
238
-	 *
239
-	 * @param GetPaid_Data $object Object to save.
240
-	 * @return WP_Error|GetPaid_Data
241
-	 */
242
-	protected function save_object( $object ) {
243
-		$object->save();
244
-
245
-		if ( ! empty( $object->last_error ) ) {
246
-			return new WP_Error( 'rest_cannot_save', $object->last_error, array( 'status' => 400 ) );
247
-		}
248
-
249
-		return new $this->crud_class( $object->get_id() );
250
-	}
251
-
252
-	/**
253
-	 * Returns the item's object.
254
-	 *
255
-	 * Child classes must implement this method.
256
-	 * @since 1.0.13
257
-	 *
258
-	 * @param int|WP_Post $object_id Supplied ID.
259
-	 * @return GetPaid_Data|WP_Error GetPaid_Data object if ID is valid, WP_Error otherwise.
260
-	 */
261
-	protected function get_object( $object_id ) {
262
-
263
-		// Do we have an object?
264
-		if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
265
-			return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
266
-		}
267
-
268
-		// Fetch the object.
269
-		$object = new $this->crud_class( $object_id );
270
-		if ( ! empty( $object->last_error ) ) {
271
-			return new WP_Error( 'rest_object_invalid_id', $object->last_error, array( 'status' => 404 ) );
272
-		}
273
-
274
-		return $object->get_id() ? $object : new WP_Error( 'rest_object_invalid_id', __( 'Invalid ID.', 'invoicing' ), array( 'status' => 404 ) );
275
-
276
-	}
277
-
278
-	/**
279
-	 * @deprecated
280
-	 */
281
-	public function get_post( $object_id ) {
282
-		return $this->get_object( $object_id );
21
+     * Post type.
22
+     *
23
+     * @var string
24
+     */
25
+    protected $post_type;
26
+
27
+    /**
28
+     * Controls visibility on frontend.
29
+     *
30
+     * @var string
31
+     */
32
+    public $public = false;
33
+
34
+    /**
35
+     * Contains this controller's class name.
36
+     *
37
+     * @var string
38
+     */
39
+    public $crud_class;
40
+
41
+    /**
42
+     * Registers the routes for the objects of the controller.
43
+     *
44
+     * @since 1.0.19
45
+     *
46
+     * @see register_rest_route()
47
+     */
48
+    public function register_namespace_routes( $namespace ) {
49
+
50
+        register_rest_route(
51
+            $namespace,
52
+            '/' . $this->rest_base,
53
+            array(
54
+                array(
55
+                    'methods'             => WP_REST_Server::READABLE,
56
+                    'callback'            => array( $this, 'get_items' ),
57
+                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
58
+                    'args'                => $this->get_collection_params(),
59
+                ),
60
+                array(
61
+                    'methods'             => WP_REST_Server::CREATABLE,
62
+                    'callback'            => array( $this, 'create_item' ),
63
+                    'permission_callback' => array( $this, 'create_item_permissions_check' ),
64
+                    'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
65
+                ),
66
+                'schema' => array( $this, 'get_public_item_schema' ),
67
+            )
68
+        );
69
+
70
+        $get_item_args = array(
71
+            'context' => $this->get_context_param( array( 'default' => 'view' ) ),
72
+        );
73
+
74
+        register_rest_route(
75
+            $namespace,
76
+            '/' . $this->rest_base . '/(?P<id>[\d]+)',
77
+            array(
78
+                'args'   => array(
79
+                    'id' => array(
80
+                        'description' => __( 'Unique identifier for the object.', 'invoicing' ),
81
+                        'type'        => 'integer',
82
+                    ),
83
+                ),
84
+                array(
85
+                    'methods'             => WP_REST_Server::READABLE,
86
+                    'callback'            => array( $this, 'get_item' ),
87
+                    'permission_callback' => array( $this, 'get_item_permissions_check' ),
88
+                    'args'                => $get_item_args,
89
+                ),
90
+                array(
91
+                    'methods'             => WP_REST_Server::EDITABLE,
92
+                    'callback'            => array( $this, 'update_item' ),
93
+                    'permission_callback' => array( $this, 'update_item_permissions_check' ),
94
+                    'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
95
+                ),
96
+                array(
97
+                    'methods'             => WP_REST_Server::DELETABLE,
98
+                    'callback'            => array( $this, 'delete_item' ),
99
+                    'permission_callback' => array( $this, 'delete_item_permissions_check' ),
100
+                    'args'                => array(
101
+                        'force' => array(
102
+                            'type'        => 'boolean',
103
+                            'default'     => false,
104
+                            'description' => __( 'Whether to bypass Trash and force deletion.', 'invoicing' ),
105
+                        ),
106
+                    ),
107
+                ),
108
+                'schema' => array( $this, 'get_public_item_schema' ),
109
+            )
110
+        );
111
+
112
+        register_rest_route(
113
+            $namespace,
114
+            '/' . $this->rest_base . '/batch',
115
+            array(
116
+                array(
117
+                    'methods'             => WP_REST_Server::EDITABLE,
118
+                    'callback'            => array( $this, 'batch_items' ),
119
+                    'permission_callback' => array( $this, 'batch_items_permissions_check' ),
120
+                    'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
121
+                ),
122
+                'schema' => array( $this, 'get_public_batch_schema' ),
123
+            )
124
+        );
125
+
126
+    }
127
+
128
+    /**
129
+     * Check permissions of items on REST API.
130
+     *
131
+     * @since 1.0.19
132
+     * @param string $context   Request context.
133
+     * @param int    $object_id Post ID.
134
+     * @return bool
135
+     */
136
+    public function check_post_permissions( $context = 'read', $object_id = 0 ) {
137
+
138
+        $contexts = array(
139
+            'read'   => 'read_private_posts',
140
+            'create' => 'publish_posts',
141
+            'edit'   => 'edit_post',
142
+            'delete' => 'delete_post',
143
+            'batch'  => 'edit_others_posts',
144
+        );
145
+
146
+        if ( 'revision' === $this->post_type ) {
147
+            $permission = false;
148
+        } else {
149
+            $cap              = $contexts[ $context ];
150
+            $post_type_object = get_post_type_object( $this->post_type );
151
+            $permission       = current_user_can( $post_type_object->cap->$cap, $object_id );
152
+        }
153
+
154
+        return apply_filters( 'getpaid_rest_check_permissions', $permission, $context, $object_id, $this->post_type );
155
+    }
156
+
157
+    /**
158
+     * Check if a given request has access to read items.
159
+     *
160
+     * @param  WP_REST_Request $request Full details about the request.
161
+     * @return WP_Error|boolean
162
+     */
163
+    public function get_items_permissions_check( $request ) {
164
+        return $this->check_post_permissions() ? true : new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
283 165
     }
284 166
 
285
-	/**
286
-	 * Get a single object.
287
-	 *
288
-	 * @param WP_REST_Request $request Full details about the request.
289
-	 * @return WP_Error|WP_REST_Response
290
-	 */
291
-	public function get_item( $request ) {
292
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
293
-
294
-		// Fetch the item.
295
-		$object = $this->get_object( $request['id'] );
296
-
297
-		if ( is_wp_error( $object ) ) {
298
-			return $object;
299
-		}
300
-
301
-		// Generate a response.
302
-		$data     = $this->prepare_item_for_response( $object, $request );
303
-		$response = rest_ensure_response( $data );
304
-
305
-		// (Maybe) add a link to the html pagee.
306
-		if ( $this->public && ! is_wp_error( $response ) ) {
307
-			$response->link_header( 'alternate', get_permalink( $object->get_id() ), array( 'type' => 'text/html' ) );
308
-		}
309
-
310
-		return $response;
311
-	}
312
-
313
-	/**
314
-	 * Create a single object.
315
-	 *
316
-	 * @param WP_REST_Request $request Full details about the request.
317
-	 * @return WP_Error|WP_REST_Response
318
-	 */
319
-	public function create_item( $request ) {
320
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
321
-
322
-		// Can not create an existing item.
323
-		if ( ! empty( $request['id'] ) ) {
324
-			/* translators: %s: post type */
325
-			return new WP_Error( "getpaid_rest_{$this->post_type}_exists", __( 'Cannot create existing resource.', 'invoicing' ), array( 'status' => 400 ) );
326
-		}
327
-
328
-		// Generate a GetPaid_Data object from the request.
329
-		$object = $this->prepare_item_for_database( $request );
330
-		if ( is_wp_error( $object ) ) {
331
-			return $object;
332
-		}
333
-
334
-		// Save the object.
335
-		$object = $this->save_object( $object );
336
-		if ( is_wp_error( $object ) ) {
337
-			return $object;
338
-		}
339
-
340
-		// Save special fields.
341
-		$save_special = $this->update_additional_fields_for_object( $object, $request );
342
-		if ( is_wp_error( $save_special ) ) {
343
-			$object->delete( true );
344
-			return $save_special;
345
-		}
346
-
347
-		/**
348
-		 * Fires after a single item is created or updated via the REST API.
349
-		 *
350
-		 * @param WP_Post         $post      Post object.
351
-		 * @param WP_REST_Request $request   Request object.
352
-		 * @param boolean         $creating  True when creating item, false when updating.
353
-		 */
354
-		do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, true );
355
-
356
-		$request->set_param( 'context', 'edit' );
357
-		$response = $this->prepare_item_for_response( $object, $request );
358
-		$response = rest_ensure_response( $response );
359
-		$response->set_status( 201 );
360
-		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ) );
361
-
362
-		return $response;
363
-	}
364
-
365
-	/**
366
-	 * Update a single object.
367
-	 *
368
-	 * @param WP_REST_Request $request Full details about the request.
369
-	 * @return WP_Error|WP_REST_Response
370
-	 */
371
-	public function update_item( $request ) {
372
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
373
-
374
-		// Fetch the item.
375
-		$object = $this->get_object( $request['id'] );
376
-		if ( is_wp_error( $object ) ) {
377
-			return $object;
378
-		}
379
-
380
-		// Prepare the item for saving.
381
-		$object = $this->prepare_item_for_database( $request );
382
-		if ( is_wp_error( $object ) ) {
383
-			return $object;
384
-		}
385
-
386
-		// Save the item.
387
-		$object = $this->save_object( $object );
388
-		if ( is_wp_error( $object ) ) {
389
-			return $object;
390
-		}
391
-
392
-		// Save special fields (those added via hooks).
393
-		$save_special = $this->update_additional_fields_for_object( $object, $request );
394
-		if ( is_wp_error( $save_special ) ) {
395
-			return $save_special;
396
-		}
397
-
398
-		/**
399
-		 * Fires after a single item is created or updated via the REST API.
400
-		 *
401
-		 * @param GetPaid_Data    $object    GetPaid_Data object.
402
-		 * @param WP_REST_Request $request   Request object.
403
-		 * @param boolean         $creating  True when creating item, false when updating.
404
-		 */
405
-		do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, false );
406
-
407
-		$request->set_param( 'context', 'edit' );
408
-		$response = $this->prepare_item_for_response( $object, $request );
409
-		return rest_ensure_response( $response );
410
-	}
411
-
412
-	/**
413
-	 * Get a collection of objects.
414
-	 *
415
-	 * @param WP_REST_Request $request Full details about the request.
416
-	 * @return WP_Error|WP_REST_Response
417
-	 */
418
-	public function get_items( $request ) {
419
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
420
-
421
-		$args                         = array();
422
-		$args['offset']               = $request['offset'];
423
-		$args['order']                = $request['order'];
424
-		$args['orderby']              = $request['orderby'];
425
-		$args['paged']                = $request['page'];
426
-		$args['post__in']             = $request['include'];
427
-		$args['post__not_in']         = $request['exclude'];
428
-		$args['posts_per_page']       = $request['per_page'];
429
-		$args['name']                 = $request['slug'];
430
-		$args['post_parent__in']      = $request['parent'];
431
-		$args['post_parent__not_in']  = $request['parent_exclude'];
432
-		$args['s']                    = $request['search'];
433
-		$args['post_status']          = wpinv_parse_list( $request['status'] );
434
-
435
-		$args['date_query'] = array();
436
-		// Set before into date query. Date query must be specified as an array of an array.
437
-		if ( isset( $request['before'] ) ) {
438
-			$args['date_query'][0]['before'] = $request['before'];
439
-		}
440
-
441
-		// Set after into date query. Date query must be specified as an array of an array.
442
-		if ( isset( $request['after'] ) ) {
443
-			$args['date_query'][0]['after'] = $request['after'];
444
-		}
445
-
446
-		// Force the post_type & fields arguments, since they're not a user input variable.
447
-		$args['post_type'] = $this->post_type;
448
-		$args['fields']    = 'ids';
449
-
450
-		// Filter the query arguments for a request.
451
-		$args       = apply_filters( "getpaid_rest_{$this->post_type}_query", $args, $request );
452
-		$query_args = $this->prepare_items_query( $args, $request );
453
-
454
-		$posts_query = new WP_Query();
455
-		$query_result = $posts_query->query( $query_args );
456
-
457
-		$posts = array();
458
-		foreach ( $query_result as $post_id ) {
459
-			if ( ! $this->check_post_permissions( 'read', $post_id ) ) {
460
-				continue;
461
-			}
462
-
463
-			$data    = $this->prepare_item_for_response( $this->get_object( $post_id ), $request );
464
-			$posts[] = $this->prepare_response_for_collection( $data );
465
-		}
466
-
467
-		$page        = (int) $query_args['paged'];
468
-		$total_posts = $posts_query->found_posts;
469
-
470
-		if ( $total_posts < 1 ) {
471
-			// Out-of-bounds, run the query again without LIMIT for total count.
472
-			unset( $query_args['paged'] );
473
-			$count_query = new WP_Query();
474
-			$count_query->query( $query_args );
475
-			$total_posts = $count_query->found_posts;
476
-		}
477
-
478
-		$max_pages = ceil( $total_posts / (int) $query_args['posts_per_page'] );
479
-
480
-		$response = rest_ensure_response( $posts );
481
-		$response->header( 'X-WP-Total', (int) $total_posts );
482
-		$response->header( 'X-WP-TotalPages', (int) $max_pages );
483
-
484
-		$request_params = $request->get_query_params();
485
-		$base = add_query_arg( $request_params, rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
486
-
487
-		if ( $page > 1 ) {
488
-			$prev_page = $page - 1;
489
-			if ( $prev_page > $max_pages ) {
490
-				$prev_page = $max_pages;
491
-			}
492
-			$prev_link = add_query_arg( 'page', $prev_page, $base );
493
-			$response->link_header( 'prev', $prev_link );
494
-		}
495
-		if ( $max_pages > $page ) {
496
-			$next_page = $page + 1;
497
-			$next_link = add_query_arg( 'page', $next_page, $base );
498
-			$response->link_header( 'next', $next_link );
499
-		}
500
-
501
-		return $response;
502
-	}
503
-
504
-	/**
505
-	 * Delete a single item.
506
-	 *
507
-	 * @param WP_REST_Request $request Full details about the request.
508
-	 * @return WP_REST_Response|WP_Error
509
-	 */
510
-	public function delete_item( $request ) {
511
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
512
-
513
-		// Fetch the item.
514
-		$item = $this->get_object( $request['id'] );
515
-		if ( is_wp_error( $item ) ) {
516
-			return $item;
517
-		}
518
-
519
-		$supports_trash = EMPTY_TRASH_DAYS > 0;
520
-		$force          = $supports_trash && (bool) $request['force'];
521
-
522
-		if ( ! $this->check_post_permissions( 'delete', $item->ID ) ) {
523
-			return new WP_Error( "cannot_delete", __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
524
-		}
525
-
526
-		$request->set_param( 'context', 'edit' );
527
-		$response = $this->prepare_item_for_response( $item, $request );
528
-
529
-		if ( ! wp_delete_post( $item->ID, $force ) ) {
530
-			return new WP_Error( 'rest_cannot_delete', sprintf( __( 'The resource cannot be deleted.', 'invoicing' ), $this->post_type ), array( 'status' => 500 ) );
531
-		}
532
-
533
-		return $response;
534
-	}
535
-
536
-	/**
537
-	 * Prepare links for the request.
538
-	 *
539
-	 * @param GetPaid_Data    $object GetPaid_Data object.
540
-	 * @return array Links for the given object.
541
-	 */
542
-	protected function prepare_links( $object ) {
543
-
544
-		$links = array(
545
-			'self'       => array(
546
-				'href'   => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ),
547
-			),
548
-			'collection' => array(
549
-				'href'   => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
550
-			),
551
-		);
552
-
553
-		if ( is_callable( array( $object, 'get_user_id' ) ) ) {
554
-			$links['user'] = array(
555
-				'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_user_id' )  ) ),
556
-				'embeddable' => true,
557
-			);
558
-		}
559
-
560
-		if ( is_callable( array( $object, 'get_owner' ) ) ) {
561
-			$links['owner']  = array(
562
-				'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_owner' )  ) ),
563
-				'embeddable' => true,
564
-			);
565
-		}
566
-
567
-		if ( is_callable( array( $object, 'get_parent_id' ) ) && call_user_func(  array( $object, 'get_parent_id' )  ) ) {
568
-			$links['parent']  = array(
569
-				'href'       => rest_url( "$this->namespace/$this->rest_base/" . call_user_func(  array( $object, 'get_parent_id' )  ) ),
570
-				'embeddable' => true,
571
-			);
572
-		}
573
-
574
-		return $links;
575
-	}
576
-
577
-	/**
578
-	 * Determine the allowed query_vars for a get_items() response and
579
-	 * prepare for WP_Query.
580
-	 *
581
-	 * @param array           $prepared_args Prepared arguments.
582
-	 * @param WP_REST_Request $request Request object.
583
-	 * @return array          $query_args
584
-	 */
585
-	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
586
-
587
-		$valid_vars = array_flip( $this->get_allowed_query_vars() );
588
-		$query_args = array();
589
-		foreach ( $valid_vars as $var => $index ) {
590
-			if ( isset( $prepared_args[ $var ] ) ) {
591
-				$query_args[ $var ] = apply_filters( "getpaid_rest_query_var-{$var}", $prepared_args[ $var ] );
592
-			}
593
-		}
594
-
595
-		$query_args['ignore_sticky_posts'] = true;
596
-
597
-		if ( 'include' === $query_args['orderby'] ) {
598
-			$query_args['orderby'] = 'post__in';
599
-		} elseif ( 'id' === $query_args['orderby'] ) {
600
-			$query_args['orderby'] = 'ID'; // ID must be capitalized.
601
-		} elseif ( 'slug' === $query_args['orderby'] ) {
602
-			$query_args['orderby'] = 'name';
603
-		}
604
-
605
-		return apply_filters( 'getpaid_rest_prepare_items_query', $query_args, $request, $this );
606
-
607
-	}
608
-
609
-	/**
610
-	 * Get all the WP Query vars that are allowed for the API request.
611
-	 *
612
-	 * @return array
613
-	 */
614
-	protected function get_allowed_query_vars() {
615
-		global $wp;
616
-
617
-		/**
618
-		 * Filter the publicly allowed query vars.
619
-		 *
620
-		 * Allows adjusting of the default query vars that are made public.
621
-		 *
622
-		 * @param array  Array of allowed WP_Query query vars.
623
-		 */
624
-		$valid_vars = apply_filters( 'query_vars', $wp->public_query_vars );
625
-
626
-		$post_type_obj = get_post_type_object( $this->post_type );
627
-		if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
628
-			$private = apply_filters( 'getpaid_rest_private_query_vars', $wp->private_query_vars );
629
-			$valid_vars = array_merge( $valid_vars, $private );
630
-		}
631
-
632
-		// Define our own in addition to WP's normal vars.
633
-		$rest_valid = array(
634
-			'post_status',
635
-			'date_query',
636
-			'ignore_sticky_posts',
637
-			'offset',
638
-			'post__in',
639
-			'post__not_in',
640
-			'post_parent',
641
-			'post_parent__in',
642
-			'post_parent__not_in',
643
-			'posts_per_page',
644
-			'meta_query',
645
-			'tax_query',
646
-			'meta_key',
647
-			'meta_value',
648
-			'meta_compare',
649
-			'meta_value_num',
650
-		);
651
-		$valid_vars = array_merge( $valid_vars, $rest_valid );
652
-
653
-		// Filter allowed query vars for the REST API.
654
-		$valid_vars = apply_filters( 'getpaid_rest_query_vars', $valid_vars, $this );
655
-
656
-		return $valid_vars;
657
-	}
658
-
659
-	/**
660
-	 * Get the query params for collections of attachments.
661
-	 *
662
-	 * @return array
663
-	 */
664
-	public function get_collection_params() {
665
-		$params = parent::get_collection_params();
666
-
667
-		$params['context']['default'] = 'view';
668
-
669
-		$params['status'] = array(
670
-			'default'           => $this->get_post_statuses(),
671
-			'description'       => __( 'Limit result set to resources assigned one or more statuses.', 'invoicing' ),
672
-			'type'              => array( 'array', 'string' ),
673
-			'items'             => array(
674
-				'enum'          => $this->get_post_statuses(),
675
-				'type'          => 'string',
676
-			),
677
-			'validate_callback' => 'rest_validate_request_arg',
678
-			'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
679
-		);
680
-
681
-		$params['after'] = array(
682
-			'description'        => __( 'Limit response to resources created after a given ISO8601 compliant date.', 'invoicing' ),
683
-			'type'               => 'string',
684
-			'format'             => 'string',
685
-			'validate_callback'  => 'rest_validate_request_arg',
686
-			'sanitize_callback'  => 'sanitize_text_field',
687
-		);
688
-		$params['before'] = array(
689
-			'description'        => __( 'Limit response to resources created before a given ISO8601 compliant date.', 'invoicing' ),
690
-			'type'               => 'string',
691
-			'format'             => 'string',
692
-			'validate_callback'  => 'rest_validate_request_arg',
693
-			'sanitize_callback'  => 'sanitize_text_field',
694
-		);
695
-		$params['exclude'] = array(
696
-			'description'       => __( 'Ensure result set excludes specific IDs.', 'invoicing' ),
697
-			'type'              => 'array',
698
-			'items'             => array(
699
-				'type'          => 'integer',
700
-			),
701
-			'default'           => array(),
702
-			'sanitize_callback' => 'wp_parse_id_list',
703
-			'validate_callback' => 'rest_validate_request_arg',
704
-		);
705
-		$params['include'] = array(
706
-			'description'       => __( 'Limit result set to specific ids.', 'invoicing' ),
707
-			'type'              => 'array',
708
-			'items'             => array(
709
-				'type'          => 'integer',
710
-			),
711
-			'default'           => array(),
712
-			'sanitize_callback' => 'wp_parse_id_list',
713
-			'validate_callback' => 'rest_validate_request_arg',
714
-		);
715
-		$params['offset'] = array(
716
-			'description'        => __( 'Offset the result set by a specific number of items.', 'invoicing' ),
717
-			'type'               => 'integer',
718
-			'sanitize_callback'  => 'absint',
719
-			'validate_callback'  => 'rest_validate_request_arg',
720
-		);
721
-		$params['order'] = array(
722
-			'description'        => __( 'Order sort attribute ascending or descending.', 'invoicing' ),
723
-			'type'               => 'string',
724
-			'default'            => 'desc',
725
-			'enum'               => array( 'asc', 'desc' ),
726
-			'validate_callback'  => 'rest_validate_request_arg',
727
-		);
728
-		$params['orderby'] = array(
729
-			'description'        => __( 'Sort collection by object attribute.', 'invoicing' ),
730
-			'type'               => 'string',
731
-			'default'            => 'date',
732
-			'enum'               => array(
733
-				'date',
734
-				'id',
735
-				'include',
736
-				'title',
737
-				'slug',
738
-				'modified',
739
-			),
740
-			'validate_callback'  => 'rest_validate_request_arg',
741
-		);
742
-
743
-		$post_type_obj = get_post_type_object( $this->post_type );
744
-
745
-		if ( isset( $post_type_obj->hierarchical ) && $post_type_obj->hierarchical ) {
746
-			$params['parent'] = array(
747
-				'description'       => __( 'Limit result set to those of particular parent IDs.', 'invoicing' ),
748
-				'type'              => 'array',
749
-				'items'             => array(
750
-					'type'          => 'integer',
751
-				),
752
-				'sanitize_callback' => 'wp_parse_id_list',
753
-				'default'           => array(),
754
-			);
755
-			$params['parent_exclude'] = array(
756
-				'description'       => __( 'Limit result set to all items except those of a particular parent ID.', 'invoicing' ),
757
-				'type'              => 'array',
758
-				'items'             => array(
759
-					'type'          => 'integer',
760
-				),
761
-				'sanitize_callback' => 'wp_parse_id_list',
762
-				'default'           => array(),
763
-			);
764
-		}
765
-
766
-		return $params;
767
-	}
768
-
769
-	/**
770
-	 * Retrieves the items's schema, conforming to JSON Schema.
771
-	 *
772
-	 * @since 1.0.19
773
-	 *
774
-	 * @return array Item schema data.
775
-	 */
776
-	public function get_item_schema() {
777
-
778
-		// Maybe retrieve the schema from cache.
779
-		if ( $this->schema ) {
780
-			return $this->add_additional_fields_schema( $this->schema );
781
-		}
782
-
783
-		$type   = str_replace( 'wpi_', '', $this->post_type );
784
-		$schema = array(
785
-			'$schema'    => 'http://json-schema.org/draft-04/schema#',
786
-			'title'      => $this->post_type,
787
-			'type'       => 'object',
788
-			'properties' => wpinv_get_data( "$type-schema" ),
789
-		);
790
-
791
-		// Filters the invoice schema for the REST API.
167
+    /**
168
+     * Check if a given request has access to create an item.
169
+     *
170
+     * @param  WP_REST_Request $request Full details about the request.
171
+     * @return WP_Error|boolean
172
+     */
173
+    public function create_item_permissions_check( $request ) {
174
+        return $this->check_post_permissions( 'create' ) ? true : new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
175
+    }
176
+
177
+    /**
178
+     * Check if a given request has access to read an item.
179
+     *
180
+     * @param  WP_REST_Request $request Full details about the request.
181
+     * @return WP_Error|boolean
182
+     */
183
+    public function get_item_permissions_check( $request ) {
184
+        $post = get_post( (int) $request['id'] );
185
+
186
+        if ( $post && ! $this->check_post_permissions( 'read', $post->ID ) ) {
187
+            return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
188
+        }
189
+
190
+        return true;
191
+    }
192
+
193
+    /**
194
+     * Check if a given request has access to update an item.
195
+     *
196
+     * @param  WP_REST_Request $request Full details about the request.
197
+     * @return WP_Error|boolean
198
+     */
199
+    public function update_item_permissions_check( $request ) {
200
+        $post = get_post( (int) $request['id'] );
201
+
202
+        if ( $post && ! $this->check_post_permissions( 'edit', $post->ID ) ) {
203
+            return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
204
+        }
205
+
206
+        return true;
207
+    }
208
+
209
+    /**
210
+     * Check if a given request has access to delete an item.
211
+     *
212
+     * @param  WP_REST_Request $request Full details about the request.
213
+     * @return bool|WP_Error
214
+     */
215
+    public function delete_item_permissions_check( $request ) {
216
+        $post = get_post( (int) $request['id'] );
217
+
218
+        if ( $post && ! $this->check_post_permissions( 'delete', $post->ID ) ) {
219
+            return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
220
+        }
221
+
222
+        return true;
223
+    }
224
+
225
+    /**
226
+     * Check if a given request has access batch create, update and delete items.
227
+     *
228
+     * @param  WP_REST_Request $request Full details about the request.
229
+     *
230
+     * @return boolean|WP_Error
231
+     */
232
+    public function batch_items_permissions_check( $request ) {
233
+        return $this->check_post_permissions( 'batch' ) ? true : new WP_Error( 'rest_cannot_batch', __( 'Sorry, you are not allowed to batch manipulate this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
234
+    }
235
+
236
+    /**
237
+     * Saves a single object.
238
+     *
239
+     * @param GetPaid_Data $object Object to save.
240
+     * @return WP_Error|GetPaid_Data
241
+     */
242
+    protected function save_object( $object ) {
243
+        $object->save();
244
+
245
+        if ( ! empty( $object->last_error ) ) {
246
+            return new WP_Error( 'rest_cannot_save', $object->last_error, array( 'status' => 400 ) );
247
+        }
248
+
249
+        return new $this->crud_class( $object->get_id() );
250
+    }
251
+
252
+    /**
253
+     * Returns the item's object.
254
+     *
255
+     * Child classes must implement this method.
256
+     * @since 1.0.13
257
+     *
258
+     * @param int|WP_Post $object_id Supplied ID.
259
+     * @return GetPaid_Data|WP_Error GetPaid_Data object if ID is valid, WP_Error otherwise.
260
+     */
261
+    protected function get_object( $object_id ) {
262
+
263
+        // Do we have an object?
264
+        if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
265
+            return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
266
+        }
267
+
268
+        // Fetch the object.
269
+        $object = new $this->crud_class( $object_id );
270
+        if ( ! empty( $object->last_error ) ) {
271
+            return new WP_Error( 'rest_object_invalid_id', $object->last_error, array( 'status' => 404 ) );
272
+        }
273
+
274
+        return $object->get_id() ? $object : new WP_Error( 'rest_object_invalid_id', __( 'Invalid ID.', 'invoicing' ), array( 'status' => 404 ) );
275
+
276
+    }
277
+
278
+    /**
279
+     * @deprecated
280
+     */
281
+    public function get_post( $object_id ) {
282
+        return $this->get_object( $object_id );
283
+    }
284
+
285
+    /**
286
+     * Get a single object.
287
+     *
288
+     * @param WP_REST_Request $request Full details about the request.
289
+     * @return WP_Error|WP_REST_Response
290
+     */
291
+    public function get_item( $request ) {
292
+        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
293
+
294
+        // Fetch the item.
295
+        $object = $this->get_object( $request['id'] );
296
+
297
+        if ( is_wp_error( $object ) ) {
298
+            return $object;
299
+        }
300
+
301
+        // Generate a response.
302
+        $data     = $this->prepare_item_for_response( $object, $request );
303
+        $response = rest_ensure_response( $data );
304
+
305
+        // (Maybe) add a link to the html pagee.
306
+        if ( $this->public && ! is_wp_error( $response ) ) {
307
+            $response->link_header( 'alternate', get_permalink( $object->get_id() ), array( 'type' => 'text/html' ) );
308
+        }
309
+
310
+        return $response;
311
+    }
312
+
313
+    /**
314
+     * Create a single object.
315
+     *
316
+     * @param WP_REST_Request $request Full details about the request.
317
+     * @return WP_Error|WP_REST_Response
318
+     */
319
+    public function create_item( $request ) {
320
+        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
321
+
322
+        // Can not create an existing item.
323
+        if ( ! empty( $request['id'] ) ) {
324
+            /* translators: %s: post type */
325
+            return new WP_Error( "getpaid_rest_{$this->post_type}_exists", __( 'Cannot create existing resource.', 'invoicing' ), array( 'status' => 400 ) );
326
+        }
327
+
328
+        // Generate a GetPaid_Data object from the request.
329
+        $object = $this->prepare_item_for_database( $request );
330
+        if ( is_wp_error( $object ) ) {
331
+            return $object;
332
+        }
333
+
334
+        // Save the object.
335
+        $object = $this->save_object( $object );
336
+        if ( is_wp_error( $object ) ) {
337
+            return $object;
338
+        }
339
+
340
+        // Save special fields.
341
+        $save_special = $this->update_additional_fields_for_object( $object, $request );
342
+        if ( is_wp_error( $save_special ) ) {
343
+            $object->delete( true );
344
+            return $save_special;
345
+        }
346
+
347
+        /**
348
+         * Fires after a single item is created or updated via the REST API.
349
+         *
350
+         * @param WP_Post         $post      Post object.
351
+         * @param WP_REST_Request $request   Request object.
352
+         * @param boolean         $creating  True when creating item, false when updating.
353
+         */
354
+        do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, true );
355
+
356
+        $request->set_param( 'context', 'edit' );
357
+        $response = $this->prepare_item_for_response( $object, $request );
358
+        $response = rest_ensure_response( $response );
359
+        $response->set_status( 201 );
360
+        $response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ) );
361
+
362
+        return $response;
363
+    }
364
+
365
+    /**
366
+     * Update a single object.
367
+     *
368
+     * @param WP_REST_Request $request Full details about the request.
369
+     * @return WP_Error|WP_REST_Response
370
+     */
371
+    public function update_item( $request ) {
372
+        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
373
+
374
+        // Fetch the item.
375
+        $object = $this->get_object( $request['id'] );
376
+        if ( is_wp_error( $object ) ) {
377
+            return $object;
378
+        }
379
+
380
+        // Prepare the item for saving.
381
+        $object = $this->prepare_item_for_database( $request );
382
+        if ( is_wp_error( $object ) ) {
383
+            return $object;
384
+        }
385
+
386
+        // Save the item.
387
+        $object = $this->save_object( $object );
388
+        if ( is_wp_error( $object ) ) {
389
+            return $object;
390
+        }
391
+
392
+        // Save special fields (those added via hooks).
393
+        $save_special = $this->update_additional_fields_for_object( $object, $request );
394
+        if ( is_wp_error( $save_special ) ) {
395
+            return $save_special;
396
+        }
397
+
398
+        /**
399
+         * Fires after a single item is created or updated via the REST API.
400
+         *
401
+         * @param GetPaid_Data    $object    GetPaid_Data object.
402
+         * @param WP_REST_Request $request   Request object.
403
+         * @param boolean         $creating  True when creating item, false when updating.
404
+         */
405
+        do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, false );
406
+
407
+        $request->set_param( 'context', 'edit' );
408
+        $response = $this->prepare_item_for_response( $object, $request );
409
+        return rest_ensure_response( $response );
410
+    }
411
+
412
+    /**
413
+     * Get a collection of objects.
414
+     *
415
+     * @param WP_REST_Request $request Full details about the request.
416
+     * @return WP_Error|WP_REST_Response
417
+     */
418
+    public function get_items( $request ) {
419
+        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
420
+
421
+        $args                         = array();
422
+        $args['offset']               = $request['offset'];
423
+        $args['order']                = $request['order'];
424
+        $args['orderby']              = $request['orderby'];
425
+        $args['paged']                = $request['page'];
426
+        $args['post__in']             = $request['include'];
427
+        $args['post__not_in']         = $request['exclude'];
428
+        $args['posts_per_page']       = $request['per_page'];
429
+        $args['name']                 = $request['slug'];
430
+        $args['post_parent__in']      = $request['parent'];
431
+        $args['post_parent__not_in']  = $request['parent_exclude'];
432
+        $args['s']                    = $request['search'];
433
+        $args['post_status']          = wpinv_parse_list( $request['status'] );
434
+
435
+        $args['date_query'] = array();
436
+        // Set before into date query. Date query must be specified as an array of an array.
437
+        if ( isset( $request['before'] ) ) {
438
+            $args['date_query'][0]['before'] = $request['before'];
439
+        }
440
+
441
+        // Set after into date query. Date query must be specified as an array of an array.
442
+        if ( isset( $request['after'] ) ) {
443
+            $args['date_query'][0]['after'] = $request['after'];
444
+        }
445
+
446
+        // Force the post_type & fields arguments, since they're not a user input variable.
447
+        $args['post_type'] = $this->post_type;
448
+        $args['fields']    = 'ids';
449
+
450
+        // Filter the query arguments for a request.
451
+        $args       = apply_filters( "getpaid_rest_{$this->post_type}_query", $args, $request );
452
+        $query_args = $this->prepare_items_query( $args, $request );
453
+
454
+        $posts_query = new WP_Query();
455
+        $query_result = $posts_query->query( $query_args );
456
+
457
+        $posts = array();
458
+        foreach ( $query_result as $post_id ) {
459
+            if ( ! $this->check_post_permissions( 'read', $post_id ) ) {
460
+                continue;
461
+            }
462
+
463
+            $data    = $this->prepare_item_for_response( $this->get_object( $post_id ), $request );
464
+            $posts[] = $this->prepare_response_for_collection( $data );
465
+        }
466
+
467
+        $page        = (int) $query_args['paged'];
468
+        $total_posts = $posts_query->found_posts;
469
+
470
+        if ( $total_posts < 1 ) {
471
+            // Out-of-bounds, run the query again without LIMIT for total count.
472
+            unset( $query_args['paged'] );
473
+            $count_query = new WP_Query();
474
+            $count_query->query( $query_args );
475
+            $total_posts = $count_query->found_posts;
476
+        }
477
+
478
+        $max_pages = ceil( $total_posts / (int) $query_args['posts_per_page'] );
479
+
480
+        $response = rest_ensure_response( $posts );
481
+        $response->header( 'X-WP-Total', (int) $total_posts );
482
+        $response->header( 'X-WP-TotalPages', (int) $max_pages );
483
+
484
+        $request_params = $request->get_query_params();
485
+        $base = add_query_arg( $request_params, rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
486
+
487
+        if ( $page > 1 ) {
488
+            $prev_page = $page - 1;
489
+            if ( $prev_page > $max_pages ) {
490
+                $prev_page = $max_pages;
491
+            }
492
+            $prev_link = add_query_arg( 'page', $prev_page, $base );
493
+            $response->link_header( 'prev', $prev_link );
494
+        }
495
+        if ( $max_pages > $page ) {
496
+            $next_page = $page + 1;
497
+            $next_link = add_query_arg( 'page', $next_page, $base );
498
+            $response->link_header( 'next', $next_link );
499
+        }
500
+
501
+        return $response;
502
+    }
503
+
504
+    /**
505
+     * Delete a single item.
506
+     *
507
+     * @param WP_REST_Request $request Full details about the request.
508
+     * @return WP_REST_Response|WP_Error
509
+     */
510
+    public function delete_item( $request ) {
511
+        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
512
+
513
+        // Fetch the item.
514
+        $item = $this->get_object( $request['id'] );
515
+        if ( is_wp_error( $item ) ) {
516
+            return $item;
517
+        }
518
+
519
+        $supports_trash = EMPTY_TRASH_DAYS > 0;
520
+        $force          = $supports_trash && (bool) $request['force'];
521
+
522
+        if ( ! $this->check_post_permissions( 'delete', $item->ID ) ) {
523
+            return new WP_Error( "cannot_delete", __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
524
+        }
525
+
526
+        $request->set_param( 'context', 'edit' );
527
+        $response = $this->prepare_item_for_response( $item, $request );
528
+
529
+        if ( ! wp_delete_post( $item->ID, $force ) ) {
530
+            return new WP_Error( 'rest_cannot_delete', sprintf( __( 'The resource cannot be deleted.', 'invoicing' ), $this->post_type ), array( 'status' => 500 ) );
531
+        }
532
+
533
+        return $response;
534
+    }
535
+
536
+    /**
537
+     * Prepare links for the request.
538
+     *
539
+     * @param GetPaid_Data    $object GetPaid_Data object.
540
+     * @return array Links for the given object.
541
+     */
542
+    protected function prepare_links( $object ) {
543
+
544
+        $links = array(
545
+            'self'       => array(
546
+                'href'   => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ),
547
+            ),
548
+            'collection' => array(
549
+                'href'   => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
550
+            ),
551
+        );
552
+
553
+        if ( is_callable( array( $object, 'get_user_id' ) ) ) {
554
+            $links['user'] = array(
555
+                'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_user_id' )  ) ),
556
+                'embeddable' => true,
557
+            );
558
+        }
559
+
560
+        if ( is_callable( array( $object, 'get_owner' ) ) ) {
561
+            $links['owner']  = array(
562
+                'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_owner' )  ) ),
563
+                'embeddable' => true,
564
+            );
565
+        }
566
+
567
+        if ( is_callable( array( $object, 'get_parent_id' ) ) && call_user_func(  array( $object, 'get_parent_id' )  ) ) {
568
+            $links['parent']  = array(
569
+                'href'       => rest_url( "$this->namespace/$this->rest_base/" . call_user_func(  array( $object, 'get_parent_id' )  ) ),
570
+                'embeddable' => true,
571
+            );
572
+        }
573
+
574
+        return $links;
575
+    }
576
+
577
+    /**
578
+     * Determine the allowed query_vars for a get_items() response and
579
+     * prepare for WP_Query.
580
+     *
581
+     * @param array           $prepared_args Prepared arguments.
582
+     * @param WP_REST_Request $request Request object.
583
+     * @return array          $query_args
584
+     */
585
+    protected function prepare_items_query( $prepared_args = array(), $request = null ) {
586
+
587
+        $valid_vars = array_flip( $this->get_allowed_query_vars() );
588
+        $query_args = array();
589
+        foreach ( $valid_vars as $var => $index ) {
590
+            if ( isset( $prepared_args[ $var ] ) ) {
591
+                $query_args[ $var ] = apply_filters( "getpaid_rest_query_var-{$var}", $prepared_args[ $var ] );
592
+            }
593
+        }
594
+
595
+        $query_args['ignore_sticky_posts'] = true;
596
+
597
+        if ( 'include' === $query_args['orderby'] ) {
598
+            $query_args['orderby'] = 'post__in';
599
+        } elseif ( 'id' === $query_args['orderby'] ) {
600
+            $query_args['orderby'] = 'ID'; // ID must be capitalized.
601
+        } elseif ( 'slug' === $query_args['orderby'] ) {
602
+            $query_args['orderby'] = 'name';
603
+        }
604
+
605
+        return apply_filters( 'getpaid_rest_prepare_items_query', $query_args, $request, $this );
606
+
607
+    }
608
+
609
+    /**
610
+     * Get all the WP Query vars that are allowed for the API request.
611
+     *
612
+     * @return array
613
+     */
614
+    protected function get_allowed_query_vars() {
615
+        global $wp;
616
+
617
+        /**
618
+         * Filter the publicly allowed query vars.
619
+         *
620
+         * Allows adjusting of the default query vars that are made public.
621
+         *
622
+         * @param array  Array of allowed WP_Query query vars.
623
+         */
624
+        $valid_vars = apply_filters( 'query_vars', $wp->public_query_vars );
625
+
626
+        $post_type_obj = get_post_type_object( $this->post_type );
627
+        if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
628
+            $private = apply_filters( 'getpaid_rest_private_query_vars', $wp->private_query_vars );
629
+            $valid_vars = array_merge( $valid_vars, $private );
630
+        }
631
+
632
+        // Define our own in addition to WP's normal vars.
633
+        $rest_valid = array(
634
+            'post_status',
635
+            'date_query',
636
+            'ignore_sticky_posts',
637
+            'offset',
638
+            'post__in',
639
+            'post__not_in',
640
+            'post_parent',
641
+            'post_parent__in',
642
+            'post_parent__not_in',
643
+            'posts_per_page',
644
+            'meta_query',
645
+            'tax_query',
646
+            'meta_key',
647
+            'meta_value',
648
+            'meta_compare',
649
+            'meta_value_num',
650
+        );
651
+        $valid_vars = array_merge( $valid_vars, $rest_valid );
652
+
653
+        // Filter allowed query vars for the REST API.
654
+        $valid_vars = apply_filters( 'getpaid_rest_query_vars', $valid_vars, $this );
655
+
656
+        return $valid_vars;
657
+    }
658
+
659
+    /**
660
+     * Get the query params for collections of attachments.
661
+     *
662
+     * @return array
663
+     */
664
+    public function get_collection_params() {
665
+        $params = parent::get_collection_params();
666
+
667
+        $params['context']['default'] = 'view';
668
+
669
+        $params['status'] = array(
670
+            'default'           => $this->get_post_statuses(),
671
+            'description'       => __( 'Limit result set to resources assigned one or more statuses.', 'invoicing' ),
672
+            'type'              => array( 'array', 'string' ),
673
+            'items'             => array(
674
+                'enum'          => $this->get_post_statuses(),
675
+                'type'          => 'string',
676
+            ),
677
+            'validate_callback' => 'rest_validate_request_arg',
678
+            'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
679
+        );
680
+
681
+        $params['after'] = array(
682
+            'description'        => __( 'Limit response to resources created after a given ISO8601 compliant date.', 'invoicing' ),
683
+            'type'               => 'string',
684
+            'format'             => 'string',
685
+            'validate_callback'  => 'rest_validate_request_arg',
686
+            'sanitize_callback'  => 'sanitize_text_field',
687
+        );
688
+        $params['before'] = array(
689
+            'description'        => __( 'Limit response to resources created before a given ISO8601 compliant date.', 'invoicing' ),
690
+            'type'               => 'string',
691
+            'format'             => 'string',
692
+            'validate_callback'  => 'rest_validate_request_arg',
693
+            'sanitize_callback'  => 'sanitize_text_field',
694
+        );
695
+        $params['exclude'] = array(
696
+            'description'       => __( 'Ensure result set excludes specific IDs.', 'invoicing' ),
697
+            'type'              => 'array',
698
+            'items'             => array(
699
+                'type'          => 'integer',
700
+            ),
701
+            'default'           => array(),
702
+            'sanitize_callback' => 'wp_parse_id_list',
703
+            'validate_callback' => 'rest_validate_request_arg',
704
+        );
705
+        $params['include'] = array(
706
+            'description'       => __( 'Limit result set to specific ids.', 'invoicing' ),
707
+            'type'              => 'array',
708
+            'items'             => array(
709
+                'type'          => 'integer',
710
+            ),
711
+            'default'           => array(),
712
+            'sanitize_callback' => 'wp_parse_id_list',
713
+            'validate_callback' => 'rest_validate_request_arg',
714
+        );
715
+        $params['offset'] = array(
716
+            'description'        => __( 'Offset the result set by a specific number of items.', 'invoicing' ),
717
+            'type'               => 'integer',
718
+            'sanitize_callback'  => 'absint',
719
+            'validate_callback'  => 'rest_validate_request_arg',
720
+        );
721
+        $params['order'] = array(
722
+            'description'        => __( 'Order sort attribute ascending or descending.', 'invoicing' ),
723
+            'type'               => 'string',
724
+            'default'            => 'desc',
725
+            'enum'               => array( 'asc', 'desc' ),
726
+            'validate_callback'  => 'rest_validate_request_arg',
727
+        );
728
+        $params['orderby'] = array(
729
+            'description'        => __( 'Sort collection by object attribute.', 'invoicing' ),
730
+            'type'               => 'string',
731
+            'default'            => 'date',
732
+            'enum'               => array(
733
+                'date',
734
+                'id',
735
+                'include',
736
+                'title',
737
+                'slug',
738
+                'modified',
739
+            ),
740
+            'validate_callback'  => 'rest_validate_request_arg',
741
+        );
742
+
743
+        $post_type_obj = get_post_type_object( $this->post_type );
744
+
745
+        if ( isset( $post_type_obj->hierarchical ) && $post_type_obj->hierarchical ) {
746
+            $params['parent'] = array(
747
+                'description'       => __( 'Limit result set to those of particular parent IDs.', 'invoicing' ),
748
+                'type'              => 'array',
749
+                'items'             => array(
750
+                    'type'          => 'integer',
751
+                ),
752
+                'sanitize_callback' => 'wp_parse_id_list',
753
+                'default'           => array(),
754
+            );
755
+            $params['parent_exclude'] = array(
756
+                'description'       => __( 'Limit result set to all items except those of a particular parent ID.', 'invoicing' ),
757
+                'type'              => 'array',
758
+                'items'             => array(
759
+                    'type'          => 'integer',
760
+                ),
761
+                'sanitize_callback' => 'wp_parse_id_list',
762
+                'default'           => array(),
763
+            );
764
+        }
765
+
766
+        return $params;
767
+    }
768
+
769
+    /**
770
+     * Retrieves the items's schema, conforming to JSON Schema.
771
+     *
772
+     * @since 1.0.19
773
+     *
774
+     * @return array Item schema data.
775
+     */
776
+    public function get_item_schema() {
777
+
778
+        // Maybe retrieve the schema from cache.
779
+        if ( $this->schema ) {
780
+            return $this->add_additional_fields_schema( $this->schema );
781
+        }
782
+
783
+        $type   = str_replace( 'wpi_', '', $this->post_type );
784
+        $schema = array(
785
+            '$schema'    => 'http://json-schema.org/draft-04/schema#',
786
+            'title'      => $this->post_type,
787
+            'type'       => 'object',
788
+            'properties' => wpinv_get_data( "$type-schema" ),
789
+        );
790
+
791
+        // Filters the invoice schema for the REST API.
792 792
         $schema = apply_filters( "wpinv_rest_{$type}_schema", $schema );
793 793
 
794
-		// Cache the invoice schema.
795
-		$this->schema = $schema;
796
-
797
-		return $this->add_additional_fields_schema( $this->schema );
798
-	}
799
-
800
-	/**
801
-	 * Only return writable props from schema.
802
-	 *
803
-	 * @param  array $schema Schema.
804
-	 * @return bool
805
-	 */
806
-	public function filter_writable_props( $schema ) {
807
-		return empty( $schema['readonly'] );
808
-	}
809
-
810
-	/**
811
-	 * Sanitizes and validates the list of post statuses.
812
-	 *
813
-	 * @since 1.0.13
814
-	 *
815
-	 * @param string|array    $statuses  One or more post statuses.
816
-	 * @param WP_REST_Request $request   Full details about the request.
817
-	 * @param string          $parameter Additional parameter to pass to validation.
818
-	 * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
819
-	 */
820
-	public function sanitize_post_statuses( $statuses, $request, $parameter ) {
821
-		return array_intersect( wp_parse_slug_list( $statuses ), $this->get_post_statuses() );
822
-	}
823
-
824
-	/**
825
-	 * Retrieves a valid list of post statuses.
826
-	 *
827
-	 * @since 1.0.19
828
-	 *
829
-	 * @return array A list of registered item statuses.
830
-	 */
831
-	public function get_post_statuses() {
832
-		return get_post_stati();
833
-	}
834
-
835
-	/**
836
-	 * Prepare a single object for create or update.
837
-	 *
838
-	 * @since 1.0.19
839
-	 * @param  WP_REST_Request $request Request object.
840
-	 * @return GetPaid_Data|WP_Error Data object or WP_Error.
841
-	 */
842
-	protected function prepare_item_for_database( $request ) {
843
-
844
-		// Do we have an object?
845
-		if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
846
-			return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
847
-		}
848
-
849
-		// Prepare the object.
850
-		$id        = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
851
-		$object    = new $this->crud_class( $id );
852
-
853
-		// Abort if an error exists.
854
-		if ( ! empty( $object->last_error ) ) {
855
-			return new WP_Error( 'invalid_item', $object->last_error );
856
-		}
857
-
858
-		$schema    = $this->get_item_schema();
859
-		$data_keys = array_keys( array_filter( $schema['properties'], array( $this, 'filter_writable_props' ) ) );
860
-
861
-		// Handle all writable props.
862
-		foreach ( $data_keys as $key ) {
863
-			$value = $request[ $key ];
864
-
865
-			if ( ! is_null( $value ) ) {
866
-				switch ( $key ) {
867
-
868
-					case 'meta_data':
869
-						if ( is_array( $value ) ) {
870
-							foreach ( $value as $meta ) {
871
-								$object->update_meta_data( $meta['key'], $meta['value'], isset( $meta['id'] ) ? $meta['id'] : '' );
872
-							}
873
-						}
874
-						break;
875
-
876
-					default:
877
-						if ( is_callable( array( $object, "set_{$key}" ) ) ) {
878
-							$object->{"set_{$key}"}( $value );
879
-						}
880
-						break;
881
-				}
882
-			}
883
-
884
-		}
885
-
886
-		// Filters an object before it is inserted via the REST API..
887
-		return apply_filters( "getpaid_rest_pre_insert_{$this->post_type}_object", $object, $request );
888
-	}
889
-
890
-	/**
891
-	 * Retrieves data from a GetPaid class.
892
-	 *
893
-	 * @since  1.0.19
894
-	 * @param  GetPaid_Meta_Data[]    $meta_data  meta data objects.
895
-	 * @return array
896
-	 */
897
-	protected function prepare_object_meta_data( $meta_data ) {
898
-		$meta = array();
899
-
900
-		foreach( $meta_data as $object ) {
901
-			$meta[] = $object->get_data();
902
-		}
903
-
904
-		return $meta;
905
-	}
906
-
907
-	/**
908
-	 * Retrieves invoice items.
909
-	 *
910
-	 * @since  1.0.19
911
-	 * @param  WPInv_Invoice $invoice  Invoice items.
912
-	 * @param array            $fields Fields to include.
913
-	 * @return array
914
-	 */
915
-	protected function prepare_invoice_items( $invoice ) {
916
-		$items = array();
917
-
918
-		foreach( $invoice->get_items() as $item ) {
919
-
920
-			$item_data = $item->prepare_data_for_saving();
921
-
922
-			if ( 'amount' == $invoice->get_template() ) {
923
-				$item_data['quantity'] = 1;
924
-			}
925
-
926
-			$items[] = $item_data;
927
-		}
928
-
929
-		return $items;
930
-	}
931
-
932
-	/**
933
-	 * Retrieves data from a GetPaid class.
934
-	 *
935
-	 * @since  1.0.19
936
-	 * @param  GetPaid_Data    $object  Data object.
937
-	 * @param array            $fields Fields to include.
938
-	 * @param string           $context either view or edit.
939
-	 * @return array
940
-	 */
941
-	protected function prepare_object_data( $object, $fields, $context = 'view' ) {
942
-
943
-		$data = array();
944
-
945
-		// Handle all writable props.
946
-		foreach ( array_keys( $this->get_schema_properties() ) as $key ) {
947
-
948
-			// Abort if it is not included.
949
-			if ( ! empty( $fields ) && ! $this->is_field_included( $key, $fields ) ) {
950
-				continue;
951
-			}
952
-
953
-			// Or this current object does not support the field.
954
-			if ( ! $this->object_supports_field( $object, $key ) ) {
955
-				continue;
956
-			}
957
-
958
-			// Handle meta data.
959
-			if ( $key == 'meta_data' ) {
960
-				$data['meta_data'] = $this->prepare_object_meta_data( $object->get_meta_data() );
961
-				continue;
962
-			}
963
-
964
-			// Handle items.
965
-			if ( $key == 'items' && is_a( $object, 'WPInv_Invoice' )  ) {
966
-				$data['items'] = $this->prepare_invoice_items( $object );
967
-				continue;
968
-			}
969
-
970
-			// Booleans.
971
-			if ( is_callable( array( $object, $key ) ) ) {
972
-				$data[ $key ] = $object->$key( $context );
973
-				continue;
974
-			}
975
-
976
-			// Get object value.
977
-			if ( is_callable( array( $object, "get_{$key}" ) ) ) {
978
-				$value = $object->{"get_{$key}"}( $context );
979
-
980
-				// If the value is an instance of GetPaid_Data...
981
-				if ( is_a( $value, 'GetPaid_Data' ) ) {
982
-					$value = $value->get_data( $context );
983
-				}
984
-
985
-				// For objects, retrieves it's properties.
986
-				$data[ $key ] = is_object( $value ) ? get_object_vars( $value ) :  $value ;
987
-				continue;
988
-			}
989
-
990
-		}
991
-
992
-		return $data;
993
-	}
994
-
995
-	/**
996
-	 * Checks if a key should be included in a response.
997
-	 *
998
-	 * @since  1.0.19
999
-	 * @param  GetPaid_Data $object  Data object.
1000
-	 * @param  string       $field_key The key to check for.
1001
-	 * @return bool
1002
-	 */
1003
-	public function object_supports_field( $object, $field_key ) {
1004
-		return apply_filters( "getpaid_rest_{$this->post_type}_object_supports_key", true, $object, $field_key );
1005
-	}
1006
-
1007
-	/**
1008
-	 * Prepare a single object output for response.
1009
-	 *
1010
-	 * @since  1.0.19
1011
-	 * @param  GetPaid_Data    $object  Data object.
1012
-	 * @param  WP_REST_Request $request Request object.
1013
-	 * @return WP_REST_Response
1014
-	 */
1015
-	public function prepare_item_for_response( $object, $request ) {
1016
-
1017
-		// Fetch the fields to include in this response.
1018
-		$fields = $this->get_fields_for_response( $request );
1019
-
1020
-		// Prepare object data.
1021
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1022
-		$data    = $this->prepare_object_data( $object, $fields, $context );
1023
-		$data    = $this->add_additional_fields_to_object( $data, $request );
1024
-		$data    = $this->limit_object_to_requested_fields( $data, $fields );
1025
-		$data    = $this->filter_response_by_context( $data, $context );
1026
-
1027
-		// Prepare the response.
1028
-		$response = rest_ensure_response( $data );
1029
-		$response->add_links( $this->prepare_links( $object, $request ) );
1030
-
1031
-		// Filter item response.
1032
-		return apply_filters( "getpaid_rest_prepare_{$this->post_type}_object", $response, $object, $request );
1033
-	}
794
+        // Cache the invoice schema.
795
+        $this->schema = $schema;
796
+
797
+        return $this->add_additional_fields_schema( $this->schema );
798
+    }
799
+
800
+    /**
801
+     * Only return writable props from schema.
802
+     *
803
+     * @param  array $schema Schema.
804
+     * @return bool
805
+     */
806
+    public function filter_writable_props( $schema ) {
807
+        return empty( $schema['readonly'] );
808
+    }
809
+
810
+    /**
811
+     * Sanitizes and validates the list of post statuses.
812
+     *
813
+     * @since 1.0.13
814
+     *
815
+     * @param string|array    $statuses  One or more post statuses.
816
+     * @param WP_REST_Request $request   Full details about the request.
817
+     * @param string          $parameter Additional parameter to pass to validation.
818
+     * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
819
+     */
820
+    public function sanitize_post_statuses( $statuses, $request, $parameter ) {
821
+        return array_intersect( wp_parse_slug_list( $statuses ), $this->get_post_statuses() );
822
+    }
823
+
824
+    /**
825
+     * Retrieves a valid list of post statuses.
826
+     *
827
+     * @since 1.0.19
828
+     *
829
+     * @return array A list of registered item statuses.
830
+     */
831
+    public function get_post_statuses() {
832
+        return get_post_stati();
833
+    }
834
+
835
+    /**
836
+     * Prepare a single object for create or update.
837
+     *
838
+     * @since 1.0.19
839
+     * @param  WP_REST_Request $request Request object.
840
+     * @return GetPaid_Data|WP_Error Data object or WP_Error.
841
+     */
842
+    protected function prepare_item_for_database( $request ) {
843
+
844
+        // Do we have an object?
845
+        if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
846
+            return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
847
+        }
848
+
849
+        // Prepare the object.
850
+        $id        = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
851
+        $object    = new $this->crud_class( $id );
852
+
853
+        // Abort if an error exists.
854
+        if ( ! empty( $object->last_error ) ) {
855
+            return new WP_Error( 'invalid_item', $object->last_error );
856
+        }
857
+
858
+        $schema    = $this->get_item_schema();
859
+        $data_keys = array_keys( array_filter( $schema['properties'], array( $this, 'filter_writable_props' ) ) );
860
+
861
+        // Handle all writable props.
862
+        foreach ( $data_keys as $key ) {
863
+            $value = $request[ $key ];
864
+
865
+            if ( ! is_null( $value ) ) {
866
+                switch ( $key ) {
867
+
868
+                    case 'meta_data':
869
+                        if ( is_array( $value ) ) {
870
+                            foreach ( $value as $meta ) {
871
+                                $object->update_meta_data( $meta['key'], $meta['value'], isset( $meta['id'] ) ? $meta['id'] : '' );
872
+                            }
873
+                        }
874
+                        break;
875
+
876
+                    default:
877
+                        if ( is_callable( array( $object, "set_{$key}" ) ) ) {
878
+                            $object->{"set_{$key}"}( $value );
879
+                        }
880
+                        break;
881
+                }
882
+            }
883
+
884
+        }
885
+
886
+        // Filters an object before it is inserted via the REST API..
887
+        return apply_filters( "getpaid_rest_pre_insert_{$this->post_type}_object", $object, $request );
888
+    }
889
+
890
+    /**
891
+     * Retrieves data from a GetPaid class.
892
+     *
893
+     * @since  1.0.19
894
+     * @param  GetPaid_Meta_Data[]    $meta_data  meta data objects.
895
+     * @return array
896
+     */
897
+    protected function prepare_object_meta_data( $meta_data ) {
898
+        $meta = array();
899
+
900
+        foreach( $meta_data as $object ) {
901
+            $meta[] = $object->get_data();
902
+        }
903
+
904
+        return $meta;
905
+    }
906
+
907
+    /**
908
+     * Retrieves invoice items.
909
+     *
910
+     * @since  1.0.19
911
+     * @param  WPInv_Invoice $invoice  Invoice items.
912
+     * @param array            $fields Fields to include.
913
+     * @return array
914
+     */
915
+    protected function prepare_invoice_items( $invoice ) {
916
+        $items = array();
917
+
918
+        foreach( $invoice->get_items() as $item ) {
919
+
920
+            $item_data = $item->prepare_data_for_saving();
921
+
922
+            if ( 'amount' == $invoice->get_template() ) {
923
+                $item_data['quantity'] = 1;
924
+            }
925
+
926
+            $items[] = $item_data;
927
+        }
928
+
929
+        return $items;
930
+    }
931
+
932
+    /**
933
+     * Retrieves data from a GetPaid class.
934
+     *
935
+     * @since  1.0.19
936
+     * @param  GetPaid_Data    $object  Data object.
937
+     * @param array            $fields Fields to include.
938
+     * @param string           $context either view or edit.
939
+     * @return array
940
+     */
941
+    protected function prepare_object_data( $object, $fields, $context = 'view' ) {
942
+
943
+        $data = array();
944
+
945
+        // Handle all writable props.
946
+        foreach ( array_keys( $this->get_schema_properties() ) as $key ) {
947
+
948
+            // Abort if it is not included.
949
+            if ( ! empty( $fields ) && ! $this->is_field_included( $key, $fields ) ) {
950
+                continue;
951
+            }
952
+
953
+            // Or this current object does not support the field.
954
+            if ( ! $this->object_supports_field( $object, $key ) ) {
955
+                continue;
956
+            }
957
+
958
+            // Handle meta data.
959
+            if ( $key == 'meta_data' ) {
960
+                $data['meta_data'] = $this->prepare_object_meta_data( $object->get_meta_data() );
961
+                continue;
962
+            }
963
+
964
+            // Handle items.
965
+            if ( $key == 'items' && is_a( $object, 'WPInv_Invoice' )  ) {
966
+                $data['items'] = $this->prepare_invoice_items( $object );
967
+                continue;
968
+            }
969
+
970
+            // Booleans.
971
+            if ( is_callable( array( $object, $key ) ) ) {
972
+                $data[ $key ] = $object->$key( $context );
973
+                continue;
974
+            }
975
+
976
+            // Get object value.
977
+            if ( is_callable( array( $object, "get_{$key}" ) ) ) {
978
+                $value = $object->{"get_{$key}"}( $context );
979
+
980
+                // If the value is an instance of GetPaid_Data...
981
+                if ( is_a( $value, 'GetPaid_Data' ) ) {
982
+                    $value = $value->get_data( $context );
983
+                }
984
+
985
+                // For objects, retrieves it's properties.
986
+                $data[ $key ] = is_object( $value ) ? get_object_vars( $value ) :  $value ;
987
+                continue;
988
+            }
989
+
990
+        }
991
+
992
+        return $data;
993
+    }
994
+
995
+    /**
996
+     * Checks if a key should be included in a response.
997
+     *
998
+     * @since  1.0.19
999
+     * @param  GetPaid_Data $object  Data object.
1000
+     * @param  string       $field_key The key to check for.
1001
+     * @return bool
1002
+     */
1003
+    public function object_supports_field( $object, $field_key ) {
1004
+        return apply_filters( "getpaid_rest_{$this->post_type}_object_supports_key", true, $object, $field_key );
1005
+    }
1006
+
1007
+    /**
1008
+     * Prepare a single object output for response.
1009
+     *
1010
+     * @since  1.0.19
1011
+     * @param  GetPaid_Data    $object  Data object.
1012
+     * @param  WP_REST_Request $request Request object.
1013
+     * @return WP_REST_Response
1014
+     */
1015
+    public function prepare_item_for_response( $object, $request ) {
1016
+
1017
+        // Fetch the fields to include in this response.
1018
+        $fields = $this->get_fields_for_response( $request );
1019
+
1020
+        // Prepare object data.
1021
+        $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1022
+        $data    = $this->prepare_object_data( $object, $fields, $context );
1023
+        $data    = $this->add_additional_fields_to_object( $data, $request );
1024
+        $data    = $this->limit_object_to_requested_fields( $data, $fields );
1025
+        $data    = $this->filter_response_by_context( $data, $context );
1026
+
1027
+        // Prepare the response.
1028
+        $response = rest_ensure_response( $data );
1029
+        $response->add_links( $this->prepare_links( $object, $request ) );
1030
+
1031
+        // Filter item response.
1032
+        return apply_filters( "getpaid_rest_prepare_{$this->post_type}_object", $response, $object, $request );
1033
+    }
1034 1034
 
1035 1035
 }
Please login to merge, or discard this patch.
Spacing   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  * @version 1.0.19
9 9
  */
10 10
 
11
-defined( 'ABSPATH' ) || exit;
11
+defined('ABSPATH') || exit;
12 12
 
13 13
 /**
14 14
  * GetPaid REST Posts controller class.
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 	 *
46 46
 	 * @see register_rest_route()
47 47
 	 */
48
-	public function register_namespace_routes( $namespace ) {
48
+	public function register_namespace_routes($namespace) {
49 49
 
50 50
 		register_rest_route(
51 51
 			$namespace,
@@ -53,22 +53,22 @@  discard block
 block discarded – undo
53 53
 			array(
54 54
 				array(
55 55
 					'methods'             => WP_REST_Server::READABLE,
56
-					'callback'            => array( $this, 'get_items' ),
57
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
56
+					'callback'            => array($this, 'get_items'),
57
+					'permission_callback' => array($this, 'get_items_permissions_check'),
58 58
 					'args'                => $this->get_collection_params(),
59 59
 				),
60 60
 				array(
61 61
 					'methods'             => WP_REST_Server::CREATABLE,
62
-					'callback'            => array( $this, 'create_item' ),
63
-					'permission_callback' => array( $this, 'create_item_permissions_check' ),
64
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
62
+					'callback'            => array($this, 'create_item'),
63
+					'permission_callback' => array($this, 'create_item_permissions_check'),
64
+					'args'                => $this->get_endpoint_args_for_item_schema(WP_REST_Server::CREATABLE),
65 65
 				),
66
-				'schema' => array( $this, 'get_public_item_schema' ),
66
+				'schema' => array($this, 'get_public_item_schema'),
67 67
 			)
68 68
 		);
69 69
 
70 70
 		$get_item_args = array(
71
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
71
+			'context' => $this->get_context_param(array('default' => 'view')),
72 72
 		);
73 73
 
74 74
 		register_rest_route(
@@ -77,35 +77,35 @@  discard block
 block discarded – undo
77 77
 			array(
78 78
 				'args'   => array(
79 79
 					'id' => array(
80
-						'description' => __( 'Unique identifier for the object.', 'invoicing' ),
80
+						'description' => __('Unique identifier for the object.', 'invoicing'),
81 81
 						'type'        => 'integer',
82 82
 					),
83 83
 				),
84 84
 				array(
85 85
 					'methods'             => WP_REST_Server::READABLE,
86
-					'callback'            => array( $this, 'get_item' ),
87
-					'permission_callback' => array( $this, 'get_item_permissions_check' ),
86
+					'callback'            => array($this, 'get_item'),
87
+					'permission_callback' => array($this, 'get_item_permissions_check'),
88 88
 					'args'                => $get_item_args,
89 89
 				),
90 90
 				array(
91 91
 					'methods'             => WP_REST_Server::EDITABLE,
92
-					'callback'            => array( $this, 'update_item' ),
93
-					'permission_callback' => array( $this, 'update_item_permissions_check' ),
94
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
92
+					'callback'            => array($this, 'update_item'),
93
+					'permission_callback' => array($this, 'update_item_permissions_check'),
94
+					'args'                => $this->get_endpoint_args_for_item_schema(WP_REST_Server::EDITABLE),
95 95
 				),
96 96
 				array(
97 97
 					'methods'             => WP_REST_Server::DELETABLE,
98
-					'callback'            => array( $this, 'delete_item' ),
99
-					'permission_callback' => array( $this, 'delete_item_permissions_check' ),
98
+					'callback'            => array($this, 'delete_item'),
99
+					'permission_callback' => array($this, 'delete_item_permissions_check'),
100 100
 					'args'                => array(
101 101
 						'force' => array(
102 102
 							'type'        => 'boolean',
103 103
 							'default'     => false,
104
-							'description' => __( 'Whether to bypass Trash and force deletion.', 'invoicing' ),
104
+							'description' => __('Whether to bypass Trash and force deletion.', 'invoicing'),
105 105
 						),
106 106
 					),
107 107
 				),
108
-				'schema' => array( $this, 'get_public_item_schema' ),
108
+				'schema' => array($this, 'get_public_item_schema'),
109 109
 			)
110 110
 		);
111 111
 
@@ -115,11 +115,11 @@  discard block
 block discarded – undo
115 115
 			array(
116 116
 				array(
117 117
 					'methods'             => WP_REST_Server::EDITABLE,
118
-					'callback'            => array( $this, 'batch_items' ),
119
-					'permission_callback' => array( $this, 'batch_items_permissions_check' ),
120
-					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
118
+					'callback'            => array($this, 'batch_items'),
119
+					'permission_callback' => array($this, 'batch_items_permissions_check'),
120
+					'args'                => $this->get_endpoint_args_for_item_schema(WP_REST_Server::EDITABLE),
121 121
 				),
122
-				'schema' => array( $this, 'get_public_batch_schema' ),
122
+				'schema' => array($this, 'get_public_batch_schema'),
123 123
 			)
124 124
 		);
125 125
 
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	 * @param int    $object_id Post ID.
134 134
 	 * @return bool
135 135
 	 */
136
-	public function check_post_permissions( $context = 'read', $object_id = 0 ) {
136
+	public function check_post_permissions($context = 'read', $object_id = 0) {
137 137
 
138 138
 		$contexts = array(
139 139
 			'read'   => 'read_private_posts',
@@ -143,15 +143,15 @@  discard block
 block discarded – undo
143 143
 			'batch'  => 'edit_others_posts',
144 144
 		);
145 145
 
146
-		if ( 'revision' === $this->post_type ) {
146
+		if ('revision' === $this->post_type) {
147 147
 			$permission = false;
148 148
 		} else {
149
-			$cap              = $contexts[ $context ];
150
-			$post_type_object = get_post_type_object( $this->post_type );
151
-			$permission       = current_user_can( $post_type_object->cap->$cap, $object_id );
149
+			$cap              = $contexts[$context];
150
+			$post_type_object = get_post_type_object($this->post_type);
151
+			$permission       = current_user_can($post_type_object->cap->$cap, $object_id);
152 152
 		}
153 153
 
154
-		return apply_filters( 'getpaid_rest_check_permissions', $permission, $context, $object_id, $this->post_type );
154
+		return apply_filters('getpaid_rest_check_permissions', $permission, $context, $object_id, $this->post_type);
155 155
 	}
156 156
 
157 157
 	/**
@@ -160,8 +160,8 @@  discard block
 block discarded – undo
160 160
 	 * @param  WP_REST_Request $request Full details about the request.
161 161
 	 * @return WP_Error|boolean
162 162
 	 */
163
-	public function get_items_permissions_check( $request ) {
164
-		return $this->check_post_permissions() ? true : new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
163
+	public function get_items_permissions_check($request) {
164
+		return $this->check_post_permissions() ? true : new WP_Error('rest_cannot_view', __('Sorry, you cannot list resources.', 'invoicing'), array('status' => rest_authorization_required_code()));
165 165
 	}
166 166
 
167 167
 	/**
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 	 * @param  WP_REST_Request $request Full details about the request.
171 171
 	 * @return WP_Error|boolean
172 172
 	 */
173
-	public function create_item_permissions_check( $request ) {
174
-		return $this->check_post_permissions( 'create' ) ? true : new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
173
+	public function create_item_permissions_check($request) {
174
+		return $this->check_post_permissions('create') ? true : new WP_Error('rest_cannot_create', __('Sorry, you are not allowed to create resources.', 'invoicing'), array('status' => rest_authorization_required_code()));
175 175
 	}
176 176
 
177 177
 	/**
@@ -180,11 +180,11 @@  discard block
 block discarded – undo
180 180
 	 * @param  WP_REST_Request $request Full details about the request.
181 181
 	 * @return WP_Error|boolean
182 182
 	 */
183
-	public function get_item_permissions_check( $request ) {
184
-		$post = get_post( (int) $request['id'] );
183
+	public function get_item_permissions_check($request) {
184
+		$post = get_post((int) $request['id']);
185 185
 
186
-		if ( $post && ! $this->check_post_permissions( 'read', $post->ID ) ) {
187
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
186
+		if ($post && !$this->check_post_permissions('read', $post->ID)) {
187
+			return new WP_Error('rest_cannot_view', __('Sorry, you cannot view this resource.', 'invoicing'), array('status' => rest_authorization_required_code()));
188 188
 		}
189 189
 
190 190
 		return true;
@@ -196,11 +196,11 @@  discard block
 block discarded – undo
196 196
 	 * @param  WP_REST_Request $request Full details about the request.
197 197
 	 * @return WP_Error|boolean
198 198
 	 */
199
-	public function update_item_permissions_check( $request ) {
200
-		$post = get_post( (int) $request['id'] );
199
+	public function update_item_permissions_check($request) {
200
+		$post = get_post((int) $request['id']);
201 201
 
202
-		if ( $post && ! $this->check_post_permissions( 'edit', $post->ID ) ) {
203
-			return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
202
+		if ($post && !$this->check_post_permissions('edit', $post->ID)) {
203
+			return new WP_Error('rest_cannot_edit', __('Sorry, you are not allowed to edit this resource.', 'invoicing'), array('status' => rest_authorization_required_code()));
204 204
 		}
205 205
 
206 206
 		return true;
@@ -212,11 +212,11 @@  discard block
 block discarded – undo
212 212
 	 * @param  WP_REST_Request $request Full details about the request.
213 213
 	 * @return bool|WP_Error
214 214
 	 */
215
-	public function delete_item_permissions_check( $request ) {
216
-		$post = get_post( (int) $request['id'] );
215
+	public function delete_item_permissions_check($request) {
216
+		$post = get_post((int) $request['id']);
217 217
 
218
-		if ( $post && ! $this->check_post_permissions( 'delete', $post->ID ) ) {
219
-			return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
218
+		if ($post && !$this->check_post_permissions('delete', $post->ID)) {
219
+			return new WP_Error('rest_cannot_delete', __('Sorry, you are not allowed to delete this resource.', 'invoicing'), array('status' => rest_authorization_required_code()));
220 220
 		}
221 221
 
222 222
 		return true;
@@ -229,8 +229,8 @@  discard block
 block discarded – undo
229 229
 	 *
230 230
 	 * @return boolean|WP_Error
231 231
 	 */
232
-	public function batch_items_permissions_check( $request ) {
233
-		return $this->check_post_permissions( 'batch' ) ? true : new WP_Error( 'rest_cannot_batch', __( 'Sorry, you are not allowed to batch manipulate this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
232
+	public function batch_items_permissions_check($request) {
233
+		return $this->check_post_permissions('batch') ? true : new WP_Error('rest_cannot_batch', __('Sorry, you are not allowed to batch manipulate this resource.', 'invoicing'), array('status' => rest_authorization_required_code()));
234 234
 	}
235 235
 
236 236
 	/**
@@ -239,14 +239,14 @@  discard block
 block discarded – undo
239 239
 	 * @param GetPaid_Data $object Object to save.
240 240
 	 * @return WP_Error|GetPaid_Data
241 241
 	 */
242
-	protected function save_object( $object ) {
242
+	protected function save_object($object) {
243 243
 		$object->save();
244 244
 
245
-		if ( ! empty( $object->last_error ) ) {
246
-			return new WP_Error( 'rest_cannot_save', $object->last_error, array( 'status' => 400 ) );
245
+		if (!empty($object->last_error)) {
246
+			return new WP_Error('rest_cannot_save', $object->last_error, array('status' => 400));
247 247
 		}
248 248
 
249
-		return new $this->crud_class( $object->get_id() );
249
+		return new $this->crud_class($object->get_id());
250 250
 	}
251 251
 
252 252
 	/**
@@ -258,28 +258,28 @@  discard block
 block discarded – undo
258 258
 	 * @param int|WP_Post $object_id Supplied ID.
259 259
 	 * @return GetPaid_Data|WP_Error GetPaid_Data object if ID is valid, WP_Error otherwise.
260 260
 	 */
261
-	protected function get_object( $object_id ) {
261
+	protected function get_object($object_id) {
262 262
 
263 263
 		// Do we have an object?
264
-		if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
265
-			return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
264
+		if (empty($this->crud_class) || !class_exists($this->crud_class)) {
265
+			return new WP_Error('no_crud_class', __('You need to specify a CRUD class for this controller', 'invoicing'));
266 266
 		}
267 267
 
268 268
 		// Fetch the object.
269
-		$object = new $this->crud_class( $object_id );
270
-		if ( ! empty( $object->last_error ) ) {
271
-			return new WP_Error( 'rest_object_invalid_id', $object->last_error, array( 'status' => 404 ) );
269
+		$object = new $this->crud_class($object_id);
270
+		if (!empty($object->last_error)) {
271
+			return new WP_Error('rest_object_invalid_id', $object->last_error, array('status' => 404));
272 272
 		}
273 273
 
274
-		return $object->get_id() ? $object : new WP_Error( 'rest_object_invalid_id', __( 'Invalid ID.', 'invoicing' ), array( 'status' => 404 ) );
274
+		return $object->get_id() ? $object : new WP_Error('rest_object_invalid_id', __('Invalid ID.', 'invoicing'), array('status' => 404));
275 275
 
276 276
 	}
277 277
 
278 278
 	/**
279 279
 	 * @deprecated
280 280
 	 */
281
-	public function get_post( $object_id ) {
282
-		return $this->get_object( $object_id );
281
+	public function get_post($object_id) {
282
+		return $this->get_object($object_id);
283 283
     }
284 284
 
285 285
 	/**
@@ -288,23 +288,23 @@  discard block
 block discarded – undo
288 288
 	 * @param WP_REST_Request $request Full details about the request.
289 289
 	 * @return WP_Error|WP_REST_Response
290 290
 	 */
291
-	public function get_item( $request ) {
292
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
291
+	public function get_item($request) {
292
+		remove_filter('rest_post_dispatch', 'rest_filter_response_fields', 10, 3);
293 293
 
294 294
 		// Fetch the item.
295
-		$object = $this->get_object( $request['id'] );
295
+		$object = $this->get_object($request['id']);
296 296
 
297
-		if ( is_wp_error( $object ) ) {
297
+		if (is_wp_error($object)) {
298 298
 			return $object;
299 299
 		}
300 300
 
301 301
 		// Generate a response.
302
-		$data     = $this->prepare_item_for_response( $object, $request );
303
-		$response = rest_ensure_response( $data );
302
+		$data     = $this->prepare_item_for_response($object, $request);
303
+		$response = rest_ensure_response($data);
304 304
 
305 305
 		// (Maybe) add a link to the html pagee.
306
-		if ( $this->public && ! is_wp_error( $response ) ) {
307
-			$response->link_header( 'alternate', get_permalink( $object->get_id() ), array( 'type' => 'text/html' ) );
306
+		if ($this->public && !is_wp_error($response)) {
307
+			$response->link_header('alternate', get_permalink($object->get_id()), array('type' => 'text/html'));
308 308
 		}
309 309
 
310 310
 		return $response;
@@ -316,31 +316,31 @@  discard block
 block discarded – undo
316 316
 	 * @param WP_REST_Request $request Full details about the request.
317 317
 	 * @return WP_Error|WP_REST_Response
318 318
 	 */
319
-	public function create_item( $request ) {
320
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
319
+	public function create_item($request) {
320
+		remove_filter('rest_post_dispatch', 'rest_filter_response_fields', 10, 3);
321 321
 
322 322
 		// Can not create an existing item.
323
-		if ( ! empty( $request['id'] ) ) {
323
+		if (!empty($request['id'])) {
324 324
 			/* translators: %s: post type */
325
-			return new WP_Error( "getpaid_rest_{$this->post_type}_exists", __( 'Cannot create existing resource.', 'invoicing' ), array( 'status' => 400 ) );
325
+			return new WP_Error("getpaid_rest_{$this->post_type}_exists", __('Cannot create existing resource.', 'invoicing'), array('status' => 400));
326 326
 		}
327 327
 
328 328
 		// Generate a GetPaid_Data object from the request.
329
-		$object = $this->prepare_item_for_database( $request );
330
-		if ( is_wp_error( $object ) ) {
329
+		$object = $this->prepare_item_for_database($request);
330
+		if (is_wp_error($object)) {
331 331
 			return $object;
332 332
 		}
333 333
 
334 334
 		// Save the object.
335
-		$object = $this->save_object( $object );
336
-		if ( is_wp_error( $object ) ) {
335
+		$object = $this->save_object($object);
336
+		if (is_wp_error($object)) {
337 337
 			return $object;
338 338
 		}
339 339
 
340 340
 		// Save special fields.
341
-		$save_special = $this->update_additional_fields_for_object( $object, $request );
342
-		if ( is_wp_error( $save_special ) ) {
343
-			$object->delete( true );
341
+		$save_special = $this->update_additional_fields_for_object($object, $request);
342
+		if (is_wp_error($save_special)) {
343
+			$object->delete(true);
344 344
 			return $save_special;
345 345
 		}
346 346
 
@@ -351,13 +351,13 @@  discard block
 block discarded – undo
351 351
 		 * @param WP_REST_Request $request   Request object.
352 352
 		 * @param boolean         $creating  True when creating item, false when updating.
353 353
 		 */
354
-		do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, true );
354
+		do_action("getpaid_rest_insert_{$this->post_type}", $object, $request, true);
355 355
 
356
-		$request->set_param( 'context', 'edit' );
357
-		$response = $this->prepare_item_for_response( $object, $request );
358
-		$response = rest_ensure_response( $response );
359
-		$response->set_status( 201 );
360
-		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ) );
356
+		$request->set_param('context', 'edit');
357
+		$response = $this->prepare_item_for_response($object, $request);
358
+		$response = rest_ensure_response($response);
359
+		$response->set_status(201);
360
+		$response->header('Location', rest_url(sprintf('/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id())));
361 361
 
362 362
 		return $response;
363 363
 	}
@@ -368,30 +368,30 @@  discard block
 block discarded – undo
368 368
 	 * @param WP_REST_Request $request Full details about the request.
369 369
 	 * @return WP_Error|WP_REST_Response
370 370
 	 */
371
-	public function update_item( $request ) {
372
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
371
+	public function update_item($request) {
372
+		remove_filter('rest_post_dispatch', 'rest_filter_response_fields', 10, 3);
373 373
 
374 374
 		// Fetch the item.
375
-		$object = $this->get_object( $request['id'] );
376
-		if ( is_wp_error( $object ) ) {
375
+		$object = $this->get_object($request['id']);
376
+		if (is_wp_error($object)) {
377 377
 			return $object;
378 378
 		}
379 379
 
380 380
 		// Prepare the item for saving.
381
-		$object = $this->prepare_item_for_database( $request );
382
-		if ( is_wp_error( $object ) ) {
381
+		$object = $this->prepare_item_for_database($request);
382
+		if (is_wp_error($object)) {
383 383
 			return $object;
384 384
 		}
385 385
 
386 386
 		// Save the item.
387
-		$object = $this->save_object( $object );
388
-		if ( is_wp_error( $object ) ) {
387
+		$object = $this->save_object($object);
388
+		if (is_wp_error($object)) {
389 389
 			return $object;
390 390
 		}
391 391
 
392 392
 		// Save special fields (those added via hooks).
393
-		$save_special = $this->update_additional_fields_for_object( $object, $request );
394
-		if ( is_wp_error( $save_special ) ) {
393
+		$save_special = $this->update_additional_fields_for_object($object, $request);
394
+		if (is_wp_error($save_special)) {
395 395
 			return $save_special;
396 396
 		}
397 397
 
@@ -402,11 +402,11 @@  discard block
 block discarded – undo
402 402
 		 * @param WP_REST_Request $request   Request object.
403 403
 		 * @param boolean         $creating  True when creating item, false when updating.
404 404
 		 */
405
-		do_action( "getpaid_rest_insert_{$this->post_type}", $object, $request, false );
405
+		do_action("getpaid_rest_insert_{$this->post_type}", $object, $request, false);
406 406
 
407
-		$request->set_param( 'context', 'edit' );
408
-		$response = $this->prepare_item_for_response( $object, $request );
409
-		return rest_ensure_response( $response );
407
+		$request->set_param('context', 'edit');
408
+		$response = $this->prepare_item_for_response($object, $request);
409
+		return rest_ensure_response($response);
410 410
 	}
411 411
 
412 412
 	/**
@@ -415,8 +415,8 @@  discard block
 block discarded – undo
415 415
 	 * @param WP_REST_Request $request Full details about the request.
416 416
 	 * @return WP_Error|WP_REST_Response
417 417
 	 */
418
-	public function get_items( $request ) {
419
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
418
+	public function get_items($request) {
419
+		remove_filter('rest_post_dispatch', 'rest_filter_response_fields', 10, 3);
420 420
 
421 421
 		$args                         = array();
422 422
 		$args['offset']               = $request['offset'];
@@ -430,16 +430,16 @@  discard block
 block discarded – undo
430 430
 		$args['post_parent__in']      = $request['parent'];
431 431
 		$args['post_parent__not_in']  = $request['parent_exclude'];
432 432
 		$args['s']                    = $request['search'];
433
-		$args['post_status']          = wpinv_parse_list( $request['status'] );
433
+		$args['post_status']          = wpinv_parse_list($request['status']);
434 434
 
435 435
 		$args['date_query'] = array();
436 436
 		// Set before into date query. Date query must be specified as an array of an array.
437
-		if ( isset( $request['before'] ) ) {
437
+		if (isset($request['before'])) {
438 438
 			$args['date_query'][0]['before'] = $request['before'];
439 439
 		}
440 440
 
441 441
 		// Set after into date query. Date query must be specified as an array of an array.
442
-		if ( isset( $request['after'] ) ) {
442
+		if (isset($request['after'])) {
443 443
 			$args['date_query'][0]['after'] = $request['after'];
444 444
 		}
445 445
 
@@ -448,54 +448,54 @@  discard block
 block discarded – undo
448 448
 		$args['fields']    = 'ids';
449 449
 
450 450
 		// Filter the query arguments for a request.
451
-		$args       = apply_filters( "getpaid_rest_{$this->post_type}_query", $args, $request );
452
-		$query_args = $this->prepare_items_query( $args, $request );
451
+		$args       = apply_filters("getpaid_rest_{$this->post_type}_query", $args, $request);
452
+		$query_args = $this->prepare_items_query($args, $request);
453 453
 
454 454
 		$posts_query = new WP_Query();
455
-		$query_result = $posts_query->query( $query_args );
455
+		$query_result = $posts_query->query($query_args);
456 456
 
457 457
 		$posts = array();
458
-		foreach ( $query_result as $post_id ) {
459
-			if ( ! $this->check_post_permissions( 'read', $post_id ) ) {
458
+		foreach ($query_result as $post_id) {
459
+			if (!$this->check_post_permissions('read', $post_id)) {
460 460
 				continue;
461 461
 			}
462 462
 
463
-			$data    = $this->prepare_item_for_response( $this->get_object( $post_id ), $request );
464
-			$posts[] = $this->prepare_response_for_collection( $data );
463
+			$data    = $this->prepare_item_for_response($this->get_object($post_id), $request);
464
+			$posts[] = $this->prepare_response_for_collection($data);
465 465
 		}
466 466
 
467 467
 		$page        = (int) $query_args['paged'];
468 468
 		$total_posts = $posts_query->found_posts;
469 469
 
470
-		if ( $total_posts < 1 ) {
470
+		if ($total_posts < 1) {
471 471
 			// Out-of-bounds, run the query again without LIMIT for total count.
472
-			unset( $query_args['paged'] );
472
+			unset($query_args['paged']);
473 473
 			$count_query = new WP_Query();
474
-			$count_query->query( $query_args );
474
+			$count_query->query($query_args);
475 475
 			$total_posts = $count_query->found_posts;
476 476
 		}
477 477
 
478
-		$max_pages = ceil( $total_posts / (int) $query_args['posts_per_page'] );
478
+		$max_pages = ceil($total_posts / (int) $query_args['posts_per_page']);
479 479
 
480
-		$response = rest_ensure_response( $posts );
481
-		$response->header( 'X-WP-Total', (int) $total_posts );
482
-		$response->header( 'X-WP-TotalPages', (int) $max_pages );
480
+		$response = rest_ensure_response($posts);
481
+		$response->header('X-WP-Total', (int) $total_posts);
482
+		$response->header('X-WP-TotalPages', (int) $max_pages);
483 483
 
484 484
 		$request_params = $request->get_query_params();
485
-		$base = add_query_arg( $request_params, rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
485
+		$base = add_query_arg($request_params, rest_url(sprintf('/%s/%s', $this->namespace, $this->rest_base)));
486 486
 
487
-		if ( $page > 1 ) {
487
+		if ($page > 1) {
488 488
 			$prev_page = $page - 1;
489
-			if ( $prev_page > $max_pages ) {
489
+			if ($prev_page > $max_pages) {
490 490
 				$prev_page = $max_pages;
491 491
 			}
492
-			$prev_link = add_query_arg( 'page', $prev_page, $base );
493
-			$response->link_header( 'prev', $prev_link );
492
+			$prev_link = add_query_arg('page', $prev_page, $base);
493
+			$response->link_header('prev', $prev_link);
494 494
 		}
495
-		if ( $max_pages > $page ) {
495
+		if ($max_pages > $page) {
496 496
 			$next_page = $page + 1;
497
-			$next_link = add_query_arg( 'page', $next_page, $base );
498
-			$response->link_header( 'next', $next_link );
497
+			$next_link = add_query_arg('page', $next_page, $base);
498
+			$response->link_header('next', $next_link);
499 499
 		}
500 500
 
501 501
 		return $response;
@@ -507,27 +507,27 @@  discard block
 block discarded – undo
507 507
 	 * @param WP_REST_Request $request Full details about the request.
508 508
 	 * @return WP_REST_Response|WP_Error
509 509
 	 */
510
-	public function delete_item( $request ) {
511
-		remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
510
+	public function delete_item($request) {
511
+		remove_filter('rest_post_dispatch', 'rest_filter_response_fields', 10, 3);
512 512
 
513 513
 		// Fetch the item.
514
-		$item = $this->get_object( $request['id'] );
515
-		if ( is_wp_error( $item ) ) {
514
+		$item = $this->get_object($request['id']);
515
+		if (is_wp_error($item)) {
516 516
 			return $item;
517 517
 		}
518 518
 
519 519
 		$supports_trash = EMPTY_TRASH_DAYS > 0;
520 520
 		$force          = $supports_trash && (bool) $request['force'];
521 521
 
522
-		if ( ! $this->check_post_permissions( 'delete', $item->ID ) ) {
523
-			return new WP_Error( "cannot_delete", __( 'Sorry, you are not allowed to delete this resource.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
522
+		if (!$this->check_post_permissions('delete', $item->ID)) {
523
+			return new WP_Error("cannot_delete", __('Sorry, you are not allowed to delete this resource.', 'invoicing'), array('status' => rest_authorization_required_code()));
524 524
 		}
525 525
 
526
-		$request->set_param( 'context', 'edit' );
527
-		$response = $this->prepare_item_for_response( $item, $request );
526
+		$request->set_param('context', 'edit');
527
+		$response = $this->prepare_item_for_response($item, $request);
528 528
 
529
-		if ( ! wp_delete_post( $item->ID, $force ) ) {
530
-			return new WP_Error( 'rest_cannot_delete', sprintf( __( 'The resource cannot be deleted.', 'invoicing' ), $this->post_type ), array( 'status' => 500 ) );
529
+		if (!wp_delete_post($item->ID, $force)) {
530
+			return new WP_Error('rest_cannot_delete', sprintf(__('The resource cannot be deleted.', 'invoicing'), $this->post_type), array('status' => 500));
531 531
 		}
532 532
 
533 533
 		return $response;
@@ -539,34 +539,34 @@  discard block
 block discarded – undo
539 539
 	 * @param GetPaid_Data    $object GetPaid_Data object.
540 540
 	 * @return array Links for the given object.
541 541
 	 */
542
-	protected function prepare_links( $object ) {
542
+	protected function prepare_links($object) {
543 543
 
544 544
 		$links = array(
545 545
 			'self'       => array(
546
-				'href'   => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ),
546
+				'href'   => rest_url(sprintf('/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id())),
547 547
 			),
548 548
 			'collection' => array(
549
-				'href'   => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
549
+				'href'   => rest_url(sprintf('/%s/%s', $this->namespace, $this->rest_base)),
550 550
 			),
551 551
 		);
552 552
 
553
-		if ( is_callable( array( $object, 'get_user_id' ) ) ) {
553
+		if (is_callable(array($object, 'get_user_id'))) {
554 554
 			$links['user'] = array(
555
-				'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_user_id' )  ) ),
555
+				'href'       => rest_url('wp/v2/users/' . call_user_func(array($object, 'get_user_id'))),
556 556
 				'embeddable' => true,
557 557
 			);
558 558
 		}
559 559
 
560
-		if ( is_callable( array( $object, 'get_owner' ) ) ) {
561
-			$links['owner']  = array(
562
-				'href'       => rest_url( 'wp/v2/users/' . call_user_func(  array( $object, 'get_owner' )  ) ),
560
+		if (is_callable(array($object, 'get_owner'))) {
561
+			$links['owner'] = array(
562
+				'href'       => rest_url('wp/v2/users/' . call_user_func(array($object, 'get_owner'))),
563 563
 				'embeddable' => true,
564 564
 			);
565 565
 		}
566 566
 
567
-		if ( is_callable( array( $object, 'get_parent_id' ) ) && call_user_func(  array( $object, 'get_parent_id' )  ) ) {
568
-			$links['parent']  = array(
569
-				'href'       => rest_url( "$this->namespace/$this->rest_base/" . call_user_func(  array( $object, 'get_parent_id' )  ) ),
567
+		if (is_callable(array($object, 'get_parent_id')) && call_user_func(array($object, 'get_parent_id'))) {
568
+			$links['parent'] = array(
569
+				'href'       => rest_url("$this->namespace/$this->rest_base/" . call_user_func(array($object, 'get_parent_id'))),
570 570
 				'embeddable' => true,
571 571
 			);
572 572
 		}
@@ -582,27 +582,27 @@  discard block
 block discarded – undo
582 582
 	 * @param WP_REST_Request $request Request object.
583 583
 	 * @return array          $query_args
584 584
 	 */
585
-	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
585
+	protected function prepare_items_query($prepared_args = array(), $request = null) {
586 586
 
587
-		$valid_vars = array_flip( $this->get_allowed_query_vars() );
587
+		$valid_vars = array_flip($this->get_allowed_query_vars());
588 588
 		$query_args = array();
589
-		foreach ( $valid_vars as $var => $index ) {
590
-			if ( isset( $prepared_args[ $var ] ) ) {
591
-				$query_args[ $var ] = apply_filters( "getpaid_rest_query_var-{$var}", $prepared_args[ $var ] );
589
+		foreach ($valid_vars as $var => $index) {
590
+			if (isset($prepared_args[$var])) {
591
+				$query_args[$var] = apply_filters("getpaid_rest_query_var-{$var}", $prepared_args[$var]);
592 592
 			}
593 593
 		}
594 594
 
595 595
 		$query_args['ignore_sticky_posts'] = true;
596 596
 
597
-		if ( 'include' === $query_args['orderby'] ) {
597
+		if ('include' === $query_args['orderby']) {
598 598
 			$query_args['orderby'] = 'post__in';
599
-		} elseif ( 'id' === $query_args['orderby'] ) {
599
+		} elseif ('id' === $query_args['orderby']) {
600 600
 			$query_args['orderby'] = 'ID'; // ID must be capitalized.
601
-		} elseif ( 'slug' === $query_args['orderby'] ) {
601
+		} elseif ('slug' === $query_args['orderby']) {
602 602
 			$query_args['orderby'] = 'name';
603 603
 		}
604 604
 
605
-		return apply_filters( 'getpaid_rest_prepare_items_query', $query_args, $request, $this );
605
+		return apply_filters('getpaid_rest_prepare_items_query', $query_args, $request, $this);
606 606
 
607 607
 	}
608 608
 
@@ -621,12 +621,12 @@  discard block
 block discarded – undo
621 621
 		 *
622 622
 		 * @param array  Array of allowed WP_Query query vars.
623 623
 		 */
624
-		$valid_vars = apply_filters( 'query_vars', $wp->public_query_vars );
624
+		$valid_vars = apply_filters('query_vars', $wp->public_query_vars);
625 625
 
626
-		$post_type_obj = get_post_type_object( $this->post_type );
627
-		if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
628
-			$private = apply_filters( 'getpaid_rest_private_query_vars', $wp->private_query_vars );
629
-			$valid_vars = array_merge( $valid_vars, $private );
626
+		$post_type_obj = get_post_type_object($this->post_type);
627
+		if (current_user_can($post_type_obj->cap->edit_posts)) {
628
+			$private = apply_filters('getpaid_rest_private_query_vars', $wp->private_query_vars);
629
+			$valid_vars = array_merge($valid_vars, $private);
630 630
 		}
631 631
 
632 632
 		// Define our own in addition to WP's normal vars.
@@ -648,10 +648,10 @@  discard block
 block discarded – undo
648 648
 			'meta_compare',
649 649
 			'meta_value_num',
650 650
 		);
651
-		$valid_vars = array_merge( $valid_vars, $rest_valid );
651
+		$valid_vars = array_merge($valid_vars, $rest_valid);
652 652
 
653 653
 		// Filter allowed query vars for the REST API.
654
-		$valid_vars = apply_filters( 'getpaid_rest_query_vars', $valid_vars, $this );
654
+		$valid_vars = apply_filters('getpaid_rest_query_vars', $valid_vars, $this);
655 655
 
656 656
 		return $valid_vars;
657 657
 	}
@@ -668,32 +668,32 @@  discard block
 block discarded – undo
668 668
 
669 669
 		$params['status'] = array(
670 670
 			'default'           => $this->get_post_statuses(),
671
-			'description'       => __( 'Limit result set to resources assigned one or more statuses.', 'invoicing' ),
672
-			'type'              => array( 'array', 'string' ),
671
+			'description'       => __('Limit result set to resources assigned one or more statuses.', 'invoicing'),
672
+			'type'              => array('array', 'string'),
673 673
 			'items'             => array(
674 674
 				'enum'          => $this->get_post_statuses(),
675 675
 				'type'          => 'string',
676 676
 			),
677 677
 			'validate_callback' => 'rest_validate_request_arg',
678
-			'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
678
+			'sanitize_callback' => array($this, 'sanitize_post_statuses'),
679 679
 		);
680 680
 
681 681
 		$params['after'] = array(
682
-			'description'        => __( 'Limit response to resources created after a given ISO8601 compliant date.', 'invoicing' ),
682
+			'description'        => __('Limit response to resources created after a given ISO8601 compliant date.', 'invoicing'),
683 683
 			'type'               => 'string',
684 684
 			'format'             => 'string',
685 685
 			'validate_callback'  => 'rest_validate_request_arg',
686 686
 			'sanitize_callback'  => 'sanitize_text_field',
687 687
 		);
688 688
 		$params['before'] = array(
689
-			'description'        => __( 'Limit response to resources created before a given ISO8601 compliant date.', 'invoicing' ),
689
+			'description'        => __('Limit response to resources created before a given ISO8601 compliant date.', 'invoicing'),
690 690
 			'type'               => 'string',
691 691
 			'format'             => 'string',
692 692
 			'validate_callback'  => 'rest_validate_request_arg',
693 693
 			'sanitize_callback'  => 'sanitize_text_field',
694 694
 		);
695 695
 		$params['exclude'] = array(
696
-			'description'       => __( 'Ensure result set excludes specific IDs.', 'invoicing' ),
696
+			'description'       => __('Ensure result set excludes specific IDs.', 'invoicing'),
697 697
 			'type'              => 'array',
698 698
 			'items'             => array(
699 699
 				'type'          => 'integer',
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 			'validate_callback' => 'rest_validate_request_arg',
704 704
 		);
705 705
 		$params['include'] = array(
706
-			'description'       => __( 'Limit result set to specific ids.', 'invoicing' ),
706
+			'description'       => __('Limit result set to specific ids.', 'invoicing'),
707 707
 			'type'              => 'array',
708 708
 			'items'             => array(
709 709
 				'type'          => 'integer',
@@ -713,20 +713,20 @@  discard block
 block discarded – undo
713 713
 			'validate_callback' => 'rest_validate_request_arg',
714 714
 		);
715 715
 		$params['offset'] = array(
716
-			'description'        => __( 'Offset the result set by a specific number of items.', 'invoicing' ),
716
+			'description'        => __('Offset the result set by a specific number of items.', 'invoicing'),
717 717
 			'type'               => 'integer',
718 718
 			'sanitize_callback'  => 'absint',
719 719
 			'validate_callback'  => 'rest_validate_request_arg',
720 720
 		);
721 721
 		$params['order'] = array(
722
-			'description'        => __( 'Order sort attribute ascending or descending.', 'invoicing' ),
722
+			'description'        => __('Order sort attribute ascending or descending.', 'invoicing'),
723 723
 			'type'               => 'string',
724 724
 			'default'            => 'desc',
725
-			'enum'               => array( 'asc', 'desc' ),
725
+			'enum'               => array('asc', 'desc'),
726 726
 			'validate_callback'  => 'rest_validate_request_arg',
727 727
 		);
728 728
 		$params['orderby'] = array(
729
-			'description'        => __( 'Sort collection by object attribute.', 'invoicing' ),
729
+			'description'        => __('Sort collection by object attribute.', 'invoicing'),
730 730
 			'type'               => 'string',
731 731
 			'default'            => 'date',
732 732
 			'enum'               => array(
@@ -740,11 +740,11 @@  discard block
 block discarded – undo
740 740
 			'validate_callback'  => 'rest_validate_request_arg',
741 741
 		);
742 742
 
743
-		$post_type_obj = get_post_type_object( $this->post_type );
743
+		$post_type_obj = get_post_type_object($this->post_type);
744 744
 
745
-		if ( isset( $post_type_obj->hierarchical ) && $post_type_obj->hierarchical ) {
745
+		if (isset($post_type_obj->hierarchical) && $post_type_obj->hierarchical) {
746 746
 			$params['parent'] = array(
747
-				'description'       => __( 'Limit result set to those of particular parent IDs.', 'invoicing' ),
747
+				'description'       => __('Limit result set to those of particular parent IDs.', 'invoicing'),
748 748
 				'type'              => 'array',
749 749
 				'items'             => array(
750 750
 					'type'          => 'integer',
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 				'default'           => array(),
754 754
 			);
755 755
 			$params['parent_exclude'] = array(
756
-				'description'       => __( 'Limit result set to all items except those of a particular parent ID.', 'invoicing' ),
756
+				'description'       => __('Limit result set to all items except those of a particular parent ID.', 'invoicing'),
757 757
 				'type'              => 'array',
758 758
 				'items'             => array(
759 759
 					'type'          => 'integer',
@@ -776,25 +776,25 @@  discard block
 block discarded – undo
776 776
 	public function get_item_schema() {
777 777
 
778 778
 		// Maybe retrieve the schema from cache.
779
-		if ( $this->schema ) {
780
-			return $this->add_additional_fields_schema( $this->schema );
779
+		if ($this->schema) {
780
+			return $this->add_additional_fields_schema($this->schema);
781 781
 		}
782 782
 
783
-		$type   = str_replace( 'wpi_', '', $this->post_type );
783
+		$type   = str_replace('wpi_', '', $this->post_type);
784 784
 		$schema = array(
785 785
 			'$schema'    => 'http://json-schema.org/draft-04/schema#',
786 786
 			'title'      => $this->post_type,
787 787
 			'type'       => 'object',
788
-			'properties' => wpinv_get_data( "$type-schema" ),
788
+			'properties' => wpinv_get_data("$type-schema"),
789 789
 		);
790 790
 
791 791
 		// Filters the invoice schema for the REST API.
792
-        $schema = apply_filters( "wpinv_rest_{$type}_schema", $schema );
792
+        $schema = apply_filters("wpinv_rest_{$type}_schema", $schema);
793 793
 
794 794
 		// Cache the invoice schema.
795 795
 		$this->schema = $schema;
796 796
 
797
-		return $this->add_additional_fields_schema( $this->schema );
797
+		return $this->add_additional_fields_schema($this->schema);
798 798
 	}
799 799
 
800 800
 	/**
@@ -803,8 +803,8 @@  discard block
 block discarded – undo
803 803
 	 * @param  array $schema Schema.
804 804
 	 * @return bool
805 805
 	 */
806
-	public function filter_writable_props( $schema ) {
807
-		return empty( $schema['readonly'] );
806
+	public function filter_writable_props($schema) {
807
+		return empty($schema['readonly']);
808 808
 	}
809 809
 
810 810
 	/**
@@ -817,8 +817,8 @@  discard block
 block discarded – undo
817 817
 	 * @param string          $parameter Additional parameter to pass to validation.
818 818
 	 * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
819 819
 	 */
820
-	public function sanitize_post_statuses( $statuses, $request, $parameter ) {
821
-		return array_intersect( wp_parse_slug_list( $statuses ), $this->get_post_statuses() );
820
+	public function sanitize_post_statuses($statuses, $request, $parameter) {
821
+		return array_intersect(wp_parse_slug_list($statuses), $this->get_post_statuses());
822 822
 	}
823 823
 
824 824
 	/**
@@ -839,43 +839,43 @@  discard block
 block discarded – undo
839 839
 	 * @param  WP_REST_Request $request Request object.
840 840
 	 * @return GetPaid_Data|WP_Error Data object or WP_Error.
841 841
 	 */
842
-	protected function prepare_item_for_database( $request ) {
842
+	protected function prepare_item_for_database($request) {
843 843
 
844 844
 		// Do we have an object?
845
-		if ( empty( $this->crud_class ) || ! class_exists( $this->crud_class ) ) {
846
-			return new WP_Error( 'no_crud_class', __( 'You need to specify a CRUD class for this controller', 'invoicing' ) );
845
+		if (empty($this->crud_class) || !class_exists($this->crud_class)) {
846
+			return new WP_Error('no_crud_class', __('You need to specify a CRUD class for this controller', 'invoicing'));
847 847
 		}
848 848
 
849 849
 		// Prepare the object.
850
-		$id        = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
851
-		$object    = new $this->crud_class( $id );
850
+		$id        = isset($request['id']) ? absint($request['id']) : 0;
851
+		$object    = new $this->crud_class($id);
852 852
 
853 853
 		// Abort if an error exists.
854
-		if ( ! empty( $object->last_error ) ) {
855
-			return new WP_Error( 'invalid_item', $object->last_error );
854
+		if (!empty($object->last_error)) {
855
+			return new WP_Error('invalid_item', $object->last_error);
856 856
 		}
857 857
 
858 858
 		$schema    = $this->get_item_schema();
859
-		$data_keys = array_keys( array_filter( $schema['properties'], array( $this, 'filter_writable_props' ) ) );
859
+		$data_keys = array_keys(array_filter($schema['properties'], array($this, 'filter_writable_props')));
860 860
 
861 861
 		// Handle all writable props.
862
-		foreach ( $data_keys as $key ) {
863
-			$value = $request[ $key ];
862
+		foreach ($data_keys as $key) {
863
+			$value = $request[$key];
864 864
 
865
-			if ( ! is_null( $value ) ) {
866
-				switch ( $key ) {
865
+			if (!is_null($value)) {
866
+				switch ($key) {
867 867
 
868 868
 					case 'meta_data':
869
-						if ( is_array( $value ) ) {
870
-							foreach ( $value as $meta ) {
871
-								$object->update_meta_data( $meta['key'], $meta['value'], isset( $meta['id'] ) ? $meta['id'] : '' );
869
+						if (is_array($value)) {
870
+							foreach ($value as $meta) {
871
+								$object->update_meta_data($meta['key'], $meta['value'], isset($meta['id']) ? $meta['id'] : '');
872 872
 							}
873 873
 						}
874 874
 						break;
875 875
 
876 876
 					default:
877
-						if ( is_callable( array( $object, "set_{$key}" ) ) ) {
878
-							$object->{"set_{$key}"}( $value );
877
+						if (is_callable(array($object, "set_{$key}"))) {
878
+							$object->{"set_{$key}"}($value);
879 879
 						}
880 880
 						break;
881 881
 				}
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
 		}
885 885
 
886 886
 		// Filters an object before it is inserted via the REST API..
887
-		return apply_filters( "getpaid_rest_pre_insert_{$this->post_type}_object", $object, $request );
887
+		return apply_filters("getpaid_rest_pre_insert_{$this->post_type}_object", $object, $request);
888 888
 	}
889 889
 
890 890
 	/**
@@ -894,10 +894,10 @@  discard block
 block discarded – undo
894 894
 	 * @param  GetPaid_Meta_Data[]    $meta_data  meta data objects.
895 895
 	 * @return array
896 896
 	 */
897
-	protected function prepare_object_meta_data( $meta_data ) {
897
+	protected function prepare_object_meta_data($meta_data) {
898 898
 		$meta = array();
899 899
 
900
-		foreach( $meta_data as $object ) {
900
+		foreach ($meta_data as $object) {
901 901
 			$meta[] = $object->get_data();
902 902
 		}
903 903
 
@@ -912,14 +912,14 @@  discard block
 block discarded – undo
912 912
 	 * @param array            $fields Fields to include.
913 913
 	 * @return array
914 914
 	 */
915
-	protected function prepare_invoice_items( $invoice ) {
915
+	protected function prepare_invoice_items($invoice) {
916 916
 		$items = array();
917 917
 
918
-		foreach( $invoice->get_items() as $item ) {
918
+		foreach ($invoice->get_items() as $item) {
919 919
 
920 920
 			$item_data = $item->prepare_data_for_saving();
921 921
 
922
-			if ( 'amount' == $invoice->get_template() ) {
922
+			if ('amount' == $invoice->get_template()) {
923 923
 				$item_data['quantity'] = 1;
924 924
 			}
925 925
 
@@ -938,52 +938,52 @@  discard block
 block discarded – undo
938 938
 	 * @param string           $context either view or edit.
939 939
 	 * @return array
940 940
 	 */
941
-	protected function prepare_object_data( $object, $fields, $context = 'view' ) {
941
+	protected function prepare_object_data($object, $fields, $context = 'view') {
942 942
 
943 943
 		$data = array();
944 944
 
945 945
 		// Handle all writable props.
946
-		foreach ( array_keys( $this->get_schema_properties() ) as $key ) {
946
+		foreach (array_keys($this->get_schema_properties()) as $key) {
947 947
 
948 948
 			// Abort if it is not included.
949
-			if ( ! empty( $fields ) && ! $this->is_field_included( $key, $fields ) ) {
949
+			if (!empty($fields) && !$this->is_field_included($key, $fields)) {
950 950
 				continue;
951 951
 			}
952 952
 
953 953
 			// Or this current object does not support the field.
954
-			if ( ! $this->object_supports_field( $object, $key ) ) {
954
+			if (!$this->object_supports_field($object, $key)) {
955 955
 				continue;
956 956
 			}
957 957
 
958 958
 			// Handle meta data.
959
-			if ( $key == 'meta_data' ) {
960
-				$data['meta_data'] = $this->prepare_object_meta_data( $object->get_meta_data() );
959
+			if ($key == 'meta_data') {
960
+				$data['meta_data'] = $this->prepare_object_meta_data($object->get_meta_data());
961 961
 				continue;
962 962
 			}
963 963
 
964 964
 			// Handle items.
965
-			if ( $key == 'items' && is_a( $object, 'WPInv_Invoice' )  ) {
966
-				$data['items'] = $this->prepare_invoice_items( $object );
965
+			if ($key == 'items' && is_a($object, 'WPInv_Invoice')) {
966
+				$data['items'] = $this->prepare_invoice_items($object);
967 967
 				continue;
968 968
 			}
969 969
 
970 970
 			// Booleans.
971
-			if ( is_callable( array( $object, $key ) ) ) {
972
-				$data[ $key ] = $object->$key( $context );
971
+			if (is_callable(array($object, $key))) {
972
+				$data[$key] = $object->$key($context);
973 973
 				continue;
974 974
 			}
975 975
 
976 976
 			// Get object value.
977
-			if ( is_callable( array( $object, "get_{$key}" ) ) ) {
978
-				$value = $object->{"get_{$key}"}( $context );
977
+			if (is_callable(array($object, "get_{$key}"))) {
978
+				$value = $object->{"get_{$key}"}($context);
979 979
 
980 980
 				// If the value is an instance of GetPaid_Data...
981
-				if ( is_a( $value, 'GetPaid_Data' ) ) {
982
-					$value = $value->get_data( $context );
981
+				if (is_a($value, 'GetPaid_Data')) {
982
+					$value = $value->get_data($context);
983 983
 				}
984 984
 
985 985
 				// For objects, retrieves it's properties.
986
-				$data[ $key ] = is_object( $value ) ? get_object_vars( $value ) :  $value ;
986
+				$data[$key] = is_object($value) ? get_object_vars($value) : $value;
987 987
 				continue;
988 988
 			}
989 989
 
@@ -1000,8 +1000,8 @@  discard block
 block discarded – undo
1000 1000
 	 * @param  string       $field_key The key to check for.
1001 1001
 	 * @return bool
1002 1002
 	 */
1003
-	public function object_supports_field( $object, $field_key ) {
1004
-		return apply_filters( "getpaid_rest_{$this->post_type}_object_supports_key", true, $object, $field_key );
1003
+	public function object_supports_field($object, $field_key) {
1004
+		return apply_filters("getpaid_rest_{$this->post_type}_object_supports_key", true, $object, $field_key);
1005 1005
 	}
1006 1006
 
1007 1007
 	/**
@@ -1012,24 +1012,24 @@  discard block
 block discarded – undo
1012 1012
 	 * @param  WP_REST_Request $request Request object.
1013 1013
 	 * @return WP_REST_Response
1014 1014
 	 */
1015
-	public function prepare_item_for_response( $object, $request ) {
1015
+	public function prepare_item_for_response($object, $request) {
1016 1016
 
1017 1017
 		// Fetch the fields to include in this response.
1018
-		$fields = $this->get_fields_for_response( $request );
1018
+		$fields = $this->get_fields_for_response($request);
1019 1019
 
1020 1020
 		// Prepare object data.
1021
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1022
-		$data    = $this->prepare_object_data( $object, $fields, $context );
1023
-		$data    = $this->add_additional_fields_to_object( $data, $request );
1024
-		$data    = $this->limit_object_to_requested_fields( $data, $fields );
1025
-		$data    = $this->filter_response_by_context( $data, $context );
1021
+		$context = !empty($request['context']) ? $request['context'] : 'view';
1022
+		$data    = $this->prepare_object_data($object, $fields, $context);
1023
+		$data    = $this->add_additional_fields_to_object($data, $request);
1024
+		$data    = $this->limit_object_to_requested_fields($data, $fields);
1025
+		$data    = $this->filter_response_by_context($data, $context);
1026 1026
 
1027 1027
 		// Prepare the response.
1028
-		$response = rest_ensure_response( $data );
1029
-		$response->add_links( $this->prepare_links( $object, $request ) );
1028
+		$response = rest_ensure_response($data);
1029
+		$response->add_links($this->prepare_links($object, $request));
1030 1030
 
1031 1031
 		// Filter item response.
1032
-		return apply_filters( "getpaid_rest_prepare_{$this->post_type}_object", $response, $object, $request );
1032
+		return apply_filters("getpaid_rest_prepare_{$this->post_type}_object", $response, $object, $request);
1033 1033
 	}
1034 1034
 
1035 1035
 }
Please login to merge, or discard this patch.
includes/wpinv-template-functions.php 2 patches
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
  * @param string $default_path The root path to the default template. Defaults to invoicing/templates
141 141
  */
142 142
 function wpinv_get_template_html( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
143
-	return getpaid_template()->get_template( $template_name, $args, $template_path, $default_path );
143
+    return getpaid_template()->get_template( $template_name, $args, $template_path, $default_path );
144 144
 }
145 145
 
146 146
 /**
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
  * @return string
159 159
  */
160 160
 function wpinv_get_theme_template_dir_name() {
161
-	return trailingslashit( apply_filters( 'wpinv_templates_dir', 'invoicing' ) );
161
+    return trailingslashit( apply_filters( 'wpinv_templates_dir', 'invoicing' ) );
162 162
 }
163 163
 
164 164
 /**
@@ -175,122 +175,122 @@  discard block
 block discarded – undo
175 175
 }
176 176
 
177 177
 function wpinv_get_template_part( $slug, $name = null, $load = true ) {
178
-	do_action( 'get_template_part_' . $slug, $slug, $name );
178
+    do_action( 'get_template_part_' . $slug, $slug, $name );
179 179
 
180
-	// Setup possible parts
181
-	$templates = array();
182
-	if ( isset( $name ) )
183
-		$templates[] = $slug . '-' . $name . '.php';
184
-	$templates[] = $slug . '.php';
180
+    // Setup possible parts
181
+    $templates = array();
182
+    if ( isset( $name ) )
183
+        $templates[] = $slug . '-' . $name . '.php';
184
+    $templates[] = $slug . '.php';
185 185
 
186
-	// Allow template parts to be filtered
187
-	$templates = apply_filters( 'wpinv_get_template_part', $templates, $slug, $name );
186
+    // Allow template parts to be filtered
187
+    $templates = apply_filters( 'wpinv_get_template_part', $templates, $slug, $name );
188 188
 
189
-	// Return the part that is found
190
-	return wpinv_locate_tmpl( $templates, $load, false );
189
+    // Return the part that is found
190
+    return wpinv_locate_tmpl( $templates, $load, false );
191 191
 }
192 192
 
193 193
 function wpinv_locate_tmpl( $template_names, $load = false, $require_once = true ) {
194
-	// No file found yet
195
-	$located = false;
194
+    // No file found yet
195
+    $located = false;
196 196
 
197
-	// Try to find a template file
198
-	foreach ( (array)$template_names as $template_name ) {
197
+    // Try to find a template file
198
+    foreach ( (array)$template_names as $template_name ) {
199 199
 
200
-		// Continue if template is empty
201
-		if ( empty( $template_name ) )
202
-			continue;
200
+        // Continue if template is empty
201
+        if ( empty( $template_name ) )
202
+            continue;
203 203
 
204
-		// Trim off any slashes from the template name
205
-		$template_name = ltrim( $template_name, '/' );
204
+        // Trim off any slashes from the template name
205
+        $template_name = ltrim( $template_name, '/' );
206 206
 
207
-		// try locating this template file by looping through the template paths
208
-		foreach( wpinv_get_theme_template_paths() as $template_path ) {
207
+        // try locating this template file by looping through the template paths
208
+        foreach( wpinv_get_theme_template_paths() as $template_path ) {
209 209
 
210
-			if( file_exists( $template_path . $template_name ) ) {
211
-				$located = $template_path . $template_name;
212
-				break;
213
-			}
214
-		}
210
+            if( file_exists( $template_path . $template_name ) ) {
211
+                $located = $template_path . $template_name;
212
+                break;
213
+            }
214
+        }
215 215
 
216
-		if( !empty( $located ) ) {
217
-			break;
218
-		}
219
-	}
216
+        if( !empty( $located ) ) {
217
+            break;
218
+        }
219
+    }
220 220
 
221
-	if ( ( true == $load ) && ! empty( $located ) )
222
-		load_template( $located, $require_once );
221
+    if ( ( true == $load ) && ! empty( $located ) )
222
+        load_template( $located, $require_once );
223 223
 
224
-	return $located;
224
+    return $located;
225 225
 }
226 226
 
227 227
 function wpinv_get_theme_template_paths() {
228
-	$template_dir = wpinv_get_theme_template_dir_name();
228
+    $template_dir = wpinv_get_theme_template_dir_name();
229 229
 
230
-	$file_paths = array(
231
-		1 => trailingslashit( get_stylesheet_directory() ) . $template_dir,
232
-		10 => trailingslashit( get_template_directory() ) . $template_dir,
233
-		100 => wpinv_get_templates_dir()
234
-	);
230
+    $file_paths = array(
231
+        1 => trailingslashit( get_stylesheet_directory() ) . $template_dir,
232
+        10 => trailingslashit( get_template_directory() ) . $template_dir,
233
+        100 => wpinv_get_templates_dir()
234
+    );
235 235
 
236
-	$file_paths = apply_filters( 'wpinv_template_paths', $file_paths );
236
+    $file_paths = apply_filters( 'wpinv_template_paths', $file_paths );
237 237
 
238
-	// sort the file paths based on priority
239
-	ksort( $file_paths, SORT_NUMERIC );
238
+    // sort the file paths based on priority
239
+    ksort( $file_paths, SORT_NUMERIC );
240 240
 
241
-	return array_map( 'trailingslashit', $file_paths );
241
+    return array_map( 'trailingslashit', $file_paths );
242 242
 }
243 243
 
244 244
 function wpinv_checkout_meta_tags() {
245 245
 
246
-	$pages   = array();
247
-	$pages[] = wpinv_get_option( 'success_page' );
248
-	$pages[] = wpinv_get_option( 'failure_page' );
249
-	$pages[] = wpinv_get_option( 'invoice_history_page' );
250
-	$pages[] = wpinv_get_option( 'invoice_subscription_page' );
246
+    $pages   = array();
247
+    $pages[] = wpinv_get_option( 'success_page' );
248
+    $pages[] = wpinv_get_option( 'failure_page' );
249
+    $pages[] = wpinv_get_option( 'invoice_history_page' );
250
+    $pages[] = wpinv_get_option( 'invoice_subscription_page' );
251 251
 
252
-	if( !wpinv_is_checkout() && !is_page( $pages ) ) {
253
-		return;
254
-	}
252
+    if( !wpinv_is_checkout() && !is_page( $pages ) ) {
253
+        return;
254
+    }
255 255
 
256
-	echo '<meta name="robots" content="noindex,nofollow" />' . "\n";
256
+    echo '<meta name="robots" content="noindex,nofollow" />' . "\n";
257 257
 }
258 258
 add_action( 'wp_head', 'wpinv_checkout_meta_tags' );
259 259
 
260 260
 function wpinv_add_body_classes( $class ) {
261
-	$classes = (array)$class;
261
+    $classes = (array)$class;
262 262
 
263
-	if( wpinv_is_checkout() ) {
264
-		$classes[] = 'wpinv-checkout';
265
-		$classes[] = 'wpinv-page';
266
-	}
263
+    if( wpinv_is_checkout() ) {
264
+        $classes[] = 'wpinv-checkout';
265
+        $classes[] = 'wpinv-page';
266
+    }
267 267
 
268
-	if( wpinv_is_success_page() ) {
269
-		$classes[] = 'wpinv-success';
270
-		$classes[] = 'wpinv-page';
271
-	}
268
+    if( wpinv_is_success_page() ) {
269
+        $classes[] = 'wpinv-success';
270
+        $classes[] = 'wpinv-page';
271
+    }
272 272
 
273
-	if( wpinv_is_failed_transaction_page() ) {
274
-		$classes[] = 'wpinv-failed-transaction';
275
-		$classes[] = 'wpinv-page';
276
-	}
273
+    if( wpinv_is_failed_transaction_page() ) {
274
+        $classes[] = 'wpinv-failed-transaction';
275
+        $classes[] = 'wpinv-page';
276
+    }
277 277
 
278
-	if( wpinv_is_invoice_history_page() ) {
279
-		$classes[] = 'wpinv-history';
280
-		$classes[] = 'wpinv-page';
281
-	}
278
+    if( wpinv_is_invoice_history_page() ) {
279
+        $classes[] = 'wpinv-history';
280
+        $classes[] = 'wpinv-page';
281
+    }
282 282
 
283
-	if( wpinv_is_subscriptions_history_page() ) {
284
-		$classes[] = 'wpinv-subscription';
285
-		$classes[] = 'wpinv-page';
286
-	}
283
+    if( wpinv_is_subscriptions_history_page() ) {
284
+        $classes[] = 'wpinv-subscription';
285
+        $classes[] = 'wpinv-page';
286
+    }
287 287
 
288
-	if( wpinv_is_test_mode() ) {
289
-		$classes[] = 'wpinv-test-mode';
290
-		$classes[] = 'wpinv-page';
291
-	}
288
+    if( wpinv_is_test_mode() ) {
289
+        $classes[] = 'wpinv-test-mode';
290
+        $classes[] = 'wpinv-page';
291
+    }
292 292
 
293
-	return array_unique( $classes );
293
+    return array_unique( $classes );
294 294
 }
295 295
 add_filter( 'body_class', 'wpinv_add_body_classes' );
296 296
 
@@ -992,21 +992,21 @@  discard block
 block discarded – undo
992 992
 
993 993
     $formatted_address = str_ireplace( array_keys( $replacements ), $replacements, $format );
994 994
     
995
-	// Remove unavailable tags.
995
+    // Remove unavailable tags.
996 996
     $formatted_address = preg_replace( "/\{\{\w+\}\}/", '', $formatted_address );
997 997
 
998 998
     // Clean up white space.
999
-	$formatted_address = preg_replace( '/  +/', ' ', trim( $formatted_address ) );
999
+    $formatted_address = preg_replace( '/  +/', ' ', trim( $formatted_address ) );
1000 1000
     $formatted_address = preg_replace( '/\n\n+/', "\n", $formatted_address );
1001 1001
     
1002 1002
     // Break newlines apart and remove empty lines/trim commas and white space.
1003
-	$formatted_address = array_filter( array_map( 'wpinv_trim_formatted_address_line', explode( "\n", $formatted_address ) ) );
1003
+    $formatted_address = array_filter( array_map( 'wpinv_trim_formatted_address_line', explode( "\n", $formatted_address ) ) );
1004 1004
 
1005 1005
     // Add html breaks.
1006
-	$formatted_address = implode( $separator, $formatted_address );
1006
+    $formatted_address = implode( $separator, $formatted_address );
1007 1007
 
1008
-	// We're done!
1009
-	return $formatted_address;
1008
+    // We're done!
1009
+    return $formatted_address;
1010 1010
     
1011 1011
 }
1012 1012
 
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
 }
1209 1209
 
1210 1210
 function wpinv_empty_cart_message() {
1211
-	return apply_filters( 'wpinv_empty_cart_message', '<span class="wpinv_empty_cart">' . __( 'Your cart is empty.', 'invoicing' ) . '</span>' );
1211
+    return apply_filters( 'wpinv_empty_cart_message', '<span class="wpinv_empty_cart">' . __( 'Your cart is empty.', 'invoicing' ) . '</span>' );
1212 1212
 }
1213 1213
 
1214 1214
 /**
@@ -1560,10 +1560,10 @@  discard block
 block discarded – undo
1560 1560
 
1561 1561
     if ( 0 == count( $form->get_items() ) ) {
1562 1562
         echo aui()->alert(
1563
-			array(
1564
-				'type'    => 'warning',
1565
-				'content' => __( 'No published items found', 'invoicing' ),
1566
-			)
1563
+            array(
1564
+                'type'    => 'warning',
1565
+                'content' => __( 'No published items found', 'invoicing' ),
1566
+            )
1567 1567
         );
1568 1568
         return;
1569 1569
     }
@@ -1580,47 +1580,47 @@  discard block
 block discarded – undo
1580 1580
     $invoice = wpinv_get_invoice( $invoice_id );
1581 1581
 
1582 1582
     if ( empty( $invoice ) ) {
1583
-		return aui()->alert(
1584
-			array(
1585
-				'type'    => 'warning',
1586
-				'content' => __( 'Invoice not found', 'invoicing' ),
1587
-			)
1588
-		);
1583
+        return aui()->alert(
1584
+            array(
1585
+                'type'    => 'warning',
1586
+                'content' => __( 'Invoice not found', 'invoicing' ),
1587
+            )
1588
+        );
1589 1589
     }
1590 1590
 
1591 1591
     if ( $invoice->is_paid() ) {
1592
-		return aui()->alert(
1593
-			array(
1594
-				'type'    => 'warning',
1595
-				'content' => __( 'Invoice has already been paid', 'invoicing' ),
1596
-			)
1597
-		);
1592
+        return aui()->alert(
1593
+            array(
1594
+                'type'    => 'warning',
1595
+                'content' => __( 'Invoice has already been paid', 'invoicing' ),
1596
+            )
1597
+        );
1598 1598
     }
1599 1599
 
1600 1600
     // Get the form elements and items.
1601 1601
     $form     = wpinv_get_default_payment_form();
1602
-	$elements = $invoicing->form_elements->get_form_elements( $form );
1603
-	$items    = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
1602
+    $elements = $invoicing->form_elements->get_form_elements( $form );
1603
+    $items    = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
1604 1604
 
1605
-	ob_start();
1606
-	echo "<form class='wpinv_payment_form'>";
1607
-	do_action( 'wpinv_payment_form_top' );
1605
+    ob_start();
1606
+    echo "<form class='wpinv_payment_form'>";
1607
+    do_action( 'wpinv_payment_form_top' );
1608 1608
     echo "<input type='hidden' name='form_id' value='$form'/>";
1609 1609
     echo "<input type='hidden' name='invoice_id' value='$invoice_id'/>";
1610
-	wp_nonce_field( 'wpinv_payment_form', 'wpinv_payment_form' );
1611
-	wp_nonce_field( 'vat_validation', '_wpi_nonce' );
1610
+    wp_nonce_field( 'wpinv_payment_form', 'wpinv_payment_form' );
1611
+    wp_nonce_field( 'vat_validation', '_wpi_nonce' );
1612 1612
 
1613
-	foreach ( $elements as $element ) {
1614
-		do_action( 'wpinv_frontend_render_payment_form_element', $element, $items, $form );
1615
-		do_action( "wpinv_frontend_render_payment_form_{$element['type']}", $element, $items, $form );
1616
-	}
1613
+    foreach ( $elements as $element ) {
1614
+        do_action( 'wpinv_frontend_render_payment_form_element', $element, $items, $form );
1615
+        do_action( "wpinv_frontend_render_payment_form_{$element['type']}", $element, $items, $form );
1616
+    }
1617 1617
 
1618
-	echo "<div class='wpinv_payment_form_errors alert alert-danger d-none'></div>";
1619
-	do_action( 'wpinv_payment_form_bottom' );
1620
-	echo '</form>';
1618
+    echo "<div class='wpinv_payment_form_errors alert alert-danger d-none'></div>";
1619
+    do_action( 'wpinv_payment_form_bottom' );
1620
+    echo '</form>';
1621 1621
 
1622
-	$content = ob_get_clean();
1623
-	return str_replace( 'sr-only', '', $content );
1622
+    $content = ob_get_clean();
1623
+    return str_replace( 'sr-only', '', $content );
1624 1624
 }
1625 1625
 
1626 1626
 /**
@@ -1675,7 +1675,7 @@  discard block
 block discarded – undo
1675 1675
         return "<button class='btn btn-primary getpaid-payment-button' type='button' data-nonce='$nonce' data-form='$form'>$label</button>"; 
1676 1676
     }
1677 1677
 	
1678
-	if ( ! empty( $items ) ) {
1678
+    if ( ! empty( $items ) ) {
1679 1679
         $items  = esc_attr( $items );
1680 1680
         return "<button class='btn btn-primary getpaid-payment-button' type='button' data-nonce='$nonce' data-item='$items'>$label</button>"; 
1681 1681
     }
Please login to merge, or discard this patch.
Spacing   +533 added lines, -533 removed lines patch added patch discarded remove patch
@@ -4,99 +4,99 @@  discard block
 block discarded – undo
4 4
  *
5 5
  */
6 6
 
7
-defined( 'ABSPATH' ) || exit;
7
+defined('ABSPATH') || exit;
8 8
 
9 9
 /**
10 10
  * Displays an invoice.
11 11
  * 
12 12
  * @param WPInv_Invoice $invoice.
13 13
  */
14
-function getpaid_invoice( $invoice ) {
15
-    if ( ! empty( $invoice ) ) {
16
-        wpinv_get_template( 'invoice/invoice.php', compact( 'invoice' ) );
14
+function getpaid_invoice($invoice) {
15
+    if (!empty($invoice)) {
16
+        wpinv_get_template('invoice/invoice.php', compact('invoice'));
17 17
     }
18 18
 }
19
-add_action( 'getpaid_invoice', 'getpaid_invoice', 10 );
19
+add_action('getpaid_invoice', 'getpaid_invoice', 10);
20 20
 
21 21
 /**
22 22
  * Displays the invoice footer.
23 23
  */
24
-function getpaid_invoice_footer( $invoice ) {
25
-    if ( ! empty( $invoice ) ) {
26
-        wpinv_get_template( 'invoice/footer.php', compact( 'invoice' ) );
24
+function getpaid_invoice_footer($invoice) {
25
+    if (!empty($invoice)) {
26
+        wpinv_get_template('invoice/footer.php', compact('invoice'));
27 27
     }
28 28
 }
29
-add_action( 'getpaid_invoice_footer', 'getpaid_invoice_footer', 10 );
29
+add_action('getpaid_invoice_footer', 'getpaid_invoice_footer', 10);
30 30
 
31 31
 /**
32 32
  * Displays the invoice top bar.
33 33
  */
34
-function getpaid_invoice_header( $invoice ) {
35
-    if ( ! empty( $invoice ) ) {
36
-        wpinv_get_template( 'invoice/header.php', compact( 'invoice' ) );
34
+function getpaid_invoice_header($invoice) {
35
+    if (!empty($invoice)) {
36
+        wpinv_get_template('invoice/header.php', compact('invoice'));
37 37
     }
38 38
 }
39
-add_action( 'getpaid_invoice_header', 'getpaid_invoice_header', 10 );
39
+add_action('getpaid_invoice_header', 'getpaid_invoice_header', 10);
40 40
 
41 41
 /**
42 42
  * Displays actions on the left side of the header.
43 43
  */
44
-function getpaid_invoice_header_left_actions( $invoice ) {
45
-    if ( ! empty( $invoice ) ) {
46
-        wpinv_get_template( 'invoice/header-left-actions.php', compact( 'invoice' ) );
44
+function getpaid_invoice_header_left_actions($invoice) {
45
+    if (!empty($invoice)) {
46
+        wpinv_get_template('invoice/header-left-actions.php', compact('invoice'));
47 47
     }
48 48
 }
49
-add_action( 'getpaid_invoice_header_left', 'getpaid_invoice_header_left_actions', 10 );
49
+add_action('getpaid_invoice_header_left', 'getpaid_invoice_header_left_actions', 10);
50 50
 
51 51
 /**
52 52
  * Displays actions on the right side of the invoice top bar.
53 53
  */
54
-function getpaid_invoice_header_right_actions( $invoice ) {
55
-    if ( ! empty( $invoice ) ) {
56
-        wpinv_get_template( 'invoice/header-right-actions.php', compact( 'invoice' ) );
54
+function getpaid_invoice_header_right_actions($invoice) {
55
+    if (!empty($invoice)) {
56
+        wpinv_get_template('invoice/header-right-actions.php', compact('invoice'));
57 57
     }
58 58
 }
59
-add_action( 'getpaid_invoice_header_right', 'getpaid_invoice_header_right_actions', 10 );
59
+add_action('getpaid_invoice_header_right', 'getpaid_invoice_header_right_actions', 10);
60 60
 
61 61
 /**
62 62
  * Displays the invoice title, watermark, logo etc.
63 63
  */
64
-function getpaid_invoice_details_top( $invoice ) {
65
-    if ( ! empty( $invoice ) ) {
66
-        wpinv_get_template( 'invoice/details-top.php', compact( 'invoice' ) );
64
+function getpaid_invoice_details_top($invoice) {
65
+    if (!empty($invoice)) {
66
+        wpinv_get_template('invoice/details-top.php', compact('invoice'));
67 67
     }
68 68
 }
69
-add_action( 'getpaid_invoice_details', 'getpaid_invoice_details_top', 10 );
69
+add_action('getpaid_invoice_details', 'getpaid_invoice_details_top', 10);
70 70
 
71 71
 /**
72 72
  * Displays the company logo.
73 73
  */
74
-function getpaid_invoice_logo( $invoice ) {
75
-    if ( ! empty( $invoice ) ) {
76
-        wpinv_get_template( 'invoice/invoice-logo.php', compact( 'invoice' ) );
74
+function getpaid_invoice_logo($invoice) {
75
+    if (!empty($invoice)) {
76
+        wpinv_get_template('invoice/invoice-logo.php', compact('invoice'));
77 77
     }
78 78
 }
79
-add_action( 'getpaid_invoice_details_top_left', 'getpaid_invoice_logo' );
79
+add_action('getpaid_invoice_details_top_left', 'getpaid_invoice_logo');
80 80
 
81 81
 /**
82 82
  * Displays the type of invoice.
83 83
  */
84
-function getpaid_invoice_type( $invoice ) {
85
-    if ( ! empty( $invoice ) ) {
86
-        wpinv_get_template( 'invoice/invoice-type.php', compact( 'invoice' ) );
84
+function getpaid_invoice_type($invoice) {
85
+    if (!empty($invoice)) {
86
+        wpinv_get_template('invoice/invoice-type.php', compact('invoice'));
87 87
     }
88 88
 }
89
-add_action( 'getpaid_invoice_details_top_right', 'getpaid_invoice_type' );
89
+add_action('getpaid_invoice_details_top_right', 'getpaid_invoice_type');
90 90
 
91 91
 /**
92 92
  * Displays the invoice details.
93 93
  */
94
-function getpaid_invoice_details_main( $invoice ) {
95
-    if ( ! empty( $invoice ) ) {
96
-        wpinv_get_template( 'invoice/details.php', compact( 'invoice' ) );
94
+function getpaid_invoice_details_main($invoice) {
95
+    if (!empty($invoice)) {
96
+        wpinv_get_template('invoice/details.php', compact('invoice'));
97 97
     }
98 98
 }
99
-add_action( 'getpaid_invoice_details', 'getpaid_invoice_details_main', 50 );
99
+add_action('getpaid_invoice_details', 'getpaid_invoice_details_main', 50);
100 100
 
101 101
 /**
102 102
  * Returns a path to the templates directory.
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
  * @param string $template_path The templates directory relative to the theme's root dir. Defaults to 'invoicing'.
126 126
  * @param string $default_path The root path to the default template. Defaults to invoicing/templates
127 127
  */
128
-function wpinv_get_template( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
129
-    return getpaid_template()->display_template( $template_name, $args, $template_path, $default_path );
128
+function wpinv_get_template($template_name, $args = array(), $template_path = '', $default_path = '') {
129
+    return getpaid_template()->display_template($template_name, $args, $template_path, $default_path);
130 130
 }
131 131
 
132 132
 /**
@@ -139,8 +139,8 @@  discard block
 block discarded – undo
139 139
  * @param string $template_path The templates directory relative to the theme's root dir. Defaults to 'invoicing'.
140 140
  * @param string $default_path The root path to the default template. Defaults to invoicing/templates
141 141
  */
142
-function wpinv_get_template_html( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
143
-	return getpaid_template()->get_template( $template_name, $args, $template_path, $default_path );
142
+function wpinv_get_template_html($template_name, $args = array(), $template_path = '', $default_path = '') {
143
+	return getpaid_template()->get_template($template_name, $args, $template_path, $default_path);
144 144
 }
145 145
 
146 146
 /**
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
  * @return string
150 150
  */
151 151
 function wpinv_template_path() {
152
-    return apply_filters( 'wpinv_template_path', wpinv_get_theme_template_dir_name() );
152
+    return apply_filters('wpinv_template_path', wpinv_get_theme_template_dir_name());
153 153
 }
154 154
 
155 155
 /**
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
  * @return string
159 159
  */
160 160
 function wpinv_get_theme_template_dir_name() {
161
-	return trailingslashit( apply_filters( 'wpinv_templates_dir', 'invoicing' ) );
161
+	return trailingslashit(apply_filters('wpinv_templates_dir', 'invoicing'));
162 162
 }
163 163
 
164 164
 /**
@@ -170,56 +170,56 @@  discard block
 block discarded – undo
170 170
  * @param string $template_path The template path relative to the theme's root dir. Defaults to 'invoicing'.
171 171
  * @param string $default_path The root path to the default template. Defaults to invoicing/templates
172 172
  */
173
-function wpinv_locate_template( $template_name, $template_path = '', $default_path = '' ) {
174
-    return getpaid_template()->locate_template( $template_name, $template_path, $default_path );
173
+function wpinv_locate_template($template_name, $template_path = '', $default_path = '') {
174
+    return getpaid_template()->locate_template($template_name, $template_path, $default_path);
175 175
 }
176 176
 
177
-function wpinv_get_template_part( $slug, $name = null, $load = true ) {
178
-	do_action( 'get_template_part_' . $slug, $slug, $name );
177
+function wpinv_get_template_part($slug, $name = null, $load = true) {
178
+	do_action('get_template_part_' . $slug, $slug, $name);
179 179
 
180 180
 	// Setup possible parts
181 181
 	$templates = array();
182
-	if ( isset( $name ) )
182
+	if (isset($name))
183 183
 		$templates[] = $slug . '-' . $name . '.php';
184 184
 	$templates[] = $slug . '.php';
185 185
 
186 186
 	// Allow template parts to be filtered
187
-	$templates = apply_filters( 'wpinv_get_template_part', $templates, $slug, $name );
187
+	$templates = apply_filters('wpinv_get_template_part', $templates, $slug, $name);
188 188
 
189 189
 	// Return the part that is found
190
-	return wpinv_locate_tmpl( $templates, $load, false );
190
+	return wpinv_locate_tmpl($templates, $load, false);
191 191
 }
192 192
 
193
-function wpinv_locate_tmpl( $template_names, $load = false, $require_once = true ) {
193
+function wpinv_locate_tmpl($template_names, $load = false, $require_once = true) {
194 194
 	// No file found yet
195 195
 	$located = false;
196 196
 
197 197
 	// Try to find a template file
198
-	foreach ( (array)$template_names as $template_name ) {
198
+	foreach ((array) $template_names as $template_name) {
199 199
 
200 200
 		// Continue if template is empty
201
-		if ( empty( $template_name ) )
201
+		if (empty($template_name))
202 202
 			continue;
203 203
 
204 204
 		// Trim off any slashes from the template name
205
-		$template_name = ltrim( $template_name, '/' );
205
+		$template_name = ltrim($template_name, '/');
206 206
 
207 207
 		// try locating this template file by looping through the template paths
208
-		foreach( wpinv_get_theme_template_paths() as $template_path ) {
208
+		foreach (wpinv_get_theme_template_paths() as $template_path) {
209 209
 
210
-			if( file_exists( $template_path . $template_name ) ) {
210
+			if (file_exists($template_path . $template_name)) {
211 211
 				$located = $template_path . $template_name;
212 212
 				break;
213 213
 			}
214 214
 		}
215 215
 
216
-		if( !empty( $located ) ) {
216
+		if (!empty($located)) {
217 217
 			break;
218 218
 		}
219 219
 	}
220 220
 
221
-	if ( ( true == $load ) && ! empty( $located ) )
222
-		load_template( $located, $require_once );
221
+	if ((true == $load) && !empty($located))
222
+		load_template($located, $require_once);
223 223
 
224 224
 	return $located;
225 225
 }
@@ -228,155 +228,155 @@  discard block
 block discarded – undo
228 228
 	$template_dir = wpinv_get_theme_template_dir_name();
229 229
 
230 230
 	$file_paths = array(
231
-		1 => trailingslashit( get_stylesheet_directory() ) . $template_dir,
232
-		10 => trailingslashit( get_template_directory() ) . $template_dir,
231
+		1 => trailingslashit(get_stylesheet_directory()) . $template_dir,
232
+		10 => trailingslashit(get_template_directory()) . $template_dir,
233 233
 		100 => wpinv_get_templates_dir()
234 234
 	);
235 235
 
236
-	$file_paths = apply_filters( 'wpinv_template_paths', $file_paths );
236
+	$file_paths = apply_filters('wpinv_template_paths', $file_paths);
237 237
 
238 238
 	// sort the file paths based on priority
239
-	ksort( $file_paths, SORT_NUMERIC );
239
+	ksort($file_paths, SORT_NUMERIC);
240 240
 
241
-	return array_map( 'trailingslashit', $file_paths );
241
+	return array_map('trailingslashit', $file_paths);
242 242
 }
243 243
 
244 244
 function wpinv_checkout_meta_tags() {
245 245
 
246 246
 	$pages   = array();
247
-	$pages[] = wpinv_get_option( 'success_page' );
248
-	$pages[] = wpinv_get_option( 'failure_page' );
249
-	$pages[] = wpinv_get_option( 'invoice_history_page' );
250
-	$pages[] = wpinv_get_option( 'invoice_subscription_page' );
247
+	$pages[] = wpinv_get_option('success_page');
248
+	$pages[] = wpinv_get_option('failure_page');
249
+	$pages[] = wpinv_get_option('invoice_history_page');
250
+	$pages[] = wpinv_get_option('invoice_subscription_page');
251 251
 
252
-	if( !wpinv_is_checkout() && !is_page( $pages ) ) {
252
+	if (!wpinv_is_checkout() && !is_page($pages)) {
253 253
 		return;
254 254
 	}
255 255
 
256 256
 	echo '<meta name="robots" content="noindex,nofollow" />' . "\n";
257 257
 }
258
-add_action( 'wp_head', 'wpinv_checkout_meta_tags' );
258
+add_action('wp_head', 'wpinv_checkout_meta_tags');
259 259
 
260
-function wpinv_add_body_classes( $class ) {
261
-	$classes = (array)$class;
260
+function wpinv_add_body_classes($class) {
261
+	$classes = (array) $class;
262 262
 
263
-	if( wpinv_is_checkout() ) {
263
+	if (wpinv_is_checkout()) {
264 264
 		$classes[] = 'wpinv-checkout';
265 265
 		$classes[] = 'wpinv-page';
266 266
 	}
267 267
 
268
-	if( wpinv_is_success_page() ) {
268
+	if (wpinv_is_success_page()) {
269 269
 		$classes[] = 'wpinv-success';
270 270
 		$classes[] = 'wpinv-page';
271 271
 	}
272 272
 
273
-	if( wpinv_is_failed_transaction_page() ) {
273
+	if (wpinv_is_failed_transaction_page()) {
274 274
 		$classes[] = 'wpinv-failed-transaction';
275 275
 		$classes[] = 'wpinv-page';
276 276
 	}
277 277
 
278
-	if( wpinv_is_invoice_history_page() ) {
278
+	if (wpinv_is_invoice_history_page()) {
279 279
 		$classes[] = 'wpinv-history';
280 280
 		$classes[] = 'wpinv-page';
281 281
 	}
282 282
 
283
-	if( wpinv_is_subscriptions_history_page() ) {
283
+	if (wpinv_is_subscriptions_history_page()) {
284 284
 		$classes[] = 'wpinv-subscription';
285 285
 		$classes[] = 'wpinv-page';
286 286
 	}
287 287
 
288
-	if( wpinv_is_test_mode() ) {
288
+	if (wpinv_is_test_mode()) {
289 289
 		$classes[] = 'wpinv-test-mode';
290 290
 		$classes[] = 'wpinv-page';
291 291
 	}
292 292
 
293
-	return array_unique( $classes );
293
+	return array_unique($classes);
294 294
 }
295
-add_filter( 'body_class', 'wpinv_add_body_classes' );
295
+add_filter('body_class', 'wpinv_add_body_classes');
296 296
 
297
-function wpinv_html_dropdown( $name = 'wpinv_discounts', $selected = 0, $status = '' ) {
298
-    $args = array( 'nopaging' => true );
297
+function wpinv_html_dropdown($name = 'wpinv_discounts', $selected = 0, $status = '') {
298
+    $args = array('nopaging' => true);
299 299
 
300
-    if ( ! empty( $status ) )
300
+    if (!empty($status))
301 301
         $args['post_status'] = $status;
302 302
 
303
-    $discounts = wpinv_get_discounts( $args );
303
+    $discounts = wpinv_get_discounts($args);
304 304
     $options   = array();
305 305
 
306
-    if ( $discounts ) {
307
-        foreach ( $discounts as $discount ) {
308
-            $options[ absint( $discount->ID ) ] = esc_html( get_the_title( $discount->ID ) );
306
+    if ($discounts) {
307
+        foreach ($discounts as $discount) {
308
+            $options[absint($discount->ID)] = esc_html(get_the_title($discount->ID));
309 309
         }
310 310
     } else {
311
-        $options[0] = __( 'No discounts found', 'invoicing' );
311
+        $options[0] = __('No discounts found', 'invoicing');
312 312
     }
313 313
 
314
-    $output = wpinv_html_select( array(
314
+    $output = wpinv_html_select(array(
315 315
         'name'             => $name,
316 316
         'selected'         => $selected,
317 317
         'options'          => $options,
318 318
         'show_option_all'  => false,
319 319
         'show_option_none' => false,
320
-    ) );
320
+    ));
321 321
 
322 322
     return $output;
323 323
 }
324 324
 
325
-function wpinv_html_year_dropdown( $name = 'year', $selected = 0, $years_before = 5, $years_after = 0 ) {
326
-    $current     = date( 'Y' );
327
-    $start_year  = $current - absint( $years_before );
328
-    $end_year    = $current + absint( $years_after );
329
-    $selected    = empty( $selected ) ? date( 'Y' ) : $selected;
325
+function wpinv_html_year_dropdown($name = 'year', $selected = 0, $years_before = 5, $years_after = 0) {
326
+    $current     = date('Y');
327
+    $start_year  = $current - absint($years_before);
328
+    $end_year    = $current + absint($years_after);
329
+    $selected    = empty($selected) ? date('Y') : $selected;
330 330
     $options     = array();
331 331
 
332
-    while ( $start_year <= $end_year ) {
333
-        $options[ absint( $start_year ) ] = $start_year;
332
+    while ($start_year <= $end_year) {
333
+        $options[absint($start_year)] = $start_year;
334 334
         $start_year++;
335 335
     }
336 336
 
337
-    $output = wpinv_html_select( array(
337
+    $output = wpinv_html_select(array(
338 338
         'name'             => $name,
339 339
         'selected'         => $selected,
340 340
         'options'          => $options,
341 341
         'show_option_all'  => false,
342 342
         'show_option_none' => false
343
-    ) );
343
+    ));
344 344
 
345 345
     return $output;
346 346
 }
347 347
 
348
-function wpinv_html_month_dropdown( $name = 'month', $selected = 0 ) {
348
+function wpinv_html_month_dropdown($name = 'month', $selected = 0) {
349 349
 
350 350
     $options = array(
351
-        '1'  => __( 'January', 'invoicing' ),
352
-        '2'  => __( 'February', 'invoicing' ),
353
-        '3'  => __( 'March', 'invoicing' ),
354
-        '4'  => __( 'April', 'invoicing' ),
355
-        '5'  => __( 'May', 'invoicing' ),
356
-        '6'  => __( 'June', 'invoicing' ),
357
-        '7'  => __( 'July', 'invoicing' ),
358
-        '8'  => __( 'August', 'invoicing' ),
359
-        '9'  => __( 'September', 'invoicing' ),
360
-        '10' => __( 'October', 'invoicing' ),
361
-        '11' => __( 'November', 'invoicing' ),
362
-        '12' => __( 'December', 'invoicing' ),
351
+        '1'  => __('January', 'invoicing'),
352
+        '2'  => __('February', 'invoicing'),
353
+        '3'  => __('March', 'invoicing'),
354
+        '4'  => __('April', 'invoicing'),
355
+        '5'  => __('May', 'invoicing'),
356
+        '6'  => __('June', 'invoicing'),
357
+        '7'  => __('July', 'invoicing'),
358
+        '8'  => __('August', 'invoicing'),
359
+        '9'  => __('September', 'invoicing'),
360
+        '10' => __('October', 'invoicing'),
361
+        '11' => __('November', 'invoicing'),
362
+        '12' => __('December', 'invoicing'),
363 363
     );
364 364
 
365 365
     // If no month is selected, default to the current month
366
-    $selected = empty( $selected ) ? date( 'n' ) : $selected;
366
+    $selected = empty($selected) ? date('n') : $selected;
367 367
 
368
-    $output = wpinv_html_select( array(
368
+    $output = wpinv_html_select(array(
369 369
         'name'             => $name,
370 370
         'selected'         => $selected,
371 371
         'options'          => $options,
372 372
         'show_option_all'  => false,
373 373
         'show_option_none' => false
374
-    ) );
374
+    ));
375 375
 
376 376
     return $output;
377 377
 }
378 378
 
379
-function wpinv_html_select( $args = array() ) {
379
+function wpinv_html_select($args = array()) {
380 380
     $defaults = array(
381 381
         'options'          => array(),
382 382
         'name'             => null,
@@ -385,8 +385,8 @@  discard block
 block discarded – undo
385 385
         'selected'         => 0,
386 386
         'placeholder'      => null,
387 387
         'multiple'         => false,
388
-        'show_option_all'  => _x( 'All', 'all dropdown items', 'invoicing' ),
389
-        'show_option_none' => _x( 'None', 'no dropdown items', 'invoicing' ),
388
+        'show_option_all'  => _x('All', 'all dropdown items', 'invoicing'),
389
+        'show_option_none' => _x('None', 'no dropdown items', 'invoicing'),
390 390
         'data'             => array(),
391 391
         'onchange'         => null,
392 392
         'required'         => false,
@@ -394,74 +394,74 @@  discard block
 block discarded – undo
394 394
         'readonly'         => false,
395 395
     );
396 396
 
397
-    $args = wp_parse_args( $args, $defaults );
397
+    $args = wp_parse_args($args, $defaults);
398 398
 
399 399
     $data_elements = '';
400
-    foreach ( $args['data'] as $key => $value ) {
401
-        $data_elements .= ' data-' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
400
+    foreach ($args['data'] as $key => $value) {
401
+        $data_elements .= ' data-' . esc_attr($key) . '="' . esc_attr($value) . '"';
402 402
     }
403 403
 
404
-    if( $args['multiple'] ) {
404
+    if ($args['multiple']) {
405 405
         $multiple = ' MULTIPLE';
406 406
     } else {
407 407
         $multiple = '';
408 408
     }
409 409
 
410
-    if( $args['placeholder'] ) {
410
+    if ($args['placeholder']) {
411 411
         $placeholder = $args['placeholder'];
412 412
     } else {
413 413
         $placeholder = '';
414 414
     }
415 415
     
416 416
     $options = '';
417
-    if( !empty( $args['onchange'] ) ) {
418
-        $options .= ' onchange="' . esc_attr( $args['onchange'] ) . '"';
417
+    if (!empty($args['onchange'])) {
418
+        $options .= ' onchange="' . esc_attr($args['onchange']) . '"';
419 419
     }
420 420
     
421
-    if( !empty( $args['required'] ) ) {
421
+    if (!empty($args['required'])) {
422 422
         $options .= ' required="required"';
423 423
     }
424 424
     
425
-    if( !empty( $args['disabled'] ) ) {
425
+    if (!empty($args['disabled'])) {
426 426
         $options .= ' disabled';
427 427
     }
428 428
     
429
-    if( !empty( $args['readonly'] ) ) {
429
+    if (!empty($args['readonly'])) {
430 430
         $options .= ' readonly';
431 431
     }
432 432
 
433
-    $class  = implode( ' ', array_map( 'sanitize_html_class', explode( ' ', $args['class'] ) ) );
434
-    $output = '<select name="' . esc_attr( $args['name'] ) . '" id="' . esc_attr( $args['id'] ) . '" class="wpinv-select ' . $class . '"' . $multiple . ' data-placeholder="' . $placeholder . '" ' . trim( $options ) . $data_elements . '>';
433
+    $class  = implode(' ', array_map('sanitize_html_class', explode(' ', $args['class'])));
434
+    $output = '<select name="' . esc_attr($args['name']) . '" id="' . esc_attr($args['id']) . '" class="wpinv-select ' . $class . '"' . $multiple . ' data-placeholder="' . $placeholder . '" ' . trim($options) . $data_elements . '>';
435 435
 
436
-    if ( $args['show_option_all'] ) {
437
-        if( $args['multiple'] ) {
438
-            $selected = selected( true, in_array( 0, $args['selected'] ), false );
436
+    if ($args['show_option_all']) {
437
+        if ($args['multiple']) {
438
+            $selected = selected(true, in_array(0, $args['selected']), false);
439 439
         } else {
440
-            $selected = selected( $args['selected'], 0, false );
440
+            $selected = selected($args['selected'], 0, false);
441 441
         }
442
-        $output .= '<option value="all"' . $selected . '>' . esc_html( $args['show_option_all'] ) . '</option>';
442
+        $output .= '<option value="all"' . $selected . '>' . esc_html($args['show_option_all']) . '</option>';
443 443
     }
444 444
 
445
-    if ( !empty( $args['options'] ) ) {
445
+    if (!empty($args['options'])) {
446 446
 
447
-        if ( $args['show_option_none'] ) {
448
-            if( $args['multiple'] ) {
449
-                $selected = selected( true, in_array( "", $args['selected'] ), false );
447
+        if ($args['show_option_none']) {
448
+            if ($args['multiple']) {
449
+                $selected = selected(true, in_array("", $args['selected']), false);
450 450
             } else {
451
-                $selected = selected( $args['selected'] === "", true, false );
451
+                $selected = selected($args['selected'] === "", true, false);
452 452
             }
453
-            $output .= '<option value=""' . $selected . '>' . esc_html( $args['show_option_none'] ) . '</option>';
453
+            $output .= '<option value=""' . $selected . '>' . esc_html($args['show_option_none']) . '</option>';
454 454
         }
455 455
 
456
-        foreach( $args['options'] as $key => $option ) {
456
+        foreach ($args['options'] as $key => $option) {
457 457
 
458
-            if( $args['multiple'] && is_array( $args['selected'] ) ) {
459
-                $selected = selected( true, (bool)in_array( $key, $args['selected'] ), false );
458
+            if ($args['multiple'] && is_array($args['selected'])) {
459
+                $selected = selected(true, (bool) in_array($key, $args['selected']), false);
460 460
             } else {
461
-                $selected = selected( $args['selected'], $key, false );
461
+                $selected = selected($args['selected'], $key, false);
462 462
             }
463 463
 
464
-            $output .= '<option value="' . esc_attr( $key ) . '"' . $selected . '>' . esc_html( $option ) . '</option>';
464
+            $output .= '<option value="' . esc_attr($key) . '"' . $selected . '>' . esc_html($option) . '</option>';
465 465
         }
466 466
     }
467 467
 
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
     return $output;
471 471
 }
472 472
 
473
-function wpinv_item_dropdown( $args = array() ) {
473
+function wpinv_item_dropdown($args = array()) {
474 474
     $defaults = array(
475 475
         'name'              => 'wpi_item',
476 476
         'id'                => 'wpi_item',
@@ -478,14 +478,14 @@  discard block
 block discarded – undo
478 478
         'multiple'          => false,
479 479
         'selected'          => 0,
480 480
         'number'            => 100,
481
-        'placeholder'       => __( 'Choose a item', 'invoicing' ),
482
-        'data'              => array( 'search-type' => 'item' ),
481
+        'placeholder'       => __('Choose a item', 'invoicing'),
482
+        'data'              => array('search-type' => 'item'),
483 483
         'show_option_all'   => false,
484 484
         'show_option_none'  => false,
485 485
         'show_recurring'    => false,
486 486
     );
487 487
 
488
-    $args = wp_parse_args( $args, $defaults );
488
+    $args = wp_parse_args($args, $defaults);
489 489
 
490 490
     $item_args = array(
491 491
         'post_type'      => 'wpi_item',
@@ -494,44 +494,44 @@  discard block
 block discarded – undo
494 494
         'posts_per_page' => $args['number']
495 495
     );
496 496
 
497
-    $item_args  = apply_filters( 'wpinv_item_dropdown_query_args', $item_args, $args, $defaults );
497
+    $item_args  = apply_filters('wpinv_item_dropdown_query_args', $item_args, $args, $defaults);
498 498
 
499
-    $items      = get_posts( $item_args );
499
+    $items      = get_posts($item_args);
500 500
     $options    = array();
501
-    if ( $items ) {
502
-        foreach ( $items as $item ) {
503
-            $title = esc_html( $item->post_title );
501
+    if ($items) {
502
+        foreach ($items as $item) {
503
+            $title = esc_html($item->post_title);
504 504
             
505
-            if ( !empty( $args['show_recurring'] ) ) {
506
-                $title .= wpinv_get_item_suffix( $item->ID, false );
505
+            if (!empty($args['show_recurring'])) {
506
+                $title .= wpinv_get_item_suffix($item->ID, false);
507 507
             }
508 508
             
509
-            $options[ absint( $item->ID ) ] = $title;
509
+            $options[absint($item->ID)] = $title;
510 510
         }
511 511
     }
512 512
 
513 513
     // This ensures that any selected items are included in the drop down
514
-    if( is_array( $args['selected'] ) ) {
515
-        foreach( $args['selected'] as $item ) {
516
-            if( ! in_array( $item, $options ) ) {
517
-                $title = get_the_title( $item );
518
-                if ( !empty( $args['show_recurring'] ) ) {
519
-                    $title .= wpinv_get_item_suffix( $item, false );
514
+    if (is_array($args['selected'])) {
515
+        foreach ($args['selected'] as $item) {
516
+            if (!in_array($item, $options)) {
517
+                $title = get_the_title($item);
518
+                if (!empty($args['show_recurring'])) {
519
+                    $title .= wpinv_get_item_suffix($item, false);
520 520
                 }
521 521
                 $options[$item] = $title;
522 522
             }
523 523
         }
524
-    } elseif ( is_numeric( $args['selected'] ) && $args['selected'] !== 0 ) {
525
-        if ( ! in_array( $args['selected'], $options ) ) {
526
-            $title = get_the_title( $args['selected'] );
527
-            if ( !empty( $args['show_recurring'] ) ) {
528
-                $title .= wpinv_get_item_suffix( $args['selected'], false );
524
+    } elseif (is_numeric($args['selected']) && $args['selected'] !== 0) {
525
+        if (!in_array($args['selected'], $options)) {
526
+            $title = get_the_title($args['selected']);
527
+            if (!empty($args['show_recurring'])) {
528
+                $title .= wpinv_get_item_suffix($args['selected'], false);
529 529
             }
530
-            $options[$args['selected']] = get_the_title( $args['selected'] );
530
+            $options[$args['selected']] = get_the_title($args['selected']);
531 531
         }
532 532
     }
533 533
 
534
-    $output = wpinv_html_select( array(
534
+    $output = wpinv_html_select(array(
535 535
         'name'             => $args['name'],
536 536
         'selected'         => $args['selected'],
537 537
         'id'               => $args['id'],
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
         'show_option_all'  => $args['show_option_all'],
543 543
         'show_option_none' => $args['show_option_none'],
544 544
         'data'             => $args['data'],
545
-    ) );
545
+    ));
546 546
 
547 547
     return $output;
548 548
 }
@@ -562,16 +562,16 @@  discard block
 block discarded – undo
562 562
     );
563 563
 
564 564
     $options = array();
565
-    if ( $items ) {
566
-        foreach ( $items as $item ) {
567
-            $options[ $item->ID ] = esc_html( $item->post_title ) . wpinv_get_item_suffix( $item->ID, false );
565
+    if ($items) {
566
+        foreach ($items as $item) {
567
+            $options[$item->ID] = esc_html($item->post_title) . wpinv_get_item_suffix($item->ID, false);
568 568
         }
569 569
     }
570 570
 
571 571
     return $options;
572 572
 }
573 573
 
574
-function wpinv_html_checkbox( $args = array() ) {
574
+function wpinv_html_checkbox($args = array()) {
575 575
     $defaults = array(
576 576
         'name'     => null,
577 577
         'current'  => null,
@@ -582,17 +582,17 @@  discard block
 block discarded – undo
582 582
         )
583 583
     );
584 584
 
585
-    $args = wp_parse_args( $args, $defaults );
585
+    $args = wp_parse_args($args, $defaults);
586 586
 
587
-    $class = implode( ' ', array_map( 'sanitize_html_class', explode( ' ', $args['class'] ) ) );
587
+    $class = implode(' ', array_map('sanitize_html_class', explode(' ', $args['class'])));
588 588
     $options = '';
589
-    if ( ! empty( $args['options']['disabled'] ) ) {
589
+    if (!empty($args['options']['disabled'])) {
590 590
         $options .= ' disabled="disabled"';
591
-    } elseif ( ! empty( $args['options']['readonly'] ) ) {
591
+    } elseif (!empty($args['options']['readonly'])) {
592 592
         $options .= ' readonly';
593 593
     }
594 594
 
595
-    $output = '<input type="checkbox"' . $options . ' name="' . esc_attr( $args['name'] ) . '" id="' . esc_attr( $args['name'] ) . '" class="' . $class . ' ' . esc_attr( $args['name'] ) . '" ' . checked( 1, $args['current'], false ) . ' />';
595
+    $output = '<input type="checkbox"' . $options . ' name="' . esc_attr($args['name']) . '" id="' . esc_attr($args['name']) . '" class="' . $class . ' ' . esc_attr($args['name']) . '" ' . checked(1, $args['current'], false) . ' />';
596 596
 
597 597
     return $output;
598 598
 }
@@ -600,30 +600,30 @@  discard block
 block discarded – undo
600 600
 /**
601 601
  * Displays a hidden field.
602 602
  */
603
-function getpaid_hidden_field( $name, $value ) {
604
-    $name  = sanitize_text_field( $name );
605
-    $value = esc_attr( $value );
603
+function getpaid_hidden_field($name, $value) {
604
+    $name  = sanitize_text_field($name);
605
+    $value = esc_attr($value);
606 606
 
607 607
     echo "<input type='hidden' name='$name' value='$value' />";
608 608
 }
609 609
 
610
-function wpinv_html_text( $args = array() ) {
610
+function wpinv_html_text($args = array()) {
611 611
     // Backwards compatibility
612
-    if ( func_num_args() > 1 ) {
612
+    if (func_num_args() > 1) {
613 613
         $args = func_get_args();
614 614
 
615 615
         $name  = $args[0];
616
-        $value = isset( $args[1] ) ? $args[1] : '';
617
-        $label = isset( $args[2] ) ? $args[2] : '';
618
-        $desc  = isset( $args[3] ) ? $args[3] : '';
616
+        $value = isset($args[1]) ? $args[1] : '';
617
+        $label = isset($args[2]) ? $args[2] : '';
618
+        $desc  = isset($args[3]) ? $args[3] : '';
619 619
     }
620 620
 
621 621
     $defaults = array(
622 622
         'id'           => '',
623
-        'name'         => isset( $name )  ? $name  : 'text',
624
-        'value'        => isset( $value ) ? $value : null,
625
-        'label'        => isset( $label ) ? $label : null,
626
-        'desc'         => isset( $desc )  ? $desc  : null,
623
+        'name'         => isset($name) ? $name : 'text',
624
+        'value'        => isset($value) ? $value : null,
625
+        'label'        => isset($label) ? $label : null,
626
+        'desc'         => isset($desc) ? $desc : null,
627 627
         'placeholder'  => '',
628 628
         'class'        => 'regular-text',
629 629
         'disabled'     => false,
@@ -633,51 +633,51 @@  discard block
 block discarded – undo
633 633
         'data'         => false
634 634
     );
635 635
 
636
-    $args = wp_parse_args( $args, $defaults );
636
+    $args = wp_parse_args($args, $defaults);
637 637
 
638
-    $class = implode( ' ', array_map( 'sanitize_html_class', explode( ' ', $args['class'] ) ) );
638
+    $class = implode(' ', array_map('sanitize_html_class', explode(' ', $args['class'])));
639 639
     $options = '';
640
-    if( $args['required'] ) {
640
+    if ($args['required']) {
641 641
         $options .= ' required="required"';
642 642
     }
643
-    if( $args['readonly'] ) {
643
+    if ($args['readonly']) {
644 644
         $options .= ' readonly';
645 645
     }
646
-    if( $args['readonly'] ) {
646
+    if ($args['readonly']) {
647 647
         $options .= ' readonly';
648 648
     }
649 649
 
650 650
     $data = '';
651
-    if ( !empty( $args['data'] ) ) {
652
-        foreach ( $args['data'] as $key => $value ) {
653
-            $data .= 'data-' . wpinv_sanitize_key( $key ) . '="' . esc_attr( $value ) . '" ';
651
+    if (!empty($args['data'])) {
652
+        foreach ($args['data'] as $key => $value) {
653
+            $data .= 'data-' . wpinv_sanitize_key($key) . '="' . esc_attr($value) . '" ';
654 654
         }
655 655
     }
656 656
 
657
-    $output = '<span id="wpinv-' . wpinv_sanitize_key( $args['name'] ) . '-wrap">';
658
-    $output .= '<label class="wpinv-label" for="' . wpinv_sanitize_key( $args['id'] ) . '">' . esc_html( $args['label'] ) . '</label>';
659
-    if ( ! empty( $args['desc'] ) ) {
660
-        $output .= '<span class="wpinv-description">' . esc_html( $args['desc'] ) . '</span>';
657
+    $output = '<span id="wpinv-' . wpinv_sanitize_key($args['name']) . '-wrap">';
658
+    $output .= '<label class="wpinv-label" for="' . wpinv_sanitize_key($args['id']) . '">' . esc_html($args['label']) . '</label>';
659
+    if (!empty($args['desc'])) {
660
+        $output .= '<span class="wpinv-description">' . esc_html($args['desc']) . '</span>';
661 661
     }
662 662
 
663
-    $output .= '<input type="text" name="' . esc_attr( $args['name'] ) . '" id="' . esc_attr( $args['id'] )  . '" autocomplete="' . esc_attr( $args['autocomplete'] )  . '" value="' . esc_attr( $args['value'] ) . '" placeholder="' . esc_attr( $args['placeholder'] ) . '" class="' . $class . '" ' . $data . ' ' . trim( $options ) . '/>';
663
+    $output .= '<input type="text" name="' . esc_attr($args['name']) . '" id="' . esc_attr($args['id']) . '" autocomplete="' . esc_attr($args['autocomplete']) . '" value="' . esc_attr($args['value']) . '" placeholder="' . esc_attr($args['placeholder']) . '" class="' . $class . '" ' . $data . ' ' . trim($options) . '/>';
664 664
 
665 665
     $output .= '</span>';
666 666
 
667 667
     return $output;
668 668
 }
669 669
 
670
-function wpinv_html_date_field( $args = array() ) {
671
-    if( empty( $args['class'] ) ) {
670
+function wpinv_html_date_field($args = array()) {
671
+    if (empty($args['class'])) {
672 672
         $args['class'] = 'wpiDatepicker';
673
-    } elseif( ! strpos( $args['class'], 'wpiDatepicker' ) ) {
673
+    } elseif (!strpos($args['class'], 'wpiDatepicker')) {
674 674
         $args['class'] .= ' wpiDatepicker';
675 675
     }
676 676
 
677
-    return wpinv_html_text( $args );
677
+    return wpinv_html_text($args);
678 678
 }
679 679
 
680
-function wpinv_html_textarea( $args = array() ) {
680
+function wpinv_html_textarea($args = array()) {
681 681
     $defaults = array(
682 682
         'name'        => 'textarea',
683 683
         'value'       => null,
@@ -688,31 +688,31 @@  discard block
 block discarded – undo
688 688
         'placeholder' => '',
689 689
     );
690 690
 
691
-    $args = wp_parse_args( $args, $defaults );
691
+    $args = wp_parse_args($args, $defaults);
692 692
 
693
-    $class = implode( ' ', array_map( 'sanitize_html_class', explode( ' ', $args['class'] ) ) );
693
+    $class = implode(' ', array_map('sanitize_html_class', explode(' ', $args['class'])));
694 694
     $disabled = '';
695
-    if( $args['disabled'] ) {
695
+    if ($args['disabled']) {
696 696
         $disabled = ' disabled="disabled"';
697 697
     }
698 698
 
699
-    $output = '<span id="wpinv-' . wpinv_sanitize_key( $args['name'] ) . '-wrap">';
700
-    $output .= '<label class="wpinv-label" for="' . wpinv_sanitize_key( $args['name'] ) . '">' . esc_html( $args['label'] ) . '</label>';
701
-    $output .= '<textarea name="' . esc_attr( $args['name'] ) . '" placeholder="' . esc_attr( $args['placeholder'] ) . '" id="' . wpinv_sanitize_key( $args['name'] ) . '" class="' . $class . '"' . $disabled . '>' . esc_attr( $args['value'] ) . '</textarea>';
699
+    $output = '<span id="wpinv-' . wpinv_sanitize_key($args['name']) . '-wrap">';
700
+    $output .= '<label class="wpinv-label" for="' . wpinv_sanitize_key($args['name']) . '">' . esc_html($args['label']) . '</label>';
701
+    $output .= '<textarea name="' . esc_attr($args['name']) . '" placeholder="' . esc_attr($args['placeholder']) . '" id="' . wpinv_sanitize_key($args['name']) . '" class="' . $class . '"' . $disabled . '>' . esc_attr($args['value']) . '</textarea>';
702 702
 
703
-    if ( ! empty( $args['desc'] ) ) {
704
-        $output .= '<span class="wpinv-description">' . esc_html( $args['desc'] ) . '</span>';
703
+    if (!empty($args['desc'])) {
704
+        $output .= '<span class="wpinv-description">' . esc_html($args['desc']) . '</span>';
705 705
     }
706 706
     $output .= '</span>';
707 707
 
708 708
     return $output;
709 709
 }
710 710
 
711
-function wpinv_html_ajax_user_search( $args = array() ) {
711
+function wpinv_html_ajax_user_search($args = array()) {
712 712
     $defaults = array(
713 713
         'name'        => 'user_id',
714 714
         'value'       => null,
715
-        'placeholder' => __( 'Enter username', 'invoicing' ),
715
+        'placeholder' => __('Enter username', 'invoicing'),
716 716
         'label'       => null,
717 717
         'desc'        => null,
718 718
         'class'       => '',
@@ -721,13 +721,13 @@  discard block
 block discarded – undo
721 721
         'data'        => false
722 722
     );
723 723
 
724
-    $args = wp_parse_args( $args, $defaults );
724
+    $args = wp_parse_args($args, $defaults);
725 725
 
726 726
     $args['class'] = 'wpinv-ajax-user-search ' . $args['class'];
727 727
 
728 728
     $output  = '<span class="wpinv_user_search_wrap">';
729
-        $output .= wpinv_html_text( $args );
730
-        $output .= '<span class="wpinv_user_search_results hidden"><a class="wpinv-ajax-user-cancel" title="' . __( 'Cancel', 'invoicing' ) . '" aria-label="' . __( 'Cancel', 'invoicing' ) . '" href="#">x</a><span></span></span>';
729
+        $output .= wpinv_html_text($args);
730
+        $output .= '<span class="wpinv_user_search_results hidden"><a class="wpinv-ajax-user-cancel" title="' . __('Cancel', 'invoicing') . '" aria-label="' . __('Cancel', 'invoicing') . '" href="#">x</a><span></span></span>';
731 731
     $output .= '</span>';
732 732
 
733 733
     return $output;
@@ -743,20 +743,20 @@  discard block
 block discarded – undo
743 743
  * 
744 744
  * @param string $template the template that is currently being used.
745 745
  */
746
-function wpinv_template( $template ) {
746
+function wpinv_template($template) {
747 747
     global $post;
748 748
 
749
-    if ( ! is_admin() && ( is_single() || is_404() ) && ! empty( $post->ID ) && getpaid_is_invoice_post_type( get_post_type( $post->ID ) ) ) {
749
+    if (!is_admin() && (is_single() || is_404()) && !empty($post->ID) && getpaid_is_invoice_post_type(get_post_type($post->ID))) {
750 750
 
751 751
         // If the user can view this invoice, display it.
752
-        if ( wpinv_user_can_view_invoice( $post->ID ) ) {
752
+        if (wpinv_user_can_view_invoice($post->ID)) {
753 753
 
754
-            return wpinv_get_template_part( 'wpinv-invoice-print', false, false );
754
+            return wpinv_get_template_part('wpinv-invoice-print', false, false);
755 755
 
756 756
         // Else display an error message.
757 757
         } else {
758 758
 
759
-            return wpinv_get_template_part( 'wpinv-invalid-access', false, false );
759
+            return wpinv_get_template_part('wpinv-invalid-access', false, false);
760 760
 
761 761
         }
762 762
 
@@ -764,46 +764,46 @@  discard block
 block discarded – undo
764 764
 
765 765
     return $template;
766 766
 }
767
-add_filter( 'template_include', 'wpinv_template', 10, 1 );
767
+add_filter('template_include', 'wpinv_template', 10, 1);
768 768
 
769 769
 function wpinv_get_business_address() {
770 770
     $business_address   = wpinv_store_address();
771
-    $business_address   = !empty( $business_address ) ? wpautop( wp_kses_post( $business_address ) ) : '';
771
+    $business_address   = !empty($business_address) ? wpautop(wp_kses_post($business_address)) : '';
772 772
     
773 773
     $business_address = $business_address ? '<div class="address">' . $business_address . '</div>' : '';
774 774
     
775
-    return apply_filters( 'wpinv_get_business_address', $business_address );
775
+    return apply_filters('wpinv_get_business_address', $business_address);
776 776
 }
777 777
 
778 778
 /**
779 779
  * Displays the company address.
780 780
  */
781 781
 function wpinv_display_from_address() {
782
-    wpinv_get_template( 'invoice/company-address.php' );
782
+    wpinv_get_template('invoice/company-address.php');
783 783
 }
784
-add_action( 'getpaid_invoice_details_left', 'wpinv_display_from_address', 10 );
784
+add_action('getpaid_invoice_details_left', 'wpinv_display_from_address', 10);
785 785
 
786
-function wpinv_watermark( $id = 0 ) {
787
-    $output = wpinv_get_watermark( $id );
788
-    return apply_filters( 'wpinv_get_watermark', $output, $id );
786
+function wpinv_watermark($id = 0) {
787
+    $output = wpinv_get_watermark($id);
788
+    return apply_filters('wpinv_get_watermark', $output, $id);
789 789
 }
790 790
 
791
-function wpinv_get_watermark( $id ) {
792
-    if ( !$id > 0 ) {
791
+function wpinv_get_watermark($id) {
792
+    if (!$id > 0) {
793 793
         return NULL;
794 794
     }
795 795
 
796
-    $invoice = wpinv_get_invoice( $id );
796
+    $invoice = wpinv_get_invoice($id);
797 797
     
798
-    if ( !empty( $invoice ) && "wpi_invoice" === $invoice->post_type ) {
799
-        if ( $invoice->is_paid() ) {
800
-            return __( 'Paid', 'invoicing' );
798
+    if (!empty($invoice) && "wpi_invoice" === $invoice->post_type) {
799
+        if ($invoice->is_paid()) {
800
+            return __('Paid', 'invoicing');
801 801
         }
802
-        if ( $invoice->is_refunded() ) {
803
-            return __( 'Refunded', 'invoicing' );
802
+        if ($invoice->is_refunded()) {
803
+            return __('Refunded', 'invoicing');
804 804
         }
805
-        if ( $invoice->has_status( array( 'wpi-cancelled' ) ) ) {
806
-            return __( 'Cancelled', 'invoicing' );
805
+        if ($invoice->has_status(array('wpi-cancelled'))) {
806
+            return __('Cancelled', 'invoicing');
807 807
         }
808 808
     }
809 809
     
@@ -813,140 +813,140 @@  discard block
 block discarded – undo
813 813
 /**
814 814
  * @deprecated
815 815
  */
816
-function wpinv_display_invoice_details( $invoice ) {
817
-    return getpaid_invoice_meta( $invoice );
816
+function wpinv_display_invoice_details($invoice) {
817
+    return getpaid_invoice_meta($invoice);
818 818
 }
819 819
 
820 820
 /**
821 821
  * Displays invoice meta.
822 822
  */
823
-function getpaid_invoice_meta( $invoice ) {
823
+function getpaid_invoice_meta($invoice) {
824 824
 
825
-    $invoice = new WPInv_Invoice( $invoice );
825
+    $invoice = new WPInv_Invoice($invoice);
826 826
 
827 827
     // Ensure that we have an invoice.
828
-    if ( 0 == $invoice->get_id() ) {
828
+    if (0 == $invoice->get_id()) {
829 829
         return;
830 830
     }
831 831
 
832 832
     // Load the invoice meta.
833
-    $meta    = array(
833
+    $meta = array(
834 834
 
835 835
         'number' => array(
836 836
             'label' => sprintf(
837
-                __( '%s Number', 'invoicing' ),
838
-                ucfirst( $invoice->get_type() )
837
+                __('%s Number', 'invoicing'),
838
+                ucfirst($invoice->get_type())
839 839
             ),
840
-            'value' => sanitize_text_field( $invoice->get_number() ),
840
+            'value' => sanitize_text_field($invoice->get_number()),
841 841
         ),
842 842
 
843 843
         'status' => array(
844 844
             'label' => sprintf(
845
-                __( '%s Status', 'invoicing' ),
846
-                ucfirst( $invoice->get_type() )
845
+                __('%s Status', 'invoicing'),
846
+                ucfirst($invoice->get_type())
847 847
             ),
848
-            'value' => sanitize_text_field( $invoice->get_status_nicename() ),
848
+            'value' => sanitize_text_field($invoice->get_status_nicename()),
849 849
         ),
850 850
 
851 851
         'date' => array(
852 852
             'label' => sprintf(
853
-                __( '%s Date', 'invoicing' ),
854
-                ucfirst( $invoice->get_type() )
853
+                __('%s Date', 'invoicing'),
854
+                ucfirst($invoice->get_type())
855 855
             ),
856
-            'value' => getpaid_format_date( $invoice->get_created_date() ),
856
+            'value' => getpaid_format_date($invoice->get_created_date()),
857 857
         ),
858 858
 
859 859
         'date_paid' => array(
860
-            'label' => __( 'Paid On', 'invoicing' ),
861
-            'value' => getpaid_format_date( $invoice->get_completed_date() ),
860
+            'label' => __('Paid On', 'invoicing'),
861
+            'value' => getpaid_format_date($invoice->get_completed_date()),
862 862
         ),
863 863
 
864 864
         'gateway'   => array(
865
-            'label' => __( 'Payment Method', 'invoicing' ),
866
-            'value' => sanitize_text_field( $invoice->get_gateway_title() ),
865
+            'label' => __('Payment Method', 'invoicing'),
866
+            'value' => sanitize_text_field($invoice->get_gateway_title()),
867 867
         ),
868 868
 
869 869
         'transaction_id' => array(
870
-            'label' => __( 'Transaction ID', 'invoicing' ),
871
-            'value' => sanitize_text_field( $invoice->get_transaction_id() ),
870
+            'label' => __('Transaction ID', 'invoicing'),
871
+            'value' => sanitize_text_field($invoice->get_transaction_id()),
872 872
         ),
873 873
 
874 874
         'due_date'  => array(
875
-            'label' => __( 'Due Date', 'invoicing' ),
876
-            'value' => getpaid_format_date( $invoice->get_due_date() ),
875
+            'label' => __('Due Date', 'invoicing'),
876
+            'value' => getpaid_format_date($invoice->get_due_date()),
877 877
         ),
878 878
 
879 879
         'vat_number' => array(
880 880
             'label' => sprintf(
881
-                __( '%s Number', 'invoicing' ),
881
+                __('%s Number', 'invoicing'),
882 882
                 getpaid_tax()->get_vat_name()
883 883
             ),
884
-            'value' => sanitize_text_field( $invoice->get_vat_number() ),
884
+            'value' => sanitize_text_field($invoice->get_vat_number()),
885 885
         ),
886 886
 
887 887
     );
888 888
 
889 889
     // If it is not paid, remove the date of payment.
890
-    if ( ! $invoice->is_paid() ) {
891
-        unset( $meta[ 'date_paid' ] );
892
-        unset( $meta[ 'transaction_id' ] );
890
+    if (!$invoice->is_paid()) {
891
+        unset($meta['date_paid']);
892
+        unset($meta['transaction_id']);
893 893
     }
894 894
 
895
-    if ( ! $invoice->is_paid() || 'none' == $invoice->get_gateway() ) {
896
-        unset( $meta[ 'gateway' ] );
895
+    if (!$invoice->is_paid() || 'none' == $invoice->get_gateway()) {
896
+        unset($meta['gateway']);
897 897
     }
898 898
 
899 899
     // Only display the due date if due dates are enabled.
900
-    if ( ! $invoice->needs_payment() || ! wpinv_get_option( 'overdue_active' ) ) {
901
-        unset( $meta[ 'due_date' ] );
900
+    if (!$invoice->needs_payment() || !wpinv_get_option('overdue_active')) {
901
+        unset($meta['due_date']);
902 902
     }
903 903
 
904 904
     // Only display the vat number if taxes are enabled.
905
-    if ( ! wpinv_use_taxes() ) {
906
-        unset( $meta[ 'vat_number' ] );
905
+    if (!wpinv_use_taxes()) {
906
+        unset($meta['vat_number']);
907 907
     }
908 908
 
909
-    if ( $invoice->is_recurring() ) {
909
+    if ($invoice->is_recurring()) {
910 910
 
911 911
         // Link to the parent invoice.
912
-        if ( $invoice->is_renewal() ) {
912
+        if ($invoice->is_renewal()) {
913 913
 
914
-            $meta[ 'parent' ] = array(
914
+            $meta['parent'] = array(
915 915
 
916 916
                 'label' => sprintf(
917
-                    __( 'Parent %s', 'invoicing' ),
918
-                    ucfirst( $invoice->get_type() )
917
+                    __('Parent %s', 'invoicing'),
918
+                    ucfirst($invoice->get_type())
919 919
                 ),
920 920
 
921
-                'value' => wpinv_invoice_link( $invoice->get_parent_id() ),
921
+                'value' => wpinv_invoice_link($invoice->get_parent_id()),
922 922
 
923 923
             );
924 924
 
925 925
         }
926 926
 
927
-        $subscription = wpinv_get_subscription( $invoice );
927
+        $subscription = wpinv_get_subscription($invoice);
928 928
 
929
-        if ( ! empty ( $subscription ) ) {
929
+        if (!empty ($subscription)) {
930 930
 
931 931
             // Display the renewal date.
932
-            if ( $subscription->is_active() && 'cancelled' != $subscription->status ) {
932
+            if ($subscription->is_active() && 'cancelled' != $subscription->status) {
933 933
 
934
-                $meta[ 'renewal_date' ] = array(
934
+                $meta['renewal_date'] = array(
935 935
 
936
-                    'label' => __( 'Renews On', 'invoicing' ),
937
-                    'value' => getpaid_format_date( $subscription->expiration ),
936
+                    'label' => __('Renews On', 'invoicing'),
937
+                    'value' => getpaid_format_date($subscription->expiration),
938 938
         
939 939
                 );
940 940
 
941 941
             }
942 942
 
943
-            if ( $invoice->is_parent() ) {
943
+            if ($invoice->is_parent()) {
944 944
 
945 945
                 // Display the recurring amount.
946
-                $meta[ 'recurring_total' ] = array(
946
+                $meta['recurring_total'] = array(
947 947
 
948
-                    'label' => __( 'Recurring Amount', 'invoicing' ),
949
-                    'value' => wpinv_price( wpinv_format_amount( $subscription->recurring_amount ), $invoice->get_currency() ),
948
+                    'label' => __('Recurring Amount', 'invoicing'),
949
+                    'value' => wpinv_price(wpinv_format_amount($subscription->recurring_amount), $invoice->get_currency()),
950 950
         
951 951
                 );
952 952
 
@@ -956,20 +956,20 @@  discard block
 block discarded – undo
956 956
     }
957 957
 
958 958
     // Add the invoice total to the meta.
959
-    $meta[ 'invoice_total' ] = array(
959
+    $meta['invoice_total'] = array(
960 960
 
961
-        'label' => __( 'Total Amount', 'invoicing' ),
962
-        'value' => wpinv_price( wpinv_format_amount( $invoice->get_total() ), $invoice->get_currency() ),
961
+        'label' => __('Total Amount', 'invoicing'),
962
+        'value' => wpinv_price(wpinv_format_amount($invoice->get_total()), $invoice->get_currency()),
963 963
 
964 964
     );
965 965
 
966 966
     // Provide a way for third party plugins to filter the meta.
967
-    $meta = apply_filters( 'getpaid_invoice_meta_data', $meta, $invoice );
967
+    $meta = apply_filters('getpaid_invoice_meta_data', $meta, $invoice);
968 968
 
969
-    wpinv_get_template( 'invoice/invoice-meta.php', compact( 'invoice', 'meta' ) );
969
+    wpinv_get_template('invoice/invoice-meta.php', compact('invoice', 'meta'));
970 970
 
971 971
 }
972
-add_action( 'getpaid_invoice_details_right', 'getpaid_invoice_meta', 10 );
972
+add_action('getpaid_invoice_details_right', 'getpaid_invoice_meta', 10);
973 973
 
974 974
 /**
975 975
  * Retrieves the address markup to use on Invoices.
@@ -981,29 +981,29 @@  discard block
 block discarded – undo
981 981
  * @param  string $separator How to separate address lines.
982 982
  * @return string
983 983
  */
984
-function wpinv_get_invoice_address_markup( $billing_details, $separator = '<br/>' ) {
984
+function wpinv_get_invoice_address_markup($billing_details, $separator = '<br/>') {
985 985
 
986 986
     // Retrieve the address markup...
987
-    $country= empty( $billing_details['country'] ) ? '' : $billing_details['country'];
988
-    $format = wpinv_get_full_address_format( $country );
987
+    $country = empty($billing_details['country']) ? '' : $billing_details['country'];
988
+    $format = wpinv_get_full_address_format($country);
989 989
 
990 990
     // ... and the replacements.
991
-    $replacements = wpinv_get_invoice_address_replacements( $billing_details );
991
+    $replacements = wpinv_get_invoice_address_replacements($billing_details);
992 992
 
993
-    $formatted_address = str_ireplace( array_keys( $replacements ), $replacements, $format );
993
+    $formatted_address = str_ireplace(array_keys($replacements), $replacements, $format);
994 994
     
995 995
 	// Remove unavailable tags.
996
-    $formatted_address = preg_replace( "/\{\{\w+\}\}/", '', $formatted_address );
996
+    $formatted_address = preg_replace("/\{\{\w+\}\}/", '', $formatted_address);
997 997
 
998 998
     // Clean up white space.
999
-	$formatted_address = preg_replace( '/  +/', ' ', trim( $formatted_address ) );
1000
-    $formatted_address = preg_replace( '/\n\n+/', "\n", $formatted_address );
999
+	$formatted_address = preg_replace('/  +/', ' ', trim($formatted_address));
1000
+    $formatted_address = preg_replace('/\n\n+/', "\n", $formatted_address);
1001 1001
     
1002 1002
     // Break newlines apart and remove empty lines/trim commas and white space.
1003
-	$formatted_address = array_filter( array_map( 'wpinv_trim_formatted_address_line', explode( "\n", $formatted_address ) ) );
1003
+	$formatted_address = array_filter(array_map('wpinv_trim_formatted_address_line', explode("\n", $formatted_address)));
1004 1004
 
1005 1005
     // Add html breaks.
1006
-	$formatted_address = implode( $separator, $formatted_address );
1006
+	$formatted_address = implode($separator, $formatted_address);
1007 1007
 
1008 1008
 	// We're done!
1009 1009
 	return $formatted_address;
@@ -1015,88 +1015,88 @@  discard block
 block discarded – undo
1015 1015
  * 
1016 1016
  * @param WPInv_Invoice $invoice
1017 1017
  */
1018
-function wpinv_display_to_address( $invoice = 0 ) {
1019
-    if ( ! empty( $invoice ) ) {
1020
-        wpinv_get_template( 'invoice/billing-address.php', compact( 'invoice' ) );
1018
+function wpinv_display_to_address($invoice = 0) {
1019
+    if (!empty($invoice)) {
1020
+        wpinv_get_template('invoice/billing-address.php', compact('invoice'));
1021 1021
     }
1022 1022
 }
1023
-add_action( 'getpaid_invoice_details_left', 'wpinv_display_to_address', 40 );
1023
+add_action('getpaid_invoice_details_left', 'wpinv_display_to_address', 40);
1024 1024
 
1025 1025
 
1026 1026
 /**
1027 1027
  * Displays invoice line items.
1028 1028
  */
1029
-function wpinv_display_line_items( $invoice_id = 0 ) {
1029
+function wpinv_display_line_items($invoice_id = 0) {
1030 1030
 
1031 1031
     // Prepare the invoice.
1032
-    $invoice = new WPInv_Invoice( $invoice_id );
1032
+    $invoice = new WPInv_Invoice($invoice_id);
1033 1033
 
1034 1034
     // Abort if there is no invoice.
1035
-    if ( 0 == $invoice->get_id() ) {
1035
+    if (0 == $invoice->get_id()) {
1036 1036
         return;
1037 1037
     }
1038 1038
 
1039 1039
     // Line item columns.
1040
-    $columns = getpaid_invoice_item_columns( $invoice );
1041
-    $columns = apply_filters( 'getpaid_invoice_line_items_table_columns', $columns, $invoice );
1040
+    $columns = getpaid_invoice_item_columns($invoice);
1041
+    $columns = apply_filters('getpaid_invoice_line_items_table_columns', $columns, $invoice);
1042 1042
 
1043
-    wpinv_get_template( 'invoice/line-items.php', compact( 'invoice', 'columns' ) );
1043
+    wpinv_get_template('invoice/line-items.php', compact('invoice', 'columns'));
1044 1044
 }
1045
-add_action( 'getpaid_invoice_line_items', 'wpinv_display_line_items', 10 );
1045
+add_action('getpaid_invoice_line_items', 'wpinv_display_line_items', 10);
1046 1046
 
1047 1047
 /**
1048 1048
  * Displays invoice notices on invoices.
1049 1049
  */
1050 1050
 function wpinv_display_invoice_notice() {
1051 1051
 
1052
-    $label  = wpinv_get_option( 'vat_invoice_notice_label' );
1053
-    $notice = wpinv_get_option( 'vat_invoice_notice' );
1052
+    $label  = wpinv_get_option('vat_invoice_notice_label');
1053
+    $notice = wpinv_get_option('vat_invoice_notice');
1054 1054
 
1055
-    if ( empty( $label ) && empty( $notice ) ) {
1055
+    if (empty($label) && empty($notice)) {
1056 1056
         return;
1057 1057
     }
1058 1058
 
1059 1059
     echo '<div class="mt-4 mb-4 wpinv-vat-notice">';
1060 1060
 
1061
-    if ( ! empty( $label ) ) {
1062
-        $label = sanitize_text_field( $label );
1061
+    if (!empty($label)) {
1062
+        $label = sanitize_text_field($label);
1063 1063
         echo "<h5>$label</h5>";
1064 1064
     }
1065 1065
 
1066
-    if ( ! empty( $notice ) ) {
1067
-        echo '<small class="form-text text-muted">' . wpautop( wptexturize( $notice ) ) . '</small>';
1066
+    if (!empty($notice)) {
1067
+        echo '<small class="form-text text-muted">' . wpautop(wptexturize($notice)) . '</small>';
1068 1068
     }
1069 1069
 
1070 1070
     echo '</div>';
1071 1071
 }
1072
-add_action( 'getpaid_invoice_line_items', 'wpinv_display_invoice_notice', 100 );
1072
+add_action('getpaid_invoice_line_items', 'wpinv_display_invoice_notice', 100);
1073 1073
 
1074 1074
 /**
1075 1075
  * @param WPInv_Invoice $invoice
1076 1076
  */
1077
-function wpinv_display_invoice_notes( $invoice ) {
1077
+function wpinv_display_invoice_notes($invoice) {
1078 1078
 
1079 1079
     // Retrieve the notes.
1080
-    $notes = wpinv_get_invoice_notes( $invoice->get_id(), 'customer' );
1080
+    $notes = wpinv_get_invoice_notes($invoice->get_id(), 'customer');
1081 1081
 
1082 1082
     // Abort if we have non.
1083
-    if ( empty( $notes ) ) {
1083
+    if (empty($notes)) {
1084 1084
         return;
1085 1085
     }
1086 1086
 
1087 1087
     // Echo the note.
1088 1088
     echo '<div class="getpaid-invoice-notes-wrapper border position-relative w-100 mb-4 p-0">';
1089
-    echo '<h3 class="getpaid-invoice-notes-title text-dark bg-light border-bottom m-0 d-block">' . __( 'Notes', 'invoicing' ) .'</h3>';
1089
+    echo '<h3 class="getpaid-invoice-notes-title text-dark bg-light border-bottom m-0 d-block">' . __('Notes', 'invoicing') . '</h3>';
1090 1090
     echo '<ul class="getpaid-invoice-notes mt-4 p-0">';
1091 1091
 
1092
-    foreach( $notes as $note ) {
1093
-        wpinv_get_invoice_note_line_item( $note );
1092
+    foreach ($notes as $note) {
1093
+        wpinv_get_invoice_note_line_item($note);
1094 1094
     }
1095 1095
 
1096 1096
     echo '</ul>';
1097 1097
     echo '</div>';
1098 1098
 }
1099
-add_action( 'getpaid_invoice_line_items', 'wpinv_display_invoice_notes', 60 );
1099
+add_action('getpaid_invoice_line_items', 'wpinv_display_invoice_notes', 60);
1100 1100
 
1101 1101
 /**
1102 1102
  * Loads scripts on our invoice templates.
@@ -1104,32 +1104,32 @@  discard block
 block discarded – undo
1104 1104
 function wpinv_display_style() {
1105 1105
 
1106 1106
     // Make sure that all scripts have been loaded.
1107
-    if ( ! did_action( 'wp_enqueue_scripts' ) ) {
1108
-        do_action( 'wp_enqueue_scripts' );
1107
+    if (!did_action('wp_enqueue_scripts')) {
1108
+        do_action('wp_enqueue_scripts');
1109 1109
     }
1110 1110
 
1111 1111
     // Register the invoices style.
1112
-    wp_register_style( 'wpinv-single-style', WPINV_PLUGIN_URL . 'assets/css/invoice.css', array(), filemtime( WPINV_PLUGIN_DIR . 'assets/css/invoice.css' ) );
1112
+    wp_register_style('wpinv-single-style', WPINV_PLUGIN_URL . 'assets/css/invoice.css', array(), filemtime(WPINV_PLUGIN_DIR . 'assets/css/invoice.css'));
1113 1113
 
1114 1114
     // Load required styles
1115
-    wp_print_styles( 'open-sans' );
1116
-    wp_print_styles( 'wpinv-single-style' );
1117
-    wp_print_styles( 'ayecode-ui' );
1115
+    wp_print_styles('open-sans');
1116
+    wp_print_styles('wpinv-single-style');
1117
+    wp_print_styles('ayecode-ui');
1118 1118
 
1119 1119
     // Maybe load custom css.
1120
-    $custom_css = wpinv_get_option( 'template_custom_css' );
1120
+    $custom_css = wpinv_get_option('template_custom_css');
1121 1121
 
1122
-    if ( isset( $custom_css ) && ! empty( $custom_css ) ) {
1123
-        $custom_css     = wp_kses( $custom_css, array( '\'', '\"' ) );
1124
-        $custom_css     = str_replace( '&gt;', '>', $custom_css );
1122
+    if (isset($custom_css) && !empty($custom_css)) {
1123
+        $custom_css     = wp_kses($custom_css, array('\'', '\"'));
1124
+        $custom_css     = str_replace('&gt;', '>', $custom_css);
1125 1125
         echo '<style type="text/css">';
1126 1126
         echo $custom_css;
1127 1127
         echo '</style>';
1128 1128
     }
1129 1129
 
1130 1130
 }
1131
-add_action( 'wpinv_invoice_print_head', 'wpinv_display_style' );
1132
-add_action( 'wpinv_invalid_invoice_head', 'wpinv_display_style' );
1131
+add_action('wpinv_invoice_print_head', 'wpinv_display_style');
1132
+add_action('wpinv_invalid_invoice_head', 'wpinv_display_style');
1133 1133
 
1134 1134
 
1135 1135
 /**
@@ -1141,41 +1141,41 @@  discard block
 block discarded – undo
1141 1141
     // Retrieve the current invoice.
1142 1142
     $invoice_id = getpaid_get_current_invoice_id();
1143 1143
 
1144
-    if ( empty( $invoice_id ) ) {
1144
+    if (empty($invoice_id)) {
1145 1145
 
1146 1146
         return aui()->alert(
1147 1147
             array(
1148 1148
                 'type'    => 'warning',
1149
-                'content' => __( 'Invalid invoice', 'invoicing' ),
1149
+                'content' => __('Invalid invoice', 'invoicing'),
1150 1150
             )
1151 1151
         );
1152 1152
 
1153 1153
     }
1154 1154
 
1155 1155
     // Can the user view this invoice?
1156
-    if ( ! wpinv_user_can_view_invoice( $invoice_id ) ) {
1156
+    if (!wpinv_user_can_view_invoice($invoice_id)) {
1157 1157
 
1158 1158
         return aui()->alert(
1159 1159
             array(
1160 1160
                 'type'    => 'warning',
1161
-                'content' => __( 'You are not allowed to view this invoice', 'invoicing' ),
1161
+                'content' => __('You are not allowed to view this invoice', 'invoicing'),
1162 1162
             )
1163 1163
         );
1164 1164
 
1165 1165
     }
1166 1166
 
1167 1167
     // Ensure that it is not yet paid for.
1168
-    $invoice = new WPInv_Invoice( $invoice_id );
1168
+    $invoice = new WPInv_Invoice($invoice_id);
1169 1169
 
1170 1170
     // Maybe mark it as viewed.
1171
-    getpaid_maybe_mark_invoice_as_viewed( $invoice );
1171
+    getpaid_maybe_mark_invoice_as_viewed($invoice);
1172 1172
 
1173
-    if ( $invoice->is_paid() ) {
1173
+    if ($invoice->is_paid()) {
1174 1174
 
1175 1175
         return aui()->alert(
1176 1176
             array(
1177 1177
                 'type'    => 'success',
1178
-                'content' => __( 'This invoice has already been paid.', 'invoicing' ),
1178
+                'content' => __('This invoice has already been paid.', 'invoicing'),
1179 1179
             )
1180 1180
         );
1181 1181
 
@@ -1185,14 +1185,14 @@  discard block
 block discarded – undo
1185 1185
     $wpi_checkout_id = $invoice_id;
1186 1186
 
1187 1187
     // We'll display this invoice via the default form.
1188
-    $form = new GetPaid_Payment_Form( wpinv_get_default_payment_form() );
1188
+    $form = new GetPaid_Payment_Form(wpinv_get_default_payment_form());
1189 1189
 
1190
-    if ( 0 == $form->get_id() ) {
1190
+    if (0 == $form->get_id()) {
1191 1191
 
1192 1192
         return aui()->alert(
1193 1193
             array(
1194 1194
                 'type'    => 'warning',
1195
-                'content' => __( 'Error loading the payment form', 'invoicing' ),
1195
+                'content' => __('Error loading the payment form', 'invoicing'),
1196 1196
             )
1197 1197
         );
1198 1198
 
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
 
1201 1201
     // Set the invoice.
1202 1202
     $form->invoice = $invoice;
1203
-    $form->set_items( $invoice->get_items() );
1203
+    $form->set_items($invoice->get_items());
1204 1204
 
1205 1205
     // Generate the html.
1206 1206
     return $form->get_html();
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
 }
1209 1209
 
1210 1210
 function wpinv_empty_cart_message() {
1211
-	return apply_filters( 'wpinv_empty_cart_message', '<span class="wpinv_empty_cart">' . __( 'Your cart is empty.', 'invoicing' ) . '</span>' );
1211
+	return apply_filters('wpinv_empty_cart_message', '<span class="wpinv_empty_cart">' . __('Your cart is empty.', 'invoicing') . '</span>');
1212 1212
 }
1213 1213
 
1214 1214
 /**
@@ -1225,38 +1225,38 @@  discard block
 block discarded – undo
1225 1225
         )
1226 1226
     );
1227 1227
 }
1228
-add_action( 'wpinv_cart_empty', 'wpinv_empty_checkout_cart' );
1228
+add_action('wpinv_cart_empty', 'wpinv_empty_checkout_cart');
1229 1229
 
1230
-function wpinv_receipt_billing_address( $invoice_id = 0 ) {
1231
-    $invoice = wpinv_get_invoice( $invoice_id );
1230
+function wpinv_receipt_billing_address($invoice_id = 0) {
1231
+    $invoice = wpinv_get_invoice($invoice_id);
1232 1232
 
1233
-    if ( empty( $invoice ) ) {
1233
+    if (empty($invoice)) {
1234 1234
         return NULL;
1235 1235
     }
1236 1236
 
1237 1237
     $billing_details = $invoice->get_user_info();
1238
-    $address_row = wpinv_get_invoice_address_markup( $billing_details );
1238
+    $address_row = wpinv_get_invoice_address_markup($billing_details);
1239 1239
 
1240 1240
     ob_start();
1241 1241
     ?>
1242 1242
     <table class="table table-bordered table-sm wpi-billing-details">
1243 1243
         <tbody>
1244 1244
             <tr class="wpi-receipt-name">
1245
-                <th class="text-left"><?php _e( 'Name', 'invoicing' ); ?></th>
1246
-                <td><?php echo esc_html( trim( $billing_details['first_name'] . ' ' . $billing_details['last_name'] ) ) ;?></td>
1245
+                <th class="text-left"><?php _e('Name', 'invoicing'); ?></th>
1246
+                <td><?php echo esc_html(trim($billing_details['first_name'] . ' ' . $billing_details['last_name'])); ?></td>
1247 1247
             </tr>
1248 1248
             <tr class="wpi-receipt-email">
1249
-                <th class="text-left"><?php _e( 'Email', 'invoicing' ); ?></th>
1250
-                <td><?php echo $billing_details['email'] ;?></td>
1249
+                <th class="text-left"><?php _e('Email', 'invoicing'); ?></th>
1250
+                <td><?php echo $billing_details['email']; ?></td>
1251 1251
             </tr>
1252 1252
             <tr class="wpi-receipt-address">
1253
-                <th class="text-left"><?php _e( 'Address', 'invoicing' ); ?></th>
1254
-                <td><?php echo $address_row ;?></td>
1253
+                <th class="text-left"><?php _e('Address', 'invoicing'); ?></th>
1254
+                <td><?php echo $address_row; ?></td>
1255 1255
             </tr>
1256
-            <?php if ( $billing_details['phone'] ) { ?>
1256
+            <?php if ($billing_details['phone']) { ?>
1257 1257
             <tr class="wpi-receipt-phone">
1258
-                <th class="text-left"><?php _e( 'Phone', 'invoicing' ); ?></th>
1259
-                <td><?php echo esc_html( $billing_details['phone'] ) ;?></td>
1258
+                <th class="text-left"><?php _e('Phone', 'invoicing'); ?></th>
1259
+                <td><?php echo esc_html($billing_details['phone']); ?></td>
1260 1260
             </tr>
1261 1261
             <?php } ?>
1262 1262
         </tbody>
@@ -1264,7 +1264,7 @@  discard block
 block discarded – undo
1264 1264
     <?php
1265 1265
     $output = ob_get_clean();
1266 1266
     
1267
-    $output = apply_filters( 'wpinv_receipt_billing_address', $output, $invoice_id );
1267
+    $output = apply_filters('wpinv_receipt_billing_address', $output, $invoice_id);
1268 1268
 
1269 1269
     echo $output;
1270 1270
 }
@@ -1272,56 +1272,56 @@  discard block
 block discarded – undo
1272 1272
 /**
1273 1273
  * Filters the receipt page.
1274 1274
  */
1275
-function wpinv_filter_success_page_content( $content ) {
1275
+function wpinv_filter_success_page_content($content) {
1276 1276
 
1277 1277
     // Ensure this is our page.
1278
-    if ( isset( $_GET['payment-confirm'] ) && wpinv_is_success_page() ) {
1278
+    if (isset($_GET['payment-confirm']) && wpinv_is_success_page()) {
1279 1279
 
1280
-        $gateway = sanitize_text_field( $_GET['payment-confirm'] );
1281
-        return apply_filters( "wpinv_payment_confirm_$gateway", $content );
1280
+        $gateway = sanitize_text_field($_GET['payment-confirm']);
1281
+        return apply_filters("wpinv_payment_confirm_$gateway", $content);
1282 1282
 
1283 1283
     }
1284 1284
 
1285 1285
     return $content;
1286 1286
 }
1287
-add_filter( 'the_content', 'wpinv_filter_success_page_content', 99999 );
1287
+add_filter('the_content', 'wpinv_filter_success_page_content', 99999);
1288 1288
 
1289
-function wpinv_invoice_link( $invoice_id ) {
1290
-    $invoice = wpinv_get_invoice( $invoice_id );
1289
+function wpinv_invoice_link($invoice_id) {
1290
+    $invoice = wpinv_get_invoice($invoice_id);
1291 1291
 
1292
-    if ( empty( $invoice ) ) {
1292
+    if (empty($invoice)) {
1293 1293
         return NULL;
1294 1294
     }
1295 1295
 
1296
-    $invoice_link = '<a href="' . esc_url( $invoice->get_view_url() ) . '">' . $invoice->get_number() . '</a>';
1296
+    $invoice_link = '<a href="' . esc_url($invoice->get_view_url()) . '">' . $invoice->get_number() . '</a>';
1297 1297
 
1298
-    return apply_filters( 'wpinv_get_invoice_link', $invoice_link, $invoice );
1298
+    return apply_filters('wpinv_get_invoice_link', $invoice_link, $invoice);
1299 1299
 }
1300 1300
 
1301
-function wpinv_invoice_subscription_details( $invoice ) {
1302
-    if ( !empty( $invoice ) && $invoice->is_recurring() && ! wpinv_is_subscription_payment( $invoice ) ) {
1303
-        $subscription = wpinv_get_subscription( $invoice, true );
1301
+function wpinv_invoice_subscription_details($invoice) {
1302
+    if (!empty($invoice) && $invoice->is_recurring() && !wpinv_is_subscription_payment($invoice)) {
1303
+        $subscription = wpinv_get_subscription($invoice, true);
1304 1304
 
1305
-        if ( empty( $subscription ) ) {
1305
+        if (empty($subscription)) {
1306 1306
             return;
1307 1307
         }
1308 1308
 
1309 1309
         $frequency = WPInv_Subscriptions::wpinv_get_pretty_subscription_frequency($subscription->period, $subscription->frequency);
1310
-        $billing = wpinv_price(wpinv_format_amount($subscription->recurring_amount), $invoice->get_currency() ) . ' / ' . $frequency;
1311
-        $initial = wpinv_price(wpinv_format_amount($subscription->initial_amount), $invoice->get_currency() );
1310
+        $billing = wpinv_price(wpinv_format_amount($subscription->recurring_amount), $invoice->get_currency()) . ' / ' . $frequency;
1311
+        $initial = wpinv_price(wpinv_format_amount($subscription->initial_amount), $invoice->get_currency());
1312 1312
 
1313 1313
         $payments = $subscription->get_child_payments();
1314 1314
         ?>
1315 1315
         <div class="wpinv-subscriptions-details">
1316
-            <h3 class="wpinv-subscriptions-t"><?php echo apply_filters( 'wpinv_subscription_details_title', __( 'Subscription Details', 'invoicing' ) ); ?></h3>
1316
+            <h3 class="wpinv-subscriptions-t"><?php echo apply_filters('wpinv_subscription_details_title', __('Subscription Details', 'invoicing')); ?></h3>
1317 1317
             <table class="table">
1318 1318
                 <thead>
1319 1319
                     <tr>
1320
-                        <th><?php _e( 'Billing Cycle', 'invoicing' ) ;?></th>
1321
-                        <th><?php _e( 'Start Date', 'invoicing' ) ;?></th>
1322
-                        <th><?php _e( 'Expiration Date', 'invoicing' ) ;?></th>
1323
-                        <th class="text-center"><?php _e( 'Times Billed', 'invoicing' ) ;?></th>
1324
-                        <th class="text-center"><?php _e( 'Status', 'invoicing' ) ;?></th>
1320
+                        <th><?php _e('Billing Cycle', 'invoicing'); ?></th>
1321
+                        <th><?php _e('Start Date', 'invoicing'); ?></th>
1322
+                        <th><?php _e('Expiration Date', 'invoicing'); ?></th>
1323
+                        <th class="text-center"><?php _e('Times Billed', 'invoicing'); ?></th>
1324
+                        <th class="text-center"><?php _e('Status', 'invoicing'); ?></th>
1325 1325
                     </tr>
1326 1326
                 </thead>
1327 1327
                 <tbody>
@@ -1329,35 +1329,35 @@  discard block
 block discarded – undo
1329 1329
                         <td><?php printf(_x('%s then %s', 'Initial subscription amount then billing cycle and amount', 'invoicing'), $initial, $billing); ?></td>
1330 1330
                         <td><?php echo date_i18n(get_option('date_format'), strtotime($subscription->created, current_time('timestamp'))); ?></td>
1331 1331
                         <td><?php echo date_i18n(get_option('date_format'), strtotime($subscription->expiration, current_time('timestamp'))); ?></td>
1332
-                        <td class="text-center"><?php echo $subscription->get_times_billed() . ' / ' . (($subscription->bill_times == 0) ? __( 'Until Cancelled', 'invoicing' ) : $subscription->bill_times); ?></td>
1332
+                        <td class="text-center"><?php echo $subscription->get_times_billed() . ' / ' . (($subscription->bill_times == 0) ? __('Until Cancelled', 'invoicing') : $subscription->bill_times); ?></td>
1333 1333
                         <td class="text-center wpi-sub-status"><?php echo $subscription->get_status_label(); ?></td>
1334 1334
                     </tr>
1335 1335
                 </tbody>
1336 1336
             </table>
1337 1337
         </div>
1338
-        <?php if ( !empty( $payments ) ) { ?>
1338
+        <?php if (!empty($payments)) { ?>
1339 1339
         <div class="wpinv-renewal-payments">
1340
-            <h3 class="wpinv-renewals-t"><?php echo apply_filters( 'wpinv_renewal_payments_title', __( 'Renewal Payments', 'invoicing' ) ); ?></h3>
1340
+            <h3 class="wpinv-renewals-t"><?php echo apply_filters('wpinv_renewal_payments_title', __('Renewal Payments', 'invoicing')); ?></h3>
1341 1341
             <table class="table">
1342 1342
                 <thead>
1343 1343
                     <tr>
1344 1344
                         <th>#</th>
1345
-                        <th><?php _e( 'Invoice', 'invoicing' ) ;?></th>
1346
-                        <th><?php _e( 'Date', 'invoicing' ) ;?></th>
1347
-                        <th class="text-right"><?php _e( 'Amount', 'invoicing' ) ;?></th>
1345
+                        <th><?php _e('Invoice', 'invoicing'); ?></th>
1346
+                        <th><?php _e('Date', 'invoicing'); ?></th>
1347
+                        <th class="text-right"><?php _e('Amount', 'invoicing'); ?></th>
1348 1348
                     </tr>
1349 1349
                 </thead>
1350 1350
                 <tbody>
1351 1351
                     <?php
1352 1352
                         $i = 1;
1353
-                        foreach ( $payments as $payment ) {
1353
+                        foreach ($payments as $payment) {
1354 1354
                             $invoice_id = $payment->ID;
1355 1355
                     ?>
1356 1356
                     <tr>
1357
-                        <th scope="row"><?php echo $i;?></th>
1358
-                        <td><?php echo wpinv_invoice_link( $invoice_id ) ;?></td>
1357
+                        <th scope="row"><?php echo $i; ?></th>
1358
+                        <td><?php echo wpinv_invoice_link($invoice_id); ?></td>
1359 1359
                         <td><?php echo$invoice->get_date_created(); ?></td>
1360
-                        <td class="text-right"><?php echo wpinv_price( wpinv_format_amount( $invoice->get_total() ), $invoice->get_currency() ); ?></td>
1360
+                        <td class="text-right"><?php echo wpinv_price(wpinv_format_amount($invoice->get_total()), $invoice->get_currency()); ?></td>
1361 1361
                     </tr>
1362 1362
                     <?php $i++; } ?>
1363 1363
                 </tbody>
@@ -1367,64 +1367,64 @@  discard block
 block discarded – undo
1367 1367
         <?php
1368 1368
     }
1369 1369
 }
1370
-add_action( 'getpaid_invoice_line_items', 'wpinv_invoice_subscription_details', 20 );
1370
+add_action('getpaid_invoice_line_items', 'wpinv_invoice_subscription_details', 20);
1371 1371
 
1372
-function wpinv_cart_total_label( $label, $invoice ) {
1373
-    if ( empty( $invoice ) ) {
1372
+function wpinv_cart_total_label($label, $invoice) {
1373
+    if (empty($invoice)) {
1374 1374
         return $label;
1375 1375
     }
1376 1376
 
1377 1377
     $prefix_label = '';
1378
-    if ( $invoice->is_parent() && $item_id = $invoice->get_recurring() ) {
1379
-        $prefix_label   = '<span class="label label-primary label-recurring">' . __( 'Recurring Payment', 'invoicing' ) . '</span> ' . wpinv_subscription_payment_desc( $invoice );
1380
-    } else if ( $invoice->is_renewal() ) {
1381
-        $prefix_label   = '<span class="label label-primary label-renewal">' . __( 'Renewal Payment', 'invoicing' ) . '</span> ';        
1378
+    if ($invoice->is_parent() && $item_id = $invoice->get_recurring()) {
1379
+        $prefix_label   = '<span class="label label-primary label-recurring">' . __('Recurring Payment', 'invoicing') . '</span> ' . wpinv_subscription_payment_desc($invoice);
1380
+    } else if ($invoice->is_renewal()) {
1381
+        $prefix_label   = '<span class="label label-primary label-renewal">' . __('Renewal Payment', 'invoicing') . '</span> ';        
1382 1382
     }
1383 1383
 
1384
-    if ( $prefix_label != '' ) {
1385
-        $label  = '<span class="wpinv-cart-sub-desc">' . $prefix_label . '</span> ' . $label;
1384
+    if ($prefix_label != '') {
1385
+        $label = '<span class="wpinv-cart-sub-desc">' . $prefix_label . '</span> ' . $label;
1386 1386
     }
1387 1387
 
1388 1388
     return $label;
1389 1389
 }
1390
-add_filter( 'wpinv_cart_total_label', 'wpinv_cart_total_label', 10, 2 );
1391
-add_filter( 'wpinv_email_cart_total_label', 'wpinv_cart_total_label', 10, 2 );
1392
-add_filter( 'wpinv_print_cart_total_label', 'wpinv_cart_total_label', 10, 2 );
1390
+add_filter('wpinv_cart_total_label', 'wpinv_cart_total_label', 10, 2);
1391
+add_filter('wpinv_email_cart_total_label', 'wpinv_cart_total_label', 10, 2);
1392
+add_filter('wpinv_print_cart_total_label', 'wpinv_cart_total_label', 10, 2);
1393 1393
 
1394
-function wpinv_get_invoice_note_line_item( $note, $echo = true ) {
1395
-    if ( empty( $note ) ) {
1394
+function wpinv_get_invoice_note_line_item($note, $echo = true) {
1395
+    if (empty($note)) {
1396 1396
         return NULL;
1397 1397
     }
1398 1398
 
1399
-    if ( is_int( $note ) ) {
1400
-        $note = get_comment( $note );
1399
+    if (is_int($note)) {
1400
+        $note = get_comment($note);
1401 1401
     }
1402 1402
 
1403
-    if ( !( is_object( $note ) && is_a( $note, 'WP_Comment' ) ) ) {
1403
+    if (!(is_object($note) && is_a($note, 'WP_Comment'))) {
1404 1404
         return NULL;
1405 1405
     }
1406 1406
 
1407
-    $note_classes   = array( 'note' );
1408
-    $note_classes[] = get_comment_meta( $note->comment_ID, '_wpi_customer_note', true ) ? 'customer-note' : '';
1407
+    $note_classes   = array('note');
1408
+    $note_classes[] = get_comment_meta($note->comment_ID, '_wpi_customer_note', true) ? 'customer-note' : '';
1409 1409
     $note_classes[] = $note->comment_author === 'System' ? 'system-note' : '';
1410
-    $note_classes   = apply_filters( 'wpinv_invoice_note_class', array_filter( $note_classes ), $note );
1411
-    $note_classes   = !empty( $note_classes ) ? implode( ' ', $note_classes ) : '';
1410
+    $note_classes   = apply_filters('wpinv_invoice_note_class', array_filter($note_classes), $note);
1411
+    $note_classes   = !empty($note_classes) ? implode(' ', $note_classes) : '';
1412 1412
 
1413 1413
     ob_start();
1414 1414
     ?>
1415
-    <li rel="<?php echo absint( $note->comment_ID ) ; ?>" class="<?php echo esc_attr( $note_classes ); ?> mt-4 pl-3 pr-3">
1415
+    <li rel="<?php echo absint($note->comment_ID); ?>" class="<?php echo esc_attr($note_classes); ?> mt-4 pl-3 pr-3">
1416 1416
         <div class="note_content bg-light border position-relative p-4">
1417 1417
 
1418
-            <?php echo wpautop( wptexturize( wp_kses_post( $note->comment_content ) ) ); ?>
1418
+            <?php echo wpautop(wptexturize(wp_kses_post($note->comment_content))); ?>
1419 1419
 
1420
-            <?php if ( ! is_admin() ) : ?>
1420
+            <?php if (!is_admin()) : ?>
1421 1421
                 <em class="meta position-absolute form-text">
1422 1422
                     <?php
1423 1423
                         printf(
1424
-                            __( '%1$s - %2$s at %3$s', 'invoicing' ),
1424
+                            __('%1$s - %2$s at %3$s', 'invoicing'),
1425 1425
                             $note->comment_author,
1426
-                            date_i18n( get_option( 'date_format' ), strtotime( $note->comment_date ) ),
1427
-                            date_i18n( get_option( 'time_format' ), strtotime( $note->comment_date ) )
1426
+                            date_i18n(get_option('date_format'), strtotime($note->comment_date)),
1427
+                            date_i18n(get_option('time_format'), strtotime($note->comment_date))
1428 1428
                         );
1429 1429
                     ?>
1430 1430
                 </em>
@@ -1432,12 +1432,12 @@  discard block
 block discarded – undo
1432 1432
 
1433 1433
         </div>
1434 1434
 
1435
-        <?php if ( is_admin() ) : ?>
1435
+        <?php if (is_admin()) : ?>
1436 1436
 
1437 1437
             <p class="meta px-4 py-2">
1438
-                <abbr class="exact-date" title="<?php echo esc_attr( $note->comment_date ); ?>"><?php printf( __( '%1$s - %2$s at %3$s', 'invoicing' ), $note->comment_author, date_i18n( get_option( 'date_format' ), strtotime( $note->comment_date ) ), date_i18n( get_option( 'time_format' ), strtotime( $note->comment_date ) ) ); ?></abbr>&nbsp;&nbsp;
1439
-                <?php if ( $note->comment_author !== 'System' && wpinv_current_user_can_manage_invoicing() ) { ?>
1440
-                    <a href="#" class="delete_note"><?php _e( 'Delete note', 'invoicing' ); ?></a>
1438
+                <abbr class="exact-date" title="<?php echo esc_attr($note->comment_date); ?>"><?php printf(__('%1$s - %2$s at %3$s', 'invoicing'), $note->comment_author, date_i18n(get_option('date_format'), strtotime($note->comment_date)), date_i18n(get_option('time_format'), strtotime($note->comment_date))); ?></abbr>&nbsp;&nbsp;
1439
+                <?php if ($note->comment_author !== 'System' && wpinv_current_user_can_manage_invoicing()) { ?>
1440
+                    <a href="#" class="delete_note"><?php _e('Delete note', 'invoicing'); ?></a>
1441 1441
                 <?php } ?>
1442 1442
             </p>
1443 1443
 
@@ -1446,9 +1446,9 @@  discard block
 block discarded – undo
1446 1446
     </li>
1447 1447
     <?php
1448 1448
     $note_content = ob_get_clean();
1449
-    $note_content = apply_filters( 'wpinv_get_invoice_note_line_item', $note_content, $note, $echo );
1449
+    $note_content = apply_filters('wpinv_get_invoice_note_line_item', $note_content, $note, $echo);
1450 1450
 
1451
-    if ( $echo ) {
1451
+    if ($echo) {
1452 1452
         echo $note_content;
1453 1453
     } else {
1454 1454
         return $note_content;
@@ -1458,36 +1458,36 @@  discard block
 block discarded – undo
1458 1458
 function wpinv_invalid_invoice_content() {
1459 1459
     global $post;
1460 1460
 
1461
-    $invoice = wpinv_get_invoice( $post->ID );
1461
+    $invoice = wpinv_get_invoice($post->ID);
1462 1462
 
1463
-    $error = __( 'This invoice is only viewable by clicking on the invoice link that was sent to you via email.', 'invoicing' );
1464
-    if ( !empty( $invoice->get_id() ) && $invoice->has_status( array_keys( wpinv_get_invoice_statuses() ) ) ) {
1465
-        if ( is_user_logged_in() ) {
1466
-            if ( wpinv_require_login_to_checkout() ) {
1467
-                if ( isset( $_GET['invoice_key'] ) && $_GET['invoice_key'] === $invoice->get_key() ) {
1468
-                    $error = __( 'You are not allowed to view this invoice.', 'invoicing' );
1463
+    $error = __('This invoice is only viewable by clicking on the invoice link that was sent to you via email.', 'invoicing');
1464
+    if (!empty($invoice->get_id()) && $invoice->has_status(array_keys(wpinv_get_invoice_statuses()))) {
1465
+        if (is_user_logged_in()) {
1466
+            if (wpinv_require_login_to_checkout()) {
1467
+                if (isset($_GET['invoice_key']) && $_GET['invoice_key'] === $invoice->get_key()) {
1468
+                    $error = __('You are not allowed to view this invoice.', 'invoicing');
1469 1469
                 }
1470 1470
             }
1471 1471
         } else {
1472
-            if ( wpinv_require_login_to_checkout() ) {
1473
-                if ( isset( $_GET['invoice_key'] ) && $_GET['invoice_key'] === $invoice->get_key() ) {
1474
-                    $error = __( 'You must be logged in to view this invoice.', 'invoicing' );
1472
+            if (wpinv_require_login_to_checkout()) {
1473
+                if (isset($_GET['invoice_key']) && $_GET['invoice_key'] === $invoice->get_key()) {
1474
+                    $error = __('You must be logged in to view this invoice.', 'invoicing');
1475 1475
                 }
1476 1476
             }
1477 1477
         }
1478 1478
     } else {
1479
-        $error = __( 'This invoice is deleted or does not exist.', 'invoicing' );
1479
+        $error = __('This invoice is deleted or does not exist.', 'invoicing');
1480 1480
     }
1481 1481
     ?>
1482 1482
     <div class="row wpinv-row-invalid">
1483 1483
         <div class="col-md-6 col-md-offset-3 wpinv-message error">
1484
-            <h3><?php _e( 'Access Denied', 'invoicing' ); ?></h3>
1484
+            <h3><?php _e('Access Denied', 'invoicing'); ?></h3>
1485 1485
             <p class="wpinv-msg-text"><?php echo $error; ?></p>
1486 1486
         </div>
1487 1487
     </div>
1488 1488
     <?php
1489 1489
 }
1490
-add_action( 'wpinv_invalid_invoice_content', 'wpinv_invalid_invoice_content' );
1490
+add_action('wpinv_invalid_invoice_content', 'wpinv_invalid_invoice_content');
1491 1491
 
1492 1492
 /**
1493 1493
  * Function to get privacy policy text.
@@ -1496,21 +1496,21 @@  discard block
 block discarded – undo
1496 1496
  * @return string
1497 1497
  */
1498 1498
 function wpinv_get_policy_text() {
1499
-    $privacy_page_id = get_option( 'wp_page_for_privacy_policy', 0 );
1499
+    $privacy_page_id = get_option('wp_page_for_privacy_policy', 0);
1500 1500
 
1501
-    $text = wpinv_get_option('invoicing_privacy_checkout_message', sprintf( __( 'Your personal data will be used to process your invoice, payment and for other purposes described in our %s.', 'invoicing' ), '[wpinv_privacy_policy]' ));
1501
+    $text = wpinv_get_option('invoicing_privacy_checkout_message', sprintf(__('Your personal data will be used to process your invoice, payment and for other purposes described in our %s.', 'invoicing'), '[wpinv_privacy_policy]'));
1502 1502
 
1503
-    if(!$privacy_page_id){
1504
-        $privacy_page_id = wpinv_get_option( 'privacy_page', 0 );
1503
+    if (!$privacy_page_id) {
1504
+        $privacy_page_id = wpinv_get_option('privacy_page', 0);
1505 1505
     }
1506 1506
 
1507
-    $privacy_link    = $privacy_page_id ? '<a href="' . esc_url( get_permalink( $privacy_page_id ) ) . '" class="wpinv-privacy-policy-link" target="_blank">' . __( 'privacy policy', 'invoicing' ) . '</a>' : __( 'privacy policy', 'invoicing' );
1507
+    $privacy_link = $privacy_page_id ? '<a href="' . esc_url(get_permalink($privacy_page_id)) . '" class="wpinv-privacy-policy-link" target="_blank">' . __('privacy policy', 'invoicing') . '</a>' : __('privacy policy', 'invoicing');
1508 1508
 
1509 1509
     $find_replace = array(
1510 1510
         '[wpinv_privacy_policy]' => $privacy_link,
1511 1511
     );
1512 1512
 
1513
-    $privacy_text = str_replace( array_keys( $find_replace ), array_values( $find_replace ), $text );
1513
+    $privacy_text = str_replace(array_keys($find_replace), array_values($find_replace), $text);
1514 1514
 
1515 1515
     return wp_kses_post(wpautop($privacy_text));
1516 1516
 }
@@ -1518,21 +1518,21 @@  discard block
 block discarded – undo
1518 1518
 function wpinv_oxygen_fix_conflict() {
1519 1519
     global $ct_ignore_post_types;
1520 1520
 
1521
-    if ( ! is_array( $ct_ignore_post_types ) ) {
1521
+    if (!is_array($ct_ignore_post_types)) {
1522 1522
         $ct_ignore_post_types = array();
1523 1523
     }
1524 1524
 
1525
-    $post_types = array( 'wpi_discount', 'wpi_invoice', 'wpi_item' );
1525
+    $post_types = array('wpi_discount', 'wpi_invoice', 'wpi_item');
1526 1526
 
1527
-    foreach ( $post_types as $post_type ) {
1527
+    foreach ($post_types as $post_type) {
1528 1528
         $ct_ignore_post_types[] = $post_type;
1529 1529
 
1530 1530
         // Ignore post type
1531
-        add_filter( 'pre_option_oxygen_vsb_ignore_post_type_' . $post_type, '__return_true', 999 );
1531
+        add_filter('pre_option_oxygen_vsb_ignore_post_type_' . $post_type, '__return_true', 999);
1532 1532
     }
1533 1533
 
1534
-    remove_filter( 'template_include', 'wpinv_template', 10, 1 );
1535
-    add_filter( 'template_include', 'wpinv_template', 999, 1 );
1534
+    remove_filter('template_include', 'wpinv_template', 10, 1);
1535
+    add_filter('template_include', 'wpinv_template', 999, 1);
1536 1536
 }
1537 1537
 
1538 1538
 /**
@@ -1540,10 +1540,10 @@  discard block
 block discarded – undo
1540 1540
  * 
1541 1541
  * @param GetPaid_Payment_Form $form
1542 1542
  */
1543
-function getpaid_display_payment_form( $form ) {
1543
+function getpaid_display_payment_form($form) {
1544 1544
 
1545
-    if ( is_numeric( $form ) ) {
1546
-        $form = new GetPaid_Payment_Form( $form );
1545
+    if (is_numeric($form)) {
1546
+        $form = new GetPaid_Payment_Form($form);
1547 1547
     }
1548 1548
 
1549 1549
     $form->display();
@@ -1553,16 +1553,16 @@  discard block
 block discarded – undo
1553 1553
 /**
1554 1554
  * Helper function to display a item payment form on the frontend.
1555 1555
  */
1556
-function getpaid_display_item_payment_form( $items ) {
1556
+function getpaid_display_item_payment_form($items) {
1557 1557
 
1558
-    $form = new GetPaid_Payment_Form( wpinv_get_default_payment_form() );
1559
-    $form->set_items( $items );
1558
+    $form = new GetPaid_Payment_Form(wpinv_get_default_payment_form());
1559
+    $form->set_items($items);
1560 1560
 
1561
-    if ( 0 == count( $form->get_items() ) ) {
1561
+    if (0 == count($form->get_items())) {
1562 1562
         echo aui()->alert(
1563 1563
 			array(
1564 1564
 				'type'    => 'warning',
1565
-				'content' => __( 'No published items found', 'invoicing' ),
1565
+				'content' => __('No published items found', 'invoicing'),
1566 1566
 			)
1567 1567
         );
1568 1568
         return;
@@ -1574,75 +1574,75 @@  discard block
 block discarded – undo
1574 1574
 /**
1575 1575
  * Helper function to display an invoice payment form on the frontend.
1576 1576
  */
1577
-function getpaid_display_invoice_payment_form( $invoice_id ) {
1577
+function getpaid_display_invoice_payment_form($invoice_id) {
1578 1578
     global $invoicing;
1579 1579
 
1580
-    $invoice = wpinv_get_invoice( $invoice_id );
1580
+    $invoice = wpinv_get_invoice($invoice_id);
1581 1581
 
1582
-    if ( empty( $invoice ) ) {
1582
+    if (empty($invoice)) {
1583 1583
 		return aui()->alert(
1584 1584
 			array(
1585 1585
 				'type'    => 'warning',
1586
-				'content' => __( 'Invoice not found', 'invoicing' ),
1586
+				'content' => __('Invoice not found', 'invoicing'),
1587 1587
 			)
1588 1588
 		);
1589 1589
     }
1590 1590
 
1591
-    if ( $invoice->is_paid() ) {
1591
+    if ($invoice->is_paid()) {
1592 1592
 		return aui()->alert(
1593 1593
 			array(
1594 1594
 				'type'    => 'warning',
1595
-				'content' => __( 'Invoice has already been paid', 'invoicing' ),
1595
+				'content' => __('Invoice has already been paid', 'invoicing'),
1596 1596
 			)
1597 1597
 		);
1598 1598
     }
1599 1599
 
1600 1600
     // Get the form elements and items.
1601
-    $form     = wpinv_get_default_payment_form();
1602
-	$elements = $invoicing->form_elements->get_form_elements( $form );
1603
-	$items    = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
1601
+    $form = wpinv_get_default_payment_form();
1602
+	$elements = $invoicing->form_elements->get_form_elements($form);
1603
+	$items    = $invoicing->form_elements->convert_checkout_items($invoice->cart_details, $invoice);
1604 1604
 
1605 1605
 	ob_start();
1606 1606
 	echo "<form class='wpinv_payment_form'>";
1607
-	do_action( 'wpinv_payment_form_top' );
1607
+	do_action('wpinv_payment_form_top');
1608 1608
     echo "<input type='hidden' name='form_id' value='$form'/>";
1609 1609
     echo "<input type='hidden' name='invoice_id' value='$invoice_id'/>";
1610
-	wp_nonce_field( 'wpinv_payment_form', 'wpinv_payment_form' );
1611
-	wp_nonce_field( 'vat_validation', '_wpi_nonce' );
1610
+	wp_nonce_field('wpinv_payment_form', 'wpinv_payment_form');
1611
+	wp_nonce_field('vat_validation', '_wpi_nonce');
1612 1612
 
1613
-	foreach ( $elements as $element ) {
1614
-		do_action( 'wpinv_frontend_render_payment_form_element', $element, $items, $form );
1615
-		do_action( "wpinv_frontend_render_payment_form_{$element['type']}", $element, $items, $form );
1613
+	foreach ($elements as $element) {
1614
+		do_action('wpinv_frontend_render_payment_form_element', $element, $items, $form);
1615
+		do_action("wpinv_frontend_render_payment_form_{$element['type']}", $element, $items, $form);
1616 1616
 	}
1617 1617
 
1618 1618
 	echo "<div class='wpinv_payment_form_errors alert alert-danger d-none'></div>";
1619
-	do_action( 'wpinv_payment_form_bottom' );
1619
+	do_action('wpinv_payment_form_bottom');
1620 1620
 	echo '</form>';
1621 1621
 
1622 1622
 	$content = ob_get_clean();
1623
-	return str_replace( 'sr-only', '', $content );
1623
+	return str_replace('sr-only', '', $content);
1624 1624
 }
1625 1625
 
1626 1626
 /**
1627 1627
  * Helper function to convert item string to array.
1628 1628
  */
1629
-function getpaid_convert_items_to_array( $items ) {
1630
-    $items    = array_filter( array_map( 'trim', explode( ',', $items ) ) );
1629
+function getpaid_convert_items_to_array($items) {
1630
+    $items    = array_filter(array_map('trim', explode(',', $items)));
1631 1631
     $prepared = array();
1632 1632
 
1633
-    foreach ( $items as $item ) {
1634
-        $data = array_map( 'trim', explode( '|', $item ) );
1633
+    foreach ($items as $item) {
1634
+        $data = array_map('trim', explode('|', $item));
1635 1635
 
1636
-        if ( empty( $data[0] ) || ! is_numeric( $data[0] ) ) {
1636
+        if (empty($data[0]) || !is_numeric($data[0])) {
1637 1637
             continue;
1638 1638
         }
1639 1639
 
1640 1640
         $quantity = 1;
1641
-        if ( isset( $data[1] ) && is_numeric( $data[1] ) ) {
1641
+        if (isset($data[1]) && is_numeric($data[1])) {
1642 1642
             $quantity = (int) $data[1];
1643 1643
         }
1644 1644
 
1645
-        $prepared[ $data[0] ] = $quantity;
1645
+        $prepared[$data[0]] = $quantity;
1646 1646
 
1647 1647
     }
1648 1648
 
@@ -1652,13 +1652,13 @@  discard block
 block discarded – undo
1652 1652
 /**
1653 1653
  * Helper function to convert item array to string.
1654 1654
  */
1655
-function getpaid_convert_items_to_string( $items ) {
1655
+function getpaid_convert_items_to_string($items) {
1656 1656
     $prepared = array();
1657 1657
 
1658
-    foreach ( $items as $item => $quantity ) {
1658
+    foreach ($items as $item => $quantity) {
1659 1659
         $prepared[] = "$item|$quantity";
1660 1660
     }
1661
-    return implode( ',', $prepared );
1661
+    return implode(',', $prepared);
1662 1662
 }
1663 1663
 
1664 1664
 /**
@@ -1666,22 +1666,22 @@  discard block
 block discarded – undo
1666 1666
  * 
1667 1667
  * Provide a label and one of $form, $items or $invoice.
1668 1668
  */
1669
-function getpaid_get_payment_button( $label, $form = null, $items = null, $invoice = null ) {
1670
-    $label = sanitize_text_field( $label );
1669
+function getpaid_get_payment_button($label, $form = null, $items = null, $invoice = null) {
1670
+    $label = sanitize_text_field($label);
1671 1671
     $nonce = wp_create_nonce('getpaid_ajax_form');
1672 1672
 
1673
-    if ( ! empty( $form ) ) {
1674
-        $form  = esc_attr( $form );
1673
+    if (!empty($form)) {
1674
+        $form = esc_attr($form);
1675 1675
         return "<button class='btn btn-primary getpaid-payment-button' type='button' data-nonce='$nonce' data-form='$form'>$label</button>"; 
1676 1676
     }
1677 1677
 	
1678
-	if ( ! empty( $items ) ) {
1679
-        $items  = esc_attr( $items );
1678
+	if (!empty($items)) {
1679
+        $items = esc_attr($items);
1680 1680
         return "<button class='btn btn-primary getpaid-payment-button' type='button' data-nonce='$nonce' data-item='$items'>$label</button>"; 
1681 1681
     }
1682 1682
     
1683
-    if ( ! empty( $invoice ) ) {
1684
-        $invoice  = esc_attr( $invoice );
1683
+    if (!empty($invoice)) {
1684
+        $invoice = esc_attr($invoice);
1685 1685
         return "<button class='btn btn-primary getpaid-payment-button' type='button' data-nonce='$nonce' data-invoice='$invoice'>$label</button>"; 
1686 1686
     }
1687 1687
 
@@ -1692,17 +1692,17 @@  discard block
 block discarded – undo
1692 1692
  *
1693 1693
  * @param WPInv_Invoice $invoice
1694 1694
  */
1695
-function getpaid_the_invoice_description( $invoice ) {
1695
+function getpaid_the_invoice_description($invoice) {
1696 1696
     $description = $invoice->get_description();
1697 1697
 
1698
-    if ( empty( $description ) ) {
1698
+    if (empty($description)) {
1699 1699
         return;
1700 1700
     }
1701 1701
 
1702
-    $description = wp_kses_post( $description );
1702
+    $description = wp_kses_post($description);
1703 1703
     echo "<small class='getpaid-invoice-description text-dark p-2 form-text'><em>$description</em></small>";
1704 1704
 }
1705
-add_action( 'getpaid_invoice_line_items', 'getpaid_the_invoice_description', 100 );
1705
+add_action('getpaid_invoice_line_items', 'getpaid_the_invoice_description', 100);
1706 1706
 
1707 1707
 /**
1708 1708
  * Render element on a form.
@@ -1710,41 +1710,41 @@  discard block
 block discarded – undo
1710 1710
  * @param array $element
1711 1711
  * @param GetPaid_Payment_Form $form
1712 1712
  */
1713
-function getpaid_payment_form_element( $element, $form ) {
1713
+function getpaid_payment_form_element($element, $form) {
1714 1714
 
1715 1715
     // Set up the args.
1716
-    $element_type    = trim( $element['type'] );
1716
+    $element_type    = trim($element['type']);
1717 1717
     $element['form'] = $form;
1718
-    extract( $element );
1718
+    extract($element);
1719 1719
 
1720 1720
     // Try to locate the appropriate template.
1721
-    $located = wpinv_locate_template( "payment-forms/elements/$element_type.php" );
1721
+    $located = wpinv_locate_template("payment-forms/elements/$element_type.php");
1722 1722
     
1723 1723
     // Abort if this is not our element.
1724
-    if ( empty( $located ) || ! file_exists( $located ) ) {
1724
+    if (empty($located) || !file_exists($located)) {
1725 1725
         return;
1726 1726
     }
1727 1727
 
1728 1728
     // Generate the class and id of the element.
1729
-    $wrapper_class = 'getpaid-payment-form-element-' . trim( esc_attr( $element_type ) );
1730
-    $id            = isset( $id ) ? $id : uniqid( 'gp' );
1729
+    $wrapper_class = 'getpaid-payment-form-element-' . trim(esc_attr($element_type));
1730
+    $id            = isset($id) ? $id : uniqid('gp');
1731 1731
 
1732 1732
     // Echo the opening wrapper.
1733 1733
     echo "<div class='getpaid-payment-form-element $wrapper_class'>";
1734 1734
 
1735 1735
     // Fires before displaying a given element type's content.
1736
-    do_action( "getpaid_before_payment_form_{$element_type}_element", $element, $form );
1736
+    do_action("getpaid_before_payment_form_{$element_type}_element", $element, $form);
1737 1737
 
1738 1738
     // Include the template for the element.
1739 1739
     include $located;
1740 1740
 
1741 1741
     // Fires after displaying a given element type's content.
1742
-    do_action( "getpaid_payment_form_{$element_type}_element", $element, $form );
1742
+    do_action("getpaid_payment_form_{$element_type}_element", $element, $form);
1743 1743
 
1744 1744
     // Echo the closing wrapper.
1745 1745
     echo '</div>';
1746 1746
 }
1747
-add_action( 'getpaid_payment_form_element', 'getpaid_payment_form_element', 10, 2 );
1747
+add_action('getpaid_payment_form_element', 'getpaid_payment_form_element', 10, 2);
1748 1748
 
1749 1749
 /**
1750 1750
  * Shows a list of gateways that support recurring payments.
@@ -1752,17 +1752,17 @@  discard block
 block discarded – undo
1752 1752
 function wpinv_get_recurring_gateways_text() {
1753 1753
     $gateways = array();
1754 1754
 
1755
-    foreach ( wpinv_get_payment_gateways() as $key => $gateway ) {
1756
-        if ( wpinv_gateway_support_subscription( $key ) ) {
1757
-            $gateways[] = sanitize_text_field( $gateway['admin_label'] );
1755
+    foreach (wpinv_get_payment_gateways() as $key => $gateway) {
1756
+        if (wpinv_gateway_support_subscription($key)) {
1757
+            $gateways[] = sanitize_text_field($gateway['admin_label']);
1758 1758
         }
1759 1759
     }
1760 1760
 
1761
-    if ( empty( $gateways ) ) {
1762
-        return "<span class='form-text text-danger'>" . __( 'No active gateways support subscription payments.', 'invoicing' ) ."</span>";
1761
+    if (empty($gateways)) {
1762
+        return "<span class='form-text text-danger'>" . __('No active gateways support subscription payments.', 'invoicing') . "</span>";
1763 1763
     }
1764 1764
 
1765
-    return "<span class='form-text text-muted'>" . wp_sprintf( __( 'Subscription payments only supported by: %s', 'invoicing' ), implode( ', ', $gateways ) ) ."</span>";
1765
+    return "<span class='form-text text-muted'>" . wp_sprintf(__('Subscription payments only supported by: %s', 'invoicing'), implode(', ', $gateways)) . "</span>";
1766 1766
 
1767 1767
 }
1768 1768
 
@@ -1772,5 +1772,5 @@  discard block
 block discarded – undo
1772 1772
  * @return GetPaid_Template
1773 1773
  */
1774 1774
 function getpaid_template() {
1775
-    return getpaid()->get( 'template' );
1775
+    return getpaid()->get('template');
1776 1776
 }
Please login to merge, or discard this patch.