Passed
Push — master ( 854221...ab48b7 )
by Brian
04:29
created

GetPaid_Admin::duplicate_invoice()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 4
nop 1
dl 0
loc 33
rs 9.7
c 0
b 0
f 0
1
<?php
2
/**
3
 * Contains the admin class.
4
 *
5
 */
6
7
defined( 'ABSPATH' ) || exit;
8
9
/**
10
 * The main admin class.
11
 *
12
 * @since       1.0.19
13
 */
14
class GetPaid_Admin {
15
16
    /**
17
	 * Local path to this plugins admin directory
18
	 *
19
	 * @var         string
20
	 */
21
	public $admin_path;
22
23
	/**
24
	 * Web path to this plugins admin directory
25
	 *
26
	 * @var         string
27
	 */
28
	public $admin_url;
29
30
	/**
31
	 * Reports components.
32
	 *
33
	 * @var GetPaid_Reports
34
	 */
35
    public $reports;
36
37
    /**
38
	 * Class constructor.
39
	 */
40
	public function __construct() {
41
42
        $this->admin_path  = plugin_dir_path( __FILE__ );
43
		$this->admin_url   = plugins_url( '/', __FILE__ );
44
		$this->reports     = new GetPaid_Reports();
45
46
        if ( is_admin() ) {
47
			$this->init_admin_hooks();
48
        }
49
50
    }
51
52
    /**
53
	 * Init action and filter hooks
54
	 *
55
	 */
56
	private function init_admin_hooks() {
57
        add_action( 'admin_enqueue_scripts', array( $this, 'enqeue_scripts' ), 9 );
58
        add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
59
        add_action( 'admin_init', array( $this, 'init_ayecode_connect_helper' ) );
60
        add_action( 'admin_init', array( $this, 'activation_redirect' ) );
61
        add_action( 'admin_init', array( $this, 'maybe_do_admin_action' ) );
62
		add_action( 'admin_notices', array( $this, 'show_notices' ) );
63
		add_action( 'getpaid_authenticated_admin_action_rate_plugin', array( $this, 'redirect_to_wordpress_rating_page' ) );
64
		add_action( 'getpaid_authenticated_admin_action_duplicate_form', array( $this, 'duplicate_payment_form' ) );
65
		add_action( 'getpaid_authenticated_admin_action_duplicate_invoice', array( $this, 'duplicate_invoice' ) );
66
		add_action( 'getpaid_authenticated_admin_action_send_invoice', array( $this, 'send_customer_invoice' ) );
67
		add_action( 'getpaid_authenticated_admin_action_send_invoice_reminder', array( $this, 'send_customer_payment_reminder' ) );
68
        add_action( 'getpaid_authenticated_admin_action_reset_tax_rates', array( $this, 'admin_reset_tax_rates' ) );
69
		add_action( 'getpaid_authenticated_admin_action_create_missing_pages', array( $this, 'admin_create_missing_pages' ) );
70
		add_action( 'getpaid_authenticated_admin_action_refresh_permalinks', array( $this, 'admin_refresh_permalinks' ) );
71
		add_action( 'getpaid_authenticated_admin_action_create_missing_tables', array( $this, 'admin_create_missing_tables' ) );
72
		add_action( 'getpaid_authenticated_admin_action_migrate_old_invoices', array( $this, 'admin_migrate_old_invoices' ) );
73
		add_action( 'getpaid_authenticated_admin_action_download_customers', array( $this, 'admin_download_customers' ) );
74
		add_action( 'getpaid_authenticated_admin_action_recalculate_discounts', array( $this, 'admin_recalculate_discounts' ) );
75
		add_action( 'getpaid_authenticated_admin_action_install_plugin', array( $this, 'admin_install_plugin' ) );
76
		add_action( 'getpaid_authenticated_admin_action_connect_gateway', array( $this, 'admin_connect_gateway' ) );
77
		add_filter( 'admin_footer_text', array( $this, 'admin_footer_text' ) );
78
		do_action( 'getpaid_init_admin_hooks', $this );
79
80
		// Setup/welcome
81
		if ( ! empty( $_GET['page'] ) ) {
82
			switch ( sanitize_text_field( $_GET['page'] ) ) {
83
				case 'gp-setup':
84
					include_once dirname( __FILE__ ) . '/class-getpaid-admin-setup-wizard.php';
85
					break;
86
			}
87
		}
88
89
    }
90
91
    /**
92
	 * Register admin scripts
93
	 *
94
	 */
95
	public function enqeue_scripts() {
96
        global $current_screen, $pagenow;
97
98
		$page    = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
99
		$editing = $pagenow == 'post.php' || $pagenow == 'post-new.php';
100
101
        if ( ! empty( $current_screen->post_type ) ) {
102
			$page = $current_screen->post_type;
103
        }
104
105
        // General styles.
106
        if ( false !== stripos( $page, 'wpi' ) || false !== stripos( $page, 'getpaid' ) || 'gp-setup' == $page || false !== stripos( $page, 'geodir-tickets' ) ) {
107
108
            // Styles.
109
            $version = filemtime( WPINV_PLUGIN_DIR . 'assets/css/admin.css' );
110
            wp_enqueue_style( 'wpinv_admin_style', WPINV_PLUGIN_URL . 'assets/css/admin.css', array( 'wp-color-picker' ), $version );
111
            wp_enqueue_style( 'select2', WPINV_PLUGIN_URL . 'assets/css/select2/select2.min.css', array(), '4.0.13', 'all' );
112
113
            // Scripts.
114
            wp_enqueue_script( 'select2', WPINV_PLUGIN_URL . 'assets/js/select2/select2.full.min.js', array( 'jquery' ), WPINV_VERSION );
115
116
            $version = filemtime( WPINV_PLUGIN_DIR . 'assets/js/admin.js' );
117
            wp_enqueue_script( 'wpinv-admin-script', WPINV_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery', 'wp-color-picker', 'jquery-ui-tooltip' ), $version );
118
            wp_localize_script( 'wpinv-admin-script', 'WPInv_Admin', apply_filters( 'wpinv_admin_js_localize', $this->get_admin_i18() ) );
119
120
        }
121
122
        // Payment form scripts.
123
		if ( 'wpi_payment_form' == $page && $editing ) {
124
            $this->load_payment_form_scripts();
125
        }
126
127
		if ( $page == 'wpinv-subscriptions' ) {
128
			wp_enqueue_script( 'postbox' );
129
		}
130
131
    }
132
133
    /**
134
	 * Returns admin js translations.
135
	 *
136
	 */
137
	protected function get_admin_i18() {
138
        global $post;
139
140
		$date_range = array(
141
			'period' => isset( $_GET['date_range'] ) ? sanitize_text_field( $_GET['date_range'] ) : '7_days',
142
		);
143
144
		if ( $date_range['period'] == 'custom' ) {
145
146
			if ( isset( $_GET['from'] ) ) {
147
				$date_range['after'] = date( 'Y-m-d', strtotime( sanitize_text_field( $_GET['from'] ), current_time( 'timestamp' ) ) - DAY_IN_SECONDS );
148
			}
149
150
			if ( isset( $_GET['to'] ) ) {
151
				$date_range['before'] = date( 'Y-m-d', strtotime( sanitize_text_field( $_GET['to'] ), current_time( 'timestamp' ) ) + DAY_IN_SECONDS );
152
			}
153
}
154
155
        $i18n = array(
156
            'ajax_url'                  => admin_url( 'admin-ajax.php' ),
157
            'post_ID'                   => isset( $post->ID ) ? $post->ID : '',
158
			'wpinv_nonce'               => wp_create_nonce( 'wpinv-nonce' ),
159
			'rest_nonce'                => wp_create_nonce( 'wp_rest' ),
160
			'rest_root'                 => esc_url_raw( rest_url() ),
161
			'date_range'                => $date_range,
162
            'add_invoice_note_nonce'    => wp_create_nonce( 'add-invoice-note' ),
163
            'delete_invoice_note_nonce' => wp_create_nonce( 'delete-invoice-note' ),
164
            'invoice_item_nonce'        => wp_create_nonce( 'invoice-item' ),
165
            'billing_details_nonce'     => wp_create_nonce( 'get-billing-details' ),
166
            'tax'                       => wpinv_tax_amount(),
167
            'discount'                  => 0,
168
			'currency_symbol'           => wpinv_currency_symbol(),
169
			'currency'                  => wpinv_get_currency(),
170
            'currency_pos'              => wpinv_currency_position(),
171
            'thousand_sep'              => wpinv_thousands_separator(),
172
            'decimal_sep'               => wpinv_decimal_separator(),
173
            'decimals'                  => wpinv_decimals(),
174
            'save_invoice'              => __( 'Save Invoice', 'invoicing' ),
175
            'status_publish'            => wpinv_status_nicename( 'publish' ),
176
            'status_pending'            => wpinv_status_nicename( 'wpi-pending' ),
177
            'delete_tax_rate'           => __( 'Are you sure you wish to delete this tax rate?', 'invoicing' ),
178
            'status_pending'            => wpinv_status_nicename( 'wpi-pending' ),
179
            'FillBillingDetails'        => __( 'Fill the user\'s billing information? This will remove any currently entered billing information', 'invoicing' ),
180
            'confirmCalcTotals'         => __( 'Recalculate totals? This will recalculate totals based on the user billing country. If no billing country is set it will use the base country.', 'invoicing' ),
181
            'AreYouSure'                => __( 'Are you sure?', 'invoicing' ),
182
            'errDeleteItem'             => __( 'This item is in use! Before delete this item, you need to delete all the invoice(s) using this item.', 'invoicing' ),
183
            'delete_subscription'       => __( 'Are you sure you want to delete this subscription?', 'invoicing' ),
184
            'action_edit'               => __( 'Edit', 'invoicing' ),
185
            'action_cancel'             => __( 'Cancel', 'invoicing' ),
186
            'item_description'          => __( 'Item Description', 'invoicing' ),
187
            'invoice_description'       => __( 'Invoice Description', 'invoicing' ),
188
            'discount_description'      => __( 'Discount Description', 'invoicing' ),
189
			'searching'                 => __( 'Searching', 'invoicing' ),
190
			'loading'                   => __( 'Loading...', 'invoicing' ),
191
			'search_customers'          => __( 'Enter customer name or email', 'invoicing' ),
192
			'search_items'              => __( 'Enter item name', 'invoicing' ),
193
			'graphs'                    => array_merge( array( 'refunded_fees', 'refunded_items', 'refunded_subtotal', 'refunded_tax' ), array_keys( wpinv_get_report_graphs() ) ),
194
        );
195
196
		if ( ! empty( $post ) && getpaid_is_invoice_post_type( $post->post_type ) ) {
197
198
			$invoice              = new WPInv_Invoice( $post );
199
			$i18n['save_invoice'] = sprintf(
200
				__( 'Save %s', 'invoicing' ),
201
				ucfirst( $invoice->get_invoice_quote_type() )
202
			);
203
204
			$i18n['invoice_description'] = sprintf(
205
				__( '%s Description', 'invoicing' ),
206
				ucfirst( $invoice->get_invoice_quote_type() )
207
			);
208
209
		}
210
		return $i18n;
211
	}
212
213
	/**
214
	 * Change the admin footer text on GetPaid admin pages.
215
	 *
216
	 * @since  2.0.0
217
	 * @param  string $footer_text
218
	 * @return string
219
	 */
220
	public function admin_footer_text( $footer_text ) {
221
		global $current_screen;
222
223
		$page    = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
224
225
        if ( ! empty( $current_screen->post_type ) ) {
226
			$page = $current_screen->post_type;
227
        }
228
229
        // General styles.
230
        if ( apply_filters( 'getpaid_display_admin_footer_text', wpinv_current_user_can_manage_invoicing() ) && false !== stripos( $page, 'wpi' ) ) {
231
232
			// Change the footer text
233
			if ( ! get_user_meta( get_current_user_id(), 'getpaid_admin_footer_text_rated', true ) ) {
234
235
				$rating_url  = esc_url(
236
					wp_nonce_url(
237
						admin_url( 'admin.php?page=wpinv-reports&getpaid-admin-action=rate_plugin' ),
238
						'getpaid-nonce',
239
						'getpaid-nonce'
240
                    )
241
				);
242
243
				$footer_text = sprintf(
244
					/* translators: %s: five stars */
245
					__( 'If you like <strong>GetPaid</strong>, please leave us a %s rating. A huge thanks in advance!', 'invoicing' ),
246
					"<a href='$rating_url'>&#9733;&#9733;&#9733;&#9733;&#9733;</a>"
247
				);
248
249
			} else {
250
251
				$footer_text = sprintf(
252
					/* translators: %s: GetPaid */
253
					__( 'Thank you for using %s!', 'invoicing' ),
254
					"<a href='https://wpgetpaid.com/' target='_blank'><strong>GetPaid</strong></a>"
255
				);
256
257
			}
258
}
259
260
		return $footer_text;
261
	}
262
263
	/**
264
	 * Redirects to wp.org to rate the plugin.
265
	 *
266
	 * @since  2.0.0
267
	 */
268
	public function redirect_to_wordpress_rating_page() {
269
		update_user_meta( get_current_user_id(), 'getpaid_admin_footer_text_rated', 1 );
270
		wp_redirect( 'https://wordpress.org/support/plugin/invoicing/reviews?rate=5#new-post' );
271
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
272
	}
273
274
    /**
275
	 * Loads payment form js.
276
	 *
277
	 */
278
	protected function load_payment_form_scripts() {
279
        global $post;
280
281
        wp_enqueue_script( 'vue', WPINV_PLUGIN_URL . 'assets/js/vue/vue.min.js', array(), WPINV_VERSION );
282
		wp_enqueue_script( 'sortable', WPINV_PLUGIN_URL . 'assets/js/sortable.min.js', array(), WPINV_VERSION );
283
		wp_enqueue_script( 'vue_draggable', WPINV_PLUGIN_URL . 'assets/js/vue/vuedraggable.min.js', array( 'sortable', 'vue' ), WPINV_VERSION );
284
285
		$version = filemtime( WPINV_PLUGIN_DIR . 'assets/js/admin-payment-forms.js' );
286
		wp_register_script( 'wpinv-admin-payment-form-script', WPINV_PLUGIN_URL . 'assets/js/admin-payment-forms.js', array( 'wpinv-admin-script', 'vue_draggable', 'wp-hooks' ), $version );
287
288
		wp_localize_script(
289
            'wpinv-admin-payment-form-script',
290
            'wpinvPaymentFormAdmin',
291
            array(
292
				'elements'      => wpinv_get_data( 'payment-form-elements' ),
293
				'form_elements' => getpaid_get_payment_form_elements( $post->ID ),
294
				'currency'      => wpinv_currency_symbol(),
295
				'position'      => wpinv_currency_position(),
296
				'decimals'      => (int) wpinv_decimals(),
297
				'thousands_sep' => wpinv_thousands_separator(),
298
				'decimals_sep'  => wpinv_decimal_separator(),
299
				'form_items'    => gepaid_get_form_items( $post->ID ),
300
				'is_default'    => $post->ID == wpinv_get_default_payment_form(),
301
            )
302
        );
303
304
        wp_enqueue_script( 'wpinv-admin-payment-form-script' );
305
306
    }
307
308
    /**
309
	 * Add our classes to admin pages.
310
     *
311
     * @param string $classes
312
     * @return string
313
	 *
314
	 */
315
    public function admin_body_class( $classes ) {
316
		global $pagenow, $post, $current_screen;
317
318
        $page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
319
320
        if ( ! empty( $current_screen->post_type ) ) {
321
			$page = $current_screen->post_type;
322
        }
323
324
        if ( false !== stripos( $page, 'wpi' ) ) {
325
            $classes .= ' wpi-' . sanitize_key( $page );
326
        }
327
328
        if ( in_array( $page, wpinv_parse_list( 'wpi_invoice wpi_payment_form wpi_quote' ) ) ) {
329
            $classes .= ' wpinv-cpt wpinv';
330
		}
331
332
		if ( getpaid_is_invoice_post_type( $page ) ) {
333
            $classes .= ' getpaid-is-invoice-cpt';
334
        }
335
336
		return $classes;
337
    }
338
339
    /**
340
	 * Maybe show the AyeCode Connect Notice.
341
	 */
342
	public function init_ayecode_connect_helper() {
343
344
		// Register with the deactivation survey class.
345
		AyeCode_Deactivation_Survey::instance(
346
            array(
347
				'slug'              => 'invoicing',
348
				'version'           => WPINV_VERSION,
349
				'support_url'       => 'https://wpgetpaid.com/support/',
350
				'documentation_url' => 'https://docs.wpgetpaid.com/',
351
				'activated'         => (int) get_option( 'gepaid_installed_on' ),
352
            )
353
        );
354
355
        new AyeCode_Connect_Helper(
356
            array(
357
				'connect_title'     => __( 'WP Invoicing - an AyeCode product!', 'invoicing' ),
358
				'connect_external'  => __( 'Please confirm you wish to connect your site?', 'invoicing' ),
359
				'connect'           => sprintf( __( '<strong>Have a license?</strong> Forget about entering license keys or downloading zip files, connect your site for instant access. %1$slearn more%2$s', 'invoicing' ), "<a href='https://ayecode.io/introducing-ayecode-connect/' target='_blank'>", '</a>' ),
360
				'connect_button'    => __( 'Connect Site', 'invoicing' ),
361
				'connecting_button' => __( 'Connecting...', 'invoicing' ),
362
				'error_localhost'   => __( 'This service will only work with a live domain, not a localhost.', 'invoicing' ),
363
				'error'             => __( 'Something went wrong, please refresh and try again.', 'invoicing' ),
364
            ),
365
            array( 'wpi-addons' )
366
        );
367
368
    }
369
370
	/**
371
	 * Redirect users to settings on activation.
372
	 *
373
	 * @return void
374
	 */
375
	public function activation_redirect() {
376
377
		$redirected = get_option( 'wpinv_redirected_to_settings' );
378
379
		if ( ! empty( $redirected ) || wp_doing_ajax() || ! current_user_can( 'manage_options' ) ) {
380
			return;
381
		}
382
383
		// Bail if activating from network, or bulk
384
		if ( is_network_admin() || isset( $_GET['activate-multi'] ) ) {
385
			return;
386
		}
387
388
	    update_option( 'wpinv_redirected_to_settings', 1 );
389
390
        wp_safe_redirect( admin_url( 'index.php?page=gp-setup' ) );
391
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
392
393
	}
394
395
    /**
396
     * Fires an admin action after verifying that a user can fire them.
397
     */
398
    public function maybe_do_admin_action() {
399
400
        if ( wpinv_current_user_can_manage_invoicing() && isset( $_REQUEST['getpaid-admin-action'] ) && isset( $_REQUEST['getpaid-nonce'] ) && wp_verify_nonce( $_REQUEST['getpaid-nonce'], 'getpaid-nonce' ) ) {
401
            $key = sanitize_key( $_REQUEST['getpaid-admin-action'] );
402
            do_action( "getpaid_authenticated_admin_action_$key", $_REQUEST );
403
        }
404
405
    }
406
407
	/**
408
     * Duplicate invoice.
409
	 *
410
	 * @param array $args
411
     */
412
    public function duplicate_invoice( $args ) {
413
414
		if ( empty( $args['invoice_id'] ) ) {
415
			return;
416
		}
417
418
		$invoice = new WPInv_Invoice( (int) $args['invoice_id'] );
419
420
		if ( ! $invoice->exists() ) {
421
			return;
422
		}
423
424
		$new_invoice = getpaid_duplicate_invoice( $invoice );
425
		$new_invoice->save();
426
427
		if ( $new_invoice->exists() ) {
428
429
			getpaid_admin()->show_success( __( 'Invoice duplicated successfully.', 'newsletter-optin-box' ) );
430
431
			wp_safe_redirect(
432
				add_query_arg(
433
					array(
434
						'action' => 'edit',
435
						'post'   => $new_invoice->get_id(),
436
					),
437
					admin_url( 'post.php' )
438
				)
439
			);
440
			exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
441
442
		}
443
444
		getpaid_admin()->show_error( __( 'There was an error duplicating this invoice. Please try again.', 'newsletter-optin-box' ) );
445
446
	}
447
448
	/**
449
     * Sends a payment reminder to a customer.
450
	 *
451
	 * @param array $args
452
     */
453
    public function duplicate_payment_form( $args ) {
454
455
		if ( empty( $args['form_id'] ) ) {
456
			return;
457
		}
458
459
		$form = new GetPaid_Payment_Form( (int) $args['form_id'] );
460
461
		if ( ! $form->exists() ) {
462
			return;
463
		}
464
465
		$new_form = new GetPaid_Payment_Form();
466
		$new_form->set_author( $form->get_author( 'edit' ) );
467
		$new_form->set_name( $form->get_name( 'edit' ) . __( '(copy)', 'invoicing' ) );
468
		$new_form->set_elements( $form->get_elements( 'edit' ) );
469
		$new_form->set_items( $form->get_items( 'edit' ) );
470
		$new_form->save();
471
472
		if ( $new_form->exists() ) {
473
			$this->show_success( __( 'Form duplicated successfully', 'invoicing' ) );
474
			$url = get_edit_post_link( $new_form->get_id(), 'edit' );
475
		} else {
476
			$this->show_error( __( 'Unable to duplicate form', 'invoicing' ) );
477
			$url = remove_query_arg( array( 'getpaid-admin-action', 'form_id', 'getpaid-nonce' ) );
478
		}
479
480
		wp_redirect( $url );
481
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
482
	}
483
484
	/**
485
     * Sends a payment reminder to a customer.
486
	 *
487
	 * @param array $args
488
     */
489
    public function send_customer_invoice( $args ) {
490
		getpaid()->get( 'invoice_emails' )->user_invoice( new WPInv_Invoice( $args['invoice_id'] ), true );
491
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce', 'invoice_id' ) ) );
492
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
493
	}
494
495
	/**
496
     * Sends a payment reminder to a customer.
497
	 *
498
	 * @param array $args
499
     */
500
    public function send_customer_payment_reminder( $args ) {
501
		$sent = getpaid()->get( 'invoice_emails' )->force_send_overdue_notice( new WPInv_Invoice( $args['invoice_id'] ) );
502
503
		if ( $sent ) {
504
			$this->show_success( __( 'Payment reminder was successfully sent to the customer', 'invoicing' ) );
505
		} else {
506
			$this->show_error( __( 'Could not sent payment reminder to the customer', 'invoicing' ) );
507
		}
508
509
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce', 'invoice_id' ) ) );
510
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
511
	}
512
513
	/**
514
     * Resets tax rates.
515
	 *
516
     */
517
    public function admin_reset_tax_rates() {
518
519
		update_option( 'wpinv_tax_rates', wpinv_get_data( 'tax-rates' ) );
520
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
521
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
522
523
	}
524
525
	/**
526
     * Resets admin pages.
527
	 *
528
     */
529
    public function admin_create_missing_pages() {
530
		$installer = new GetPaid_Installer();
531
		$installer->create_pages();
532
		$this->show_success( __( 'GetPaid pages updated.', 'invoicing' ) );
533
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
534
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
535
	}
536
537
	/**
538
	 * Refreshes the permalinks.
539
	 */
540
	public function admin_refresh_permalinks() {
541
		flush_rewrite_rules();
542
		$this->show_success( __( 'Permalinks refreshed.', 'invoicing' ) );
543
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
544
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
545
	}
546
547
	/**
548
     * Creates an missing admin tables.
549
	 *
550
     */
551
    public function admin_create_missing_tables() {
552
		global $wpdb;
553
		$installer = new GetPaid_Installer();
554
555
		if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}wpinv_subscriptions'" ) != $wpdb->prefix . 'wpinv_subscriptions' ) {
556
			$installer->create_subscriptions_table();
557
558
			if ( $wpdb->last_error !== '' ) {
559
				$this->show_error( __( 'Your GetPaid tables have been updated:', 'invoicing' ) . ' ' . $wpdb->last_error );
560
			}
561
		}
562
563
		if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}getpaid_invoices'" ) != $wpdb->prefix . 'getpaid_invoices' ) {
564
			$installer->create_invoices_table();
565
566
			if ( '' !== $wpdb->last_error ) {
567
				$this->show_error( __( 'Your GetPaid tables have been updated:', 'invoicing' ) . ' ' . $wpdb->last_error );
568
			}
569
		}
570
571
		if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}getpaid_invoice_items'" ) != $wpdb->prefix . 'getpaid_invoice_items' ) {
572
			$installer->create_invoice_items_table();
573
574
			if ( '' !== $wpdb->last_error ) {
575
				$this->show_error( __( 'Your GetPaid tables have been updated:', 'invoicing' ) . ' ' . $wpdb->last_error );
576
			}
577
		}
578
579
		if ( ! $this->has_notices() ) {
580
			$this->show_success( __( 'Your GetPaid tables have been updated.', 'invoicing' ) );
581
		}
582
583
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
584
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
585
	}
586
587
	/**
588
     * Migrates old invoices to the new database tables.
589
	 *
590
     */
591
    public function admin_migrate_old_invoices() {
592
593
		// Migrate the invoices.
594
		$installer = new GetPaid_Installer();
595
		$installer->migrate_old_invoices();
596
597
		// Show an admin message.
598
		$this->show_success( __( 'Your invoices have been migrated.', 'invoicing' ) );
599
600
		// Redirect the admin.
601
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
602
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
603
604
	}
605
606
	/**
607
     * Download customers.
608
	 *
609
     */
610
    public function admin_download_customers() {
611
		global $wpdb;
612
613
		$output = fopen( 'php://output', 'w' );
614
615
		if ( false === $output ) {
616
			wp_die( esc_html__( 'Unsupported server', 'invoicing' ), 500 );
617
		}
618
619
		header( 'Content-Type:text/csv' );
620
		header( 'Content-Disposition:attachment;filename=customers.csv' );
621
622
		$post_types = '';
623
624
		foreach ( array_keys( getpaid_get_invoice_post_types() ) as $post_type ) {
625
			$post_types .= $wpdb->prepare( 'post_type=%s OR ', $post_type );
626
		}
627
628
		$post_types = rtrim( $post_types, ' OR' );
629
630
		$customers = $wpdb->get_col( "SELECT DISTINCT( post_author ) FROM $wpdb->posts WHERE $post_types" );
631
632
		$columns = array(
633
			'name'       => __( 'Name', 'invoicing' ),
634
			'email'      => __( 'Email', 'invoicing' ),
635
			'country'    => __( 'Country', 'invoicing' ),
636
			'state'      => __( 'State', 'invoicing' ),
637
			'city'       => __( 'City', 'invoicing' ),
638
			'zip'        => __( 'ZIP', 'invoicing' ),
639
			'address'    => __( 'Address', 'invoicing' ),
640
			'phone'      => __( 'Phone', 'invoicing' ),
641
			'company'    => __( 'Company', 'invoicing' ),
642
			'company_id' => __( 'Company ID', 'invoicing' ),
643
			'invoices'   => __( 'Invoices', 'invoicing' ),
644
			'total_raw'  => __( 'Total Spend', 'invoicing' ),
645
			'signup'     => __( 'Date created', 'invoicing' ),
646
		);
647
648
		// Output the csv column headers.
649
		fputcsv( $output, array_values( $columns ) );
650
651
		// Loop through
652
		$table = new WPInv_Customers_Table();
653
		foreach ( $customers as $customer_id ) {
654
655
			$user = get_user_by( 'id', $customer_id );
656
			$row  = array();
657
			if ( empty( $user ) ) {
658
				continue;
659
			}
660
661
			foreach ( array_keys( $columns ) as $column ) {
662
663
				$method = 'column_' . $column;
664
665
				if ( 'name' == $column ) {
666
					$value = esc_html( $user->display_name );
667
				} elseif ( 'email' == $column ) {
668
					$value = sanitize_email( $user->user_email );
669
				} elseif ( is_callable( array( $table, $method ) ) ) {
670
					$value = wp_strip_all_tags( $table->$method( $user ) );
671
				}
672
673
				if ( empty( $value ) ) {
674
					$value = esc_html( get_user_meta( $user->ID, '_wpinv_' . $column, true ) );
0 ignored issues
show
Bug introduced by
It seems like get_user_meta($user->ID,...pinv_' . $column, true) can also be of type false; however, parameter $text of esc_html() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

674
					$value = esc_html( /** @scrutinizer ignore-type */ get_user_meta( $user->ID, '_wpinv_' . $column, true ) );
Loading history...
675
				}
676
677
				$row[] = $value;
678
679
			}
680
681
			fputcsv( $output, $row );
682
		}
683
684
		fclose( $output );
685
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
686
687
	}
688
689
	/**
690
     * Installs a plugin.
691
	 *
692
	 * @param array $data
693
     */
694
    public function admin_install_plugin( $data ) {
695
696
		if ( ! empty( $data['plugins'] ) ) {
697
			include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
698
			wp_cache_flush();
699
700
			foreach ( $data['plugins'] as $slug => $file ) {
701
				$plugin_zip = esc_url( 'https://downloads.wordpress.org/plugin/' . $slug . '.latest-stable.zip' );
702
				$upgrader   = new Plugin_Upgrader( new Automatic_Upgrader_Skin() );
703
				$installed  = $upgrader->install( $plugin_zip );
704
705
				if ( ! is_wp_error( $installed ) && $installed ) {
706
					activate_plugin( $file, '', false, true );
707
				} else {
708
					wpinv_error_log( $upgrader->skin->get_upgrade_messages(), false );
0 ignored issues
show
Bug introduced by
The method get_upgrade_messages() does not exist on WP_Upgrader_Skin. It seems like you code against a sub-type of WP_Upgrader_Skin such as Automatic_Upgrader_Skin. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

708
					wpinv_error_log( $upgrader->skin->/** @scrutinizer ignore-call */ get_upgrade_messages(), false );
Loading history...
Bug introduced by
$upgrader->skin->get_upgrade_messages() of type string[] is incompatible with the type string expected by parameter $log of wpinv_error_log(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

708
					wpinv_error_log( /** @scrutinizer ignore-type */ $upgrader->skin->get_upgrade_messages(), false );
Loading history...
709
				}
710
}
711
}
712
713
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( $data['redirect'] ) : admin_url( 'plugins.php' );
714
		wp_safe_redirect( $redirect );
715
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
716
717
	}
718
719
	/**
720
     * Connects a gateway.
721
	 *
722
	 * @param array $data
723
     */
724
    public function admin_connect_gateway( $data ) {
725
726
		if ( ! empty( $data['plugin'] ) ) {
727
728
			$gateway     = sanitize_key( $data['plugin'] );
729
			$connect_url = apply_filters( "getpaid_get_{$gateway}_connect_url", false, $data );
730
731
			if ( ! empty( $connect_url ) ) {
732
				wp_redirect( $connect_url );
733
				exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
734
			}
735
736
			if ( 'stripe' == $data['plugin'] ) {
737
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
738
				include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
739
				wp_cache_flush();
740
741
				if ( ! array_key_exists( 'getpaid-stripe-payments/getpaid-stripe-payments.php', get_plugins() ) ) {
742
					$plugin_zip = esc_url( 'https://downloads.wordpress.org/plugin/getpaid-stripe-payments.latest-stable.zip' );
743
					$upgrader   = new Plugin_Upgrader( new Automatic_Upgrader_Skin() );
744
					$upgrader->install( $plugin_zip );
745
				}
746
747
				activate_plugin( 'getpaid-stripe-payments/getpaid-stripe-payments.php', '', false, true );
748
			}
749
750
			$connect_url = apply_filters( "getpaid_get_{$gateway}_connect_url", false, $data );
751
			if ( ! empty( $connect_url ) ) {
752
				wp_redirect( $connect_url );
753
				exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
754
			}
755
}
756
757
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( urldecode( $data['redirect'] ) ) : admin_url( 'admin.php?page=wpinv-settings&tab=gateways' );
758
		wp_safe_redirect( $redirect );
759
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
760
761
	}
762
763
	/**
764
     * Recalculates discounts.
765
	 *
766
     */
767
    public function admin_recalculate_discounts() {
768
		global $wpdb;
769
770
		// Fetch all invoices that have discount codes.
771
		$table    = $wpdb->prefix . 'getpaid_invoices';
772
		$invoices = $wpdb->get_col( "SELECT `post_id` FROM `$table` WHERE `discount` = 0 && `discount_code` <> ''" );
773
774
		foreach ( $invoices as $invoice ) {
775
776
			$invoice = new WPInv_Invoice( $invoice );
777
778
			if ( ! $invoice->exists() ) {
779
				continue;
780
			}
781
782
			// Abort if the discount does not exist or does not apply here.
783
			$discount = new WPInv_Discount( $invoice->get_discount_code() );
784
			if ( ! $discount->exists() ) {
785
				continue;
786
			}
787
788
			$invoice->add_discount( getpaid_calculate_invoice_discount( $invoice, $discount ) );
789
			$invoice->recalculate_total();
790
791
			if ( $invoice->get_total_discount() > 0 ) {
792
				$invoice->save();
793
			}
794
}
795
796
		// Show an admin message.
797
		$this->show_success( __( 'Discounts have been recalculated.', 'invoicing' ) );
798
799
		// Redirect the admin.
800
		wp_safe_redirect( remove_query_arg( array( 'getpaid-admin-action', 'getpaid-nonce' ) ) );
801
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
802
803
	}
804
805
    /**
806
	 * Returns an array of admin notices.
807
	 *
808
	 * @since       1.0.19
809
     * @return array
810
	 */
811
	public function get_notices() {
812
		$notices = get_option( 'wpinv_admin_notices' );
813
        return is_array( $notices ) ? $notices : array();
814
	}
815
816
	/**
817
	 * Checks if we have any admin notices.
818
	 *
819
	 * @since       2.0.4
820
     * @return array
821
	 */
822
	public function has_notices() {
823
		return count( $this->get_notices() ) > 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return count($this->get_notices()) > 0 returns the type boolean which is incompatible with the documented return type array.
Loading history...
824
	}
825
826
	/**
827
	 * Clears all admin notices
828
	 *
829
	 * @access      public
830
	 * @since       1.0.19
831
	 */
832
	public function clear_notices() {
833
		delete_option( 'wpinv_admin_notices' );
834
	}
835
836
	/**
837
	 * Saves a new admin notice
838
	 *
839
	 * @access      public
840
	 * @since       1.0.19
841
	 */
842
	public function save_notice( $type, $message ) {
843
		$notices = $this->get_notices();
844
845
		if ( empty( $notices[ $type ] ) || ! is_array( $notices[ $type ] ) ) {
846
			$notices[ $type ] = array();
847
		}
848
849
		$notices[ $type ][] = $message;
850
851
		update_option( 'wpinv_admin_notices', $notices );
852
	}
853
854
	/**
855
	 * Displays a success notice
856
	 *
857
	 * @param       string $msg The message to qeue.
858
	 * @access      public
859
	 * @since       1.0.19
860
	 */
861
	public function show_success( $msg ) {
862
		$this->save_notice( 'success', $msg );
863
	}
864
865
	/**
866
	 * Displays a error notice
867
	 *
868
	 * @access      public
869
	 * @param       string $msg The message to qeue.
870
	 * @since       1.0.19
871
	 */
872
	public function show_error( $msg ) {
873
		$this->save_notice( 'error', $msg );
874
	}
875
876
	/**
877
	 * Displays a warning notice
878
	 *
879
	 * @access      public
880
	 * @param       string $msg The message to qeue.
881
	 * @since       1.0.19
882
	 */
883
	public function show_warning( $msg ) {
884
		$this->save_notice( 'warning', $msg );
885
	}
886
887
	/**
888
	 * Displays a info notice
889
	 *
890
	 * @access      public
891
	 * @param       string $msg The message to qeue.
892
	 * @since       1.0.19
893
	 */
894
	public function show_info( $msg ) {
895
		$this->save_notice( 'info', $msg );
896
	}
897
898
	/**
899
	 * Show notices
900
	 *
901
	 * @access      public
902
	 * @since       1.0.19
903
	 */
904
	public function show_notices() {
905
906
        $notices = $this->get_notices();
907
        $this->clear_notices();
908
909
		foreach ( $notices as $type => $messages ) {
910
911
			if ( ! is_array( $messages ) ) {
912
				continue;
913
			}
914
915
            $type  = esc_attr( $type );
916
			foreach ( $messages as $message ) {
917
				echo wp_kses_post( "<div class='notice notice-$type is-dismissible'><p>$message</p></div>" );
918
            }
919
}
920
921
		foreach ( array( 'checkout_page', 'invoice_history_page', 'success_page', 'failure_page', 'invoice_subscription_page' ) as $page ) {
922
923
			if ( ! is_numeric( wpinv_get_option( $page, false ) ) ) {
924
				$url     = wp_nonce_url(
925
					add_query_arg( 'getpaid-admin-action', 'create_missing_pages' ),
926
					'getpaid-nonce',
927
					'getpaid-nonce'
928
				);
929
				$message  = __( 'Some GetPaid pages are missing. To use GetPaid without any issues, click the button below to generate the missing pages.', 'invoicing' );
930
				$message2 = __( 'Generate Pages', 'invoicing' );
931
				echo wp_kses_post( "<div class='notice notice-warning is-dismissible'><p>$message<br><br><a href='$url' class='button button-primary'>$message2</a></p></div>" );
932
				break;
933
			}
934
}
935
936
	}
937
938
}
939