Passed
Pull Request — master (#404)
by Jonathan
08:25 queued 03:56
created

Object_Sync_Sf_Admin::notices()   C

Complexity

Conditions 11
Paths 137

Size

Total Lines 83
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 11
eloc 59
c 3
b 1
f 0
nc 137
nop 0
dl 0
loc 83
rs 6.5012

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Create default WordPress admin functionality to configure the plugin.
4
 *
5
 * @class   Object_Sync_Sf_Admin
6
 * @package Object_Sync_Salesforce
7
 */
8
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * Object_Sync_Sf_Admin class.
13
 */
14
class Object_Sync_Sf_Admin {
15
16
	/**
17
	 * Current version of the plugin
18
	 *
19
	 * @var string
20
	 */
21
	public $version;
22
23
	/**
24
	 * The main plugin file
25
	 *
26
	 * @var string
27
	 */
28
	public $file;
29
30
	/**
31
	 * Global object of `$wpdb`, the WordPress database
32
	 *
33
	 * @var object
34
	 */
35
	public $wpdb;
36
37
	/**
38
	 * The plugin's slug so we can include it when necessary
39
	 *
40
	 * @var string
41
	 */
42
	public $slug;
43
44
	/**
45
	 * The plugin's prefix when saving options to the database
46
	 *
47
	 * @var string
48
	 */
49
	public $option_prefix;
50
51
	/**
52
	 * Suffix for group name in ActionScheduler
53
	 *
54
	 * @var string
55
	 */
56
	public $action_group_suffix;
57
58
	/**
59
	 * Login credentials for the Salesforce API; comes from wp-config or from the plugin settings
60
	 *
61
	 * @var array
62
	 */
63
	public $login_credentials;
64
65
	/**
66
	 * Array of what classes in the plugin can be scheduled to occur with `wp_cron` events
67
	 *
68
	 * @var array
69
	 */
70
	public $schedulable_classes;
71
72
	/**
73
	 * Object_Sync_Sf_Queue class
74
	 *
75
	 * @var object
76
	 */
77
	public $queue;
78
79
	/**
80
	 * Object_Sync_Sf_Logging class
81
	 *
82
	 * @var object
83
	 */
84
	public $logging;
85
86
	/**
87
	 * Object_Sync_Sf_Mapping class
88
	 *
89
	 * @var object
90
	 */
91
	public $mappings;
92
93
	/**
94
	 * Object_Sync_Sf_WordPress class
95
	 *
96
	 * @var object
97
	 */
98
	public $wordpress;
99
100
	/**
101
	 * Object_Sync_Sf_Salesforce class
102
	 * This contains Salesforce API methods
103
	 *
104
	 * @var array
105
	 */
106
	public $salesforce;
107
108
	/**
109
	 * Object_Sync_Sf_Salesforce_Push class
110
	 *
111
	 * @var object
112
	 */
113
	public $push;
114
115
	/**
116
	 * Object_Sync_Sf_Salesforce_Pull class
117
	 *
118
	 * @var object
119
	 */
120
	public $pull;
121
122
	/**
123
	 * Object_Sync_Sf_WordPress_Transient class
124
	 *
125
	 * @var object
126
	 */
127
	private $sfwp_transients;
128
129
	/**
130
	 * URL fragment for the plugin's settings page
131
	 *
132
	 * @var string
133
	 */
134
	private $admin_settings_url_param;
135
136
	/**
137
	 * Salesforce access token
138
	 *
139
	 * @var string
140
	 */
141
	private $access_token;
142
143
	/**
144
	 * Salesforce instance URL
145
	 *
146
	 * @var string
147
	 */
148
	private $instance_url;
149
150
	/**
151
	 * Salesforce refresh token
152
	 *
153
	 * @var string
154
	 */
155
	private $refresh_token;
156
157
	/**
158
	 * Default path for the Salesforce authorize URL
159
	 *
160
	 * @var string
161
	 */
162
	public $default_authorize_url_path;
163
164
	/**
165
	 * Default path for the Salesforce token URL
166
	 *
167
	 * @var string
168
	 */
169
	public $default_token_url_path;
170
171
	/**
172
	 * What version of the Salesforce API should be the default on the settings screen.
173
	 * Users can edit what version is used, but they won't see a correct list of all their available versions until WordPress has
174
	 * been authenticated with Salesforce.
175
	 *
176
	 * @var string
177
	 */
178
	public $default_api_version;
179
180
	/**
181
	 * Default max number of pull records. Users can edit this.
182
	 *
183
	 * @var int
184
	 */
185
	public $default_pull_limit;
186
187
	/**
188
	 * Default throttle for how often to pull from Salesforce. Users can edit this.
189
	 *
190
	 * @var int
191
	 */
192
	public $default_pull_throttle;
193
194
	/**
195
	 * Default for whether to limit to triggerable items. Users can edit this.
196
	 *
197
	 * @var bool
198
	 */
199
	public $default_triggerable;
200
201
	/**
202
	 * Default for whether to limit to items that can be updated. Users can edit this.
203
	 *
204
	 * @var bool
205
	 */
206
	public $default_updateable;
207
208
	/**
209
	 * Constructor for admin class
210
	 */
211
	public function __construct() {
212
		$this->version             = object_sync_for_salesforce()->version;
213
		$this->file                = object_sync_for_salesforce()->file;
214
		$this->wpdb                = object_sync_for_salesforce()->wpdb;
215
		$this->slug                = object_sync_for_salesforce()->slug;
216
		$this->option_prefix       = object_sync_for_salesforce()->option_prefix;
217
		$this->action_group_suffix = object_sync_for_salesforce()->action_group_suffix;
218
219
		$this->login_credentials   = object_sync_for_salesforce()->login_credentials;
220
		$this->wordpress           = object_sync_for_salesforce()->wordpress;
221
		$this->salesforce          = object_sync_for_salesforce()->salesforce;
222
		$this->mappings            = object_sync_for_salesforce()->mappings;
223
		$this->push                = object_sync_for_salesforce()->push;
224
		$this->pull                = object_sync_for_salesforce()->pull;
225
		$this->logging             = object_sync_for_salesforce()->logging;
226
		$this->schedulable_classes = object_sync_for_salesforce()->schedulable_classes;
227
		$this->queue               = object_sync_for_salesforce()->queue;
228
229
		$this->sfwp_transients          = object_sync_for_salesforce()->wordpress->sfwp_transients;
230
		$this->admin_settings_url_param = 'object-sync-salesforce-admin';
231
232
		// default authorize url path.
233
		$this->default_authorize_url_path = '/services/oauth2/authorize';
234
		// default token url path.
235
		$this->default_token_url_path = '/services/oauth2/token';
236
		// what Salesforce API version to start the settings with. This is only used in the settings form.
237
		$this->default_api_version = defined( 'OBJECT_SYNC_SF_DEFAULT_API_VERSION' ) ? OBJECT_SYNC_SF_DEFAULT_API_VERSION : '52.0';
238
		// default pull record limit.
239
		$this->default_pull_limit = 25;
240
		// default pull throttle for avoiding going over api limits.
241
		$this->default_pull_throttle = 5;
242
		// default setting for triggerable items.
243
		$this->default_triggerable = true;
244
		// default setting for updateable items.
245
		$this->default_updateable = true;
246
247
		$this->add_actions();
248
	}
249
250
	/**
251
	 * Create the action hooks to create the admin pages.
252
	 */
253
	public function add_actions() {
254
255
		// settings link.
256
		add_filter( 'plugin_action_links', array( $this, 'plugin_action_links' ), 10, 5 );
257
258
		// CSS and Javascript.
259
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts_and_styles' ) );
260
261
		// Settings API forms and notices.
262
		add_action( 'admin_menu', array( $this, 'create_admin_menu' ) );
263
		add_action( 'admin_init', array( $this, 'salesforce_settings_forms' ) );
264
		add_action( 'admin_init', array( $this, 'notices' ) );
265
		add_action( 'admin_post_post_fieldmap', array( $this, 'prepare_fieldmap_data' ) );
266
		add_action( 'admin_post_delete_fieldmap', array( $this, 'delete_fieldmap' ) );
267
268
		// Ajax for fieldmap forms.
269
		add_action( 'wp_ajax_get_salesforce_object_description', array( $this, 'get_salesforce_object_description' ), 10, 1 );
270
		add_action( 'wp_ajax_get_salesforce_object_fields', array( $this, 'get_salesforce_object_fields' ), 10, 1 );
271
		add_action( 'wp_ajax_get_wordpress_object_fields', array( $this, 'get_wordpress_object_fields' ), 10, 1 );
272
273
		// Ajax events that can be manually called.
274
		add_action( 'wp_ajax_push_to_salesforce', array( $this, 'push_to_salesforce' ), 10, 3 );
275
		add_action( 'wp_ajax_pull_from_salesforce', array( $this, 'pull_from_salesforce' ), 10, 2 );
276
		add_action( 'wp_ajax_refresh_mapped_data', array( $this, 'refresh_mapped_data' ), 10, 1 );
277
		add_action( 'wp_ajax_clear_sfwp_cache', array( $this, 'clear_sfwp_cache' ) );
278
279
		// we add a Salesforce box on user profiles.
280
		add_action( 'edit_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
281
		add_action( 'show_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
282
283
		// and we can update Salesforce fields on the user profile box.
284
		add_action( 'personal_options_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
285
		add_action( 'edit_user_profile_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
286
287
		// when either field for schedule settings changes.
288
		foreach ( $this->schedulable_classes as $key => $value ) {
289
			// if the user doesn't have any action schedule tasks, let's not leave them empty.
290
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'initial_action_schedule' ), 10, 3 );
291
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'initial_action_schedule' ), 10, 3 );
292
293
			// this is if the user is changing their tasks.
294
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'change_action_schedule' ), 10, 3 );
295
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'change_action_schedule' ), 10, 3 );
296
		}
297
298
		// handle post requests for object maps.
299
		add_action( 'admin_post_delete_object_map', array( $this, 'delete_object_map' ) );
300
		add_action( 'admin_post_post_object_map', array( $this, 'prepare_object_map_data' ) );
301
302
		// import and export plugin data.
303
		add_action( 'admin_post_object_sync_for_salesforce_import', array( $this, 'import_json_file' ) );
304
		add_action( 'admin_post_object_sync_for_salesforce_export', array( $this, 'export_json_file' ) );
305
306
	}
307
308
	/**
309
	 * Display a Settings link on the main Plugins page
310
	 *
311
	 * @param array  $links the array of links for the main plugins page.
312
	 * @param string $file the filename.
313
	 * @return array $links the array of links for the main plugins page
314
	 */
315
	public function plugin_action_links( $links, $file ) {
316
		if ( plugin_basename( $this->file ) === $file ) {
317
			$settings = '<a href="' . get_admin_url() . 'options-general.php?page=' . $this->admin_settings_url_param . '">' . __( 'Settings', 'object-sync-for-salesforce' ) . '</a>';
318
			array_unshift( $links, $settings );
319
		}
320
		return $links;
321
	}
322
323
	/**
324
	 * Admin styles. Load the CSS and JavaScript for the plugin's settings
325
	 */
326
	public function admin_scripts_and_styles() {
327
328
		// Developers might not want to bother with select2 or selectwoo, so we allow that to be changeable.
329
		$select_library = apply_filters( $this->option_prefix . 'select_library', 'selectwoo' );
330
331
		/*
332
		 * example to modify the select library
333
		 * add_filter( 'object_sync_for_salesforce_select_library', 'select_library', 10, 1 );
334
		 * function select_library( $select_library ) {
335
		 * 	$select_library = 'select2';
336
		 *  // this could also be empty; in that case we would just use default browser select
337
		 * 	return $select_library;
338
		 * }
339
		*/
340
341
		$javascript_dependencies = array( 'jquery' );
342
		$css_dependencies        = array();
343
		if ( '' !== $select_library ) {
344
			wp_enqueue_script( $select_library . 'js', plugins_url( 'assets/js/vendor/' . $select_library . '.min.js', $this->file ), array( 'jquery' ), filemtime( plugin_dir_path( $this->file ) . 'assets/js/vendor/' . $select_library . '.min.js' ), true );
345
			$javascript_dependencies[] = $select_library . 'js';
346
			wp_enqueue_style( $select_library . 'css', plugins_url( 'assets/css/vendor/' . $select_library . '.min.css', $this->file ), array(), filemtime( plugin_dir_path( $this->file ) . 'assets/css/vendor/' . $select_library . '.min.css' ), 'all' );
347
			$css_dependencies[] = $select_library . 'css';
348
		}
349
350
		wp_enqueue_script( $this->slug . '-admin', plugins_url( 'assets/js/object-sync-for-salesforce-admin.min.js', $this->file ), $javascript_dependencies, filemtime( plugin_dir_path( $this->file ) . 'assets/js/object-sync-for-salesforce-admin.min.js' ), true );
351
		wp_enqueue_style( $this->slug . '-admin', plugins_url( 'assets/css/object-sync-for-salesforce-admin.css', $this->file ), $css_dependencies, filemtime( plugin_dir_path( $this->file ) . 'assets/css/object-sync-for-salesforce-admin.css' ), 'all' );
352
	}
353
354
	/**
355
	 * Initial recurring tasks for ActionScheduler
356
	 *
357
	 * @param string $new_schedule the new, unserialized option value.
358
	 * @param string $old_schedule the old option value.
359
	 * @param string $option_name option name.
360
	 * @return string $new_schedule
361
	 */
362
	public function initial_action_schedule( $new_schedule, $old_schedule, $option_name ) {
363
364
		// get the current schedule name from the task, based on pattern in the foreach.
365
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
366
		$schedule_name     = $matches[1];
367
		$action_group_name = $schedule_name . $this->action_group_suffix;
368
369
		// make sure there are no tasks already.
370
		$current_tasks = as_get_scheduled_actions(
371
			array(
372
				'hook'  => $this->schedulable_classes[ $schedule_name ]['initializer'],
373
				'group' => $action_group_name,
374
			),
375
			ARRAY_A
376
		);
377
378
		// exit if there are already tasks; they'll be saved if the option data changed.
379
		if ( ! empty( $current_tasks ) ) {
380
			return $new_schedule;
381
		}
382
383
		$this->set_action_schedule( $schedule_name, $action_group_name );
384
385
		return $new_schedule;
386
387
	}
388
389
	/**
390
	 * Update recurring tasks for ActionScheduler if options change
391
	 *
392
	 * @param string $old_schedule the old option value.
393
	 * @param string $new_schedule the new, unserialized option value.
394
	 * @param string $option_name option name.
395
	 */
396
	public function change_action_schedule( $old_schedule, $new_schedule, $option_name ) {
397
398
		// this method does not run if the option's data is unchanged.
399
400
		// get the current schedule name from the task, based on pattern in the foreach.
401
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
402
		$schedule_name     = $matches[1];
403
		$action_group_name = $schedule_name . $this->action_group_suffix;
404
405
		$this->set_action_schedule( $schedule_name, $action_group_name );
406
407
	}
408
409
	/**
410
	 * Set up recurring tasks for ActionScheduler
411
	 *
412
	 * @param string $schedule_name the name of the schedule.
413
	 * @param string $action_group_name the group's name.
414
	 */
415
	private function set_action_schedule( $schedule_name, $action_group_name ) {
416
		// exit if there is no initializer property on this schedule.
417
		if ( ! isset( $this->schedulable_classes[ $schedule_name ]['initializer'] ) ) {
418
			return;
419
		}
420
421
		// cancel previous task.
422
		$this->queue->cancel(
423
			$this->schedulable_classes[ $schedule_name ]['initializer'],
424
			array(),
425
			$action_group_name
426
		);
427
428
		// create new recurring task for ActionScheduler to check for data to pull from Salesforce.
429
		$this->queue->schedule_recurring(
430
			time(), // plugin seems to expect UTC.
431
			$this->queue->get_frequency( $schedule_name, 'seconds' ),
432
			$this->schedulable_classes[ $schedule_name ]['initializer'],
433
			array(),
434
			$action_group_name
435
		);
436
	}
437
438
	/**
439
	 * Create the WordPress admin options page
440
	 */
441
	public function create_admin_menu() {
442
		$title = __( 'Salesforce', 'object-sync-for-salesforce' );
443
		add_options_page( $title, $title, 'configure_salesforce', $this->admin_settings_url_param, array( $this, 'show_admin_page' ) );
444
	}
445
446
	/**
447
	 * Render the admin pages in WordPress. This also allows other plugins to add tabs to this plugin's settings screen
448
	 */
449
	public function show_admin_page() {
450
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
451
		echo '<div class="wrap">';
452
		echo '<h1>' . esc_html( get_admin_page_title() ) . '</h1>';
453
		$allowed = $this->check_wordpress_admin_permissions();
454
		if ( false === $allowed ) {
455
			return;
456
		}
457
		$tabs = array(
458
			'settings'      => __( 'Settings', 'object-sync-for-salesforce' ),
459
			'authorize'     => __( 'Authorize', 'object-sync-for-salesforce' ),
460
			'fieldmaps'     => __( 'Fieldmaps', 'object-sync-for-salesforce' ),
461
			'schedule'      => __( 'Scheduling', 'object-sync-for-salesforce' ),
462
			'import-export' => __( 'Import &amp; Export', 'object-sync-for-salesforce' ),
463
		); // this creates the tabs for the admin.
464
465
		// optionally make tab(s) for logging and log settings.
466
		$logging_enabled      = get_option( $this->option_prefix . 'enable_logging', false );
467
		$tabs['log_settings'] = __( 'Log Settings', 'object-sync-for-salesforce' );
468
469
		$mapping_errors       = $this->mappings->get_failed_object_maps();
470
		$mapping_errors_total = isset( $mapping_errors['total'] ) ? $mapping_errors['total'] : 0;
471
		if ( 0 < $mapping_errors_total ) {
472
			$tabs['mapping_errors'] = __( 'Mapping Errors', 'object-sync-for-salesforce' );
473
		}
474
475
		// filter for extending the tabs available on the page
476
		// currently it will go into the default switch case for $tab.
477
		$tabs = apply_filters( $this->option_prefix . 'settings_tabs', $tabs );
478
479
		$tab = isset( $get_data['tab'] ) ? sanitize_key( $get_data['tab'] ) : 'settings';
480
		$this->tabs( $tabs, $tab );
481
482
		$consumer_key    = $this->login_credentials['consumer_key'];
483
		$consumer_secret = $this->login_credentials['consumer_secret'];
484
		$callback_url    = $this->login_credentials['callback_url'];
485
486
		if ( true !== $this->salesforce['is_authorized'] ) {
487
			$url     = esc_url( $callback_url );
488
			$anchor  = esc_html__( 'Authorize tab', 'object-sync-for-salesforce' );
489
			$message = sprintf( 'Salesforce needs to be authorized to connect to this website. Use the <a href="%s">%s</a> to connect.', $url, $anchor );
490
			require plugin_dir_path( $this->file ) . '/templates/admin/error.php';
491
		}
492
493
		if ( 0 === count( $this->mappings->get_fieldmaps() ) ) {
494
			$url     = esc_url( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps' ) );
495
			$anchor  = esc_html__( 'Fieldmaps tab', 'object-sync-for-salesforce' );
496
			$message = sprintf( 'No fieldmaps exist yet. Use the <a href="%s">%s</a> to map WordPress and Salesforce objects to each other.', $url, $anchor );
497
			require plugin_dir_path( $this->file ) . '/templates/admin/error.php';
498
		}
499
500
		try {
501
			switch ( $tab ) {
502
				case 'authorize':
503
					if ( isset( $get_data['code'] ) ) {
504
						// this string is an oauth token.
505
						$data          = esc_html( wp_unslash( $get_data['code'] ) );
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($get_data['code']) can also be of type array; 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

505
						$data          = esc_html( /** @scrutinizer ignore-type */ wp_unslash( $get_data['code'] ) );
Loading history...
506
						$is_authorized = $this->salesforce['sfapi']->request_token( $data );
507
						?>
508
						<script>window.location = '<?php echo esc_url_raw( $callback_url ); ?>'</script>
509
						<?php
510
					} elseif ( true === $this->salesforce['is_authorized'] ) {
511
							require_once plugin_dir_path( $this->file ) . '/templates/admin/authorized.php';
512
							$this->status( $this->salesforce['sfapi'] );
513
					} elseif ( true === is_object( $this->salesforce['sfapi'] ) && isset( $consumer_key ) && isset( $consumer_secret ) ) {
514
						?>
515
						<p><a class="button button-primary" href="<?php echo esc_url( $this->salesforce['sfapi']->get_authorization_code() ); ?>"><?php echo esc_html__( 'Connect to Salesforce', 'object-sync-for-salesforce' ); ?></a></p>
516
						<?php
517
					} else {
518
						$url    = esc_url( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=settings' ) );
519
						$anchor = esc_html__( 'Settings', 'object-sync-for-salesforce' );
520
						// translators: placeholders are for the settings tab link: 1) the url, and 2) the anchor text.
521
						$message = sprintf( esc_html__( 'Salesforce needs to be authorized to connect to this website but the credentials are missing. Use the <a href="%1$s">%2$s</a> tab to add them.', 'object-sync-for-salesforce' ), $url, $anchor );
522
						require_once plugin_dir_path( $this->file ) . '/templates/admin/error.php';
523
					}
524
					break;
525
				case 'fieldmaps':
526
					if ( isset( $get_data['method'] ) ) {
527
528
						$method      = sanitize_key( $get_data['method'] );
529
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps&method=' . $method );
530
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps' );
531
532
						$disable_mapped_fields = get_option( $this->option_prefix . 'disable_mapped_fields', false );
533
						$disable_mapped_fields = filter_var( $disable_mapped_fields, FILTER_VALIDATE_BOOLEAN );
534
						$fieldmap_class        = 'fieldmap';
535
						if ( true === $disable_mapped_fields ) {
536
							$fieldmap_class .= ' fieldmap-disable-mapped-fields';
537
						}
538
539
						if ( isset( $get_data['transient'] ) ) {
540
							$transient = sanitize_key( $get_data['transient'] );
541
							$posted    = $this->sfwp_transients->get( $transient );
542
						}
543
544
						if ( isset( $posted ) && is_array( $posted ) ) {
545
							$map = $posted;
546
						} elseif ( 'edit' === $method || 'clone' === $method || 'delete' === $method ) {
547
							$map = $this->mappings->get_fieldmaps( isset( $get_data['id'] ) ? sanitize_key( $get_data['id'] ) : '' );
548
						}
549
550
						if ( isset( $map ) && is_array( $map ) && isset( $map['id'] ) ) {
551
							$label                           = $map['label'];
552
							$salesforce_object               = $map['salesforce_object'];
553
							$salesforce_record_types_allowed = maybe_unserialize( $map['salesforce_record_types_allowed'] );
554
							$salesforce_record_type_default  = $map['salesforce_record_type_default'];
555
							$wordpress_object                = $map['wordpress_object'];
556
							$pull_trigger_field              = $map['pull_trigger_field'];
557
							$fieldmap_fields                 = $map['fields'];
558
							$sync_triggers                   = $map['sync_triggers'];
559
							$push_async                      = $map['push_async'];
560
							$push_drafts                     = $map['push_drafts'];
561
							$pull_to_drafts                  = $map['pull_to_drafts'];
562
							$weight                          = $map['weight'];
563
							if ( 'add' === $method || 'edit' === $method || 'clone' === $method ) {
564
								require_once plugin_dir_path( $this->file ) . '/templates/admin/fieldmaps-add-edit-clone.php';
565
							} elseif ( 'delete' === $method ) {
566
								require_once plugin_dir_path( $this->file ) . '/templates/admin/fieldmaps-delete.php';
567
							}
568
						} else {
569
							$no_fieldmap_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps&missing_fieldmap=true' );
570
							wp_safe_redirect( $no_fieldmap_url );
571
							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...
572
						}
573
					} else {
574
						$fieldmaps = $this->mappings->get_fieldmaps();
575
						require_once plugin_dir_path( $this->file ) . '/templates/admin/fieldmaps-list.php';
576
					} // End if statement.
577
					break;
578
				case 'logout':
579
					$this->logout();
580
					break;
581
				case 'clear_cache':
582
					$this->clear_cache();
583
					break;
584
				case 'clear_schedule':
585
					if ( isset( $get_data['schedule_name'] ) ) {
586
						$schedule_name = sanitize_key( $get_data['schedule_name'] );
587
					}
588
					$this->clear_schedule( $schedule_name );
589
					break;
590
				case 'settings':
591
					require_once plugin_dir_path( $this->file ) . '/templates/admin/settings.php';
592
					break;
593
				case 'mapping_errors':
594
					if ( isset( $get_data['method'] ) ) {
595
596
						$method      = sanitize_key( $get_data['method'] );
597
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors&method=' . $method );
598
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors' );
599
600
						if ( isset( $get_data['map_transient'] ) ) {
601
							$transient = sanitize_key( $get_data['map_transient'] );
602
							$posted    = $this->sfwp_transients->get( $transient );
603
						}
604
605
						if ( isset( $posted ) && is_array( $posted ) ) {
606
							$map_row = $posted;
607
						} elseif ( 'edit' === $method || 'delete' === $method ) {
608
							$map_row = $this->mappings->get_failed_object_map( isset( $get_data['id'] ) ? sanitize_key( $get_data['id'] ) : '' );
609
						}
610
611
						if ( isset( $map_row ) && is_array( $map_row ) ) {
612
							$salesforce_id = $map_row['salesforce_id'];
613
							$wordpress_id  = $map_row['wordpress_id'];
614
						}
615
616
						if ( 'edit' === $method ) {
617
							require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors-edit.php';
618
						} elseif ( 'delete' === $method ) {
619
							require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors-delete.php';
620
						}
621
					} else {
622
623
						if ( isset( $get_data['mapping_error_transient'] ) ) {
624
							$transient = sanitize_key( $get_data['mapping_error_transient'] );
625
							$posted    = $this->sfwp_transients->get( $transient );
626
						}
627
628
						$ids_string = '';
629
						$ids        = array();
630
						if ( isset( $posted['delete'] ) ) {
631
							$ids_string = maybe_serialize( $posted['delete'] );
632
							$ids        = $posted['delete'];
633
						}
634
635
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors&ids=' . $ids_string );
636
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors' );
637
						require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors.php';
638
					}
639
					break;
640
				case 'import-export':
641
					require_once plugin_dir_path( $this->file ) . '/templates/admin/import-export.php';
642
					break;
643
				default:
644
					$include_settings = apply_filters( $this->option_prefix . 'settings_tab_include_settings', true, $tab );
645
					$content_before   = apply_filters( $this->option_prefix . 'settings_tab_content_before', null, $tab );
646
					$content_after    = apply_filters( $this->option_prefix . 'settings_tab_content_after', null, $tab );
647
					if ( null !== $content_before ) {
648
						echo esc_html( $content_before );
649
					}
650
					if ( true === $include_settings ) {
651
						require_once plugin_dir_path( $this->file ) . '/templates/admin/settings.php';
652
					}
653
					if ( null !== $content_after ) {
654
						echo esc_html( $content_after );
655
					}
656
					break;
657
			} // End switch statement.
658
		} catch ( Object_Sync_Sf_Exception $ex ) {
659
			echo sprintf(
660
				'<p>Error <strong>%1$s</strong>: %2$s</p>',
661
				absint( $ex->getCode() ),
662
				esc_html( $ex->getMessage() )
663
			);
664
		} // End try for menu/page setup.
665
		echo '</div>';
666
	}
667
668
	/**
669
	 * Create default WordPress admin settings form. This runs the Settings page.
670
	 */
671
	public function salesforce_settings_forms() {
672
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
673
		$page     = isset( $get_data['tab'] ) ? sanitize_key( $get_data['tab'] ) : 'settings';
674
		$section  = isset( $get_data['tab'] ) ? sanitize_key( $get_data['tab'] ) : 'settings';
675
676
		$input_callback_default   = array( $this, 'display_input_field' );
677
		$input_checkboxes_default = array( $this, 'display_checkboxes' );
678
		$input_select_default     = array( $this, 'display_select' );
679
		$link_default             = array( $this, 'display_link' );
680
681
		$all_field_callbacks = array(
682
			'text'       => $input_callback_default,
683
			'checkboxes' => $input_checkboxes_default,
684
			'select'     => $input_select_default,
685
			'link'       => $link_default,
686
		);
687
688
		$this->fields_settings( 'settings', 'settings', $all_field_callbacks );
689
		$this->fields_fieldmaps( 'fieldmaps', 'objects' );
690
		$this->fields_scheduling( 'schedule', 'schedule', $all_field_callbacks );
691
		$this->fields_log_settings( 'log_settings', 'log_settings', $all_field_callbacks );
692
		$this->fields_errors( 'mapping_errors', 'mapping_errors', $all_field_callbacks );
693
	}
694
695
	/**
696
	 * Fields for the Settings tab
697
	 * This runs add_settings_section once, as well as add_settings_field and register_setting methods for each option
698
	 *
699
	 * @param string $page what page we're on.
700
	 * @param string $section what section of the page.
701
	 * @param array  $callbacks method to call.
702
	 */
703
	private function fields_settings( $page, $section, $callbacks ) {
704
		add_settings_section( $page, ucwords( $page ), null, $page );
705
		$salesforce_settings = array(
706
			'consumer_key'                   => array(
707
				'title'    => __( 'Consumer Key', 'object-sync-for-salesforce' ),
708
				'callback' => $callbacks['text'],
709
				'page'     => $page,
710
				'section'  => $section,
711
				'args'     => array(
712
					'type'     => 'text',
713
					'validate' => 'sanitize_validate_text',
714
					'desc'     => '',
715
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_CONSUMER_KEY',
716
				),
717
718
			),
719
			'consumer_secret'                => array(
720
				'title'    => __( 'Consumer Secret', 'object-sync-for-salesforce' ),
721
				'callback' => $callbacks['text'],
722
				'page'     => $page,
723
				'section'  => $section,
724
				'args'     => array(
725
					'type'     => 'text',
726
					'validate' => 'sanitize_validate_text',
727
					'desc'     => '',
728
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_CONSUMER_SECRET',
729
				),
730
			),
731
			'callback_url'                   => array(
732
				'title'    => __( 'Callback URL', 'object-sync-for-salesforce' ),
733
				'callback' => $callbacks['text'],
734
				'page'     => $page,
735
				'section'  => $section,
736
				'args'     => array(
737
					'type'     => 'url',
738
					'validate' => 'sanitize_validate_text',
739
					'desc'     => sprintf(
740
						// translators: %1$s is the admin URL for the Authorize tab.
741
						__( 'In most cases, you will want to use %1$s for this value.', 'object-sync-for-salesforce' ),
742
						get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=authorize' )
743
					),
744
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_CALLBACK_URL',
745
				),
746
			),
747
			'login_base_url'                 => array(
748
				'title'    => __( 'Login Base URL', 'object-sync-for-salesforce' ),
749
				'callback' => $callbacks['text'],
750
				'page'     => $page,
751
				'section'  => $section,
752
				'args'     => array(
753
					'type'     => 'url',
754
					'validate' => 'sanitize_validate_text',
755
					'desc'     => sprintf(
756
						// translators: 1) production salesforce login, 2) sandbox salesforce login.
757
						__( 'For most Salesforce setups, you should use %1$s for production and %2$s for sandbox. If you try to use an instance name as the URL, you may encounter Salesforce errors.', 'object-sync-for-salesforce' ),
758
						esc_url( 'https://login.salesforce.com' ),
759
						esc_url( 'https://test.salesforce.com' )
760
					),
761
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_LOGIN_BASE_URL',
762
				),
763
			),
764
			'authorize_url_path'             => array(
765
				'title'    => __( 'Authorize URL Path', 'object-sync-for-salesforce' ),
766
				'callback' => $callbacks['text'],
767
				'page'     => $page,
768
				'section'  => $section,
769
				'args'     => array(
770
					'type'     => 'text',
771
					'validate' => 'sanitize_validate_text',
772
					'desc'     => __( 'For most Salesforce installs, this should not be changed.', 'object-sync-for-salesforce' ),
773
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_AUTHORIZE_URL_PATH',
774
					'default'  => $this->default_authorize_url_path,
775
				),
776
			),
777
			'token_url_path'                 => array(
778
				'title'    => __( 'Token URL Path', 'object-sync-for-salesforce' ),
779
				'callback' => $callbacks['text'],
780
				'page'     => $page,
781
				'section'  => $section,
782
				'args'     => array(
783
					'type'     => 'text',
784
					'validate' => 'sanitize_validate_text',
785
					'desc'     => __( 'For most Salesforce installs, this should not be changed.', 'object-sync-for-salesforce' ),
786
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_TOKEN_URL_PATH',
787
					'default'  => $this->default_token_url_path,
788
				),
789
			),
790
			'api_version'                    => array(
791
				'title'    => __( 'Salesforce API Version', 'object-sync-for-salesforce' ),
792
				'callback' => $callbacks['text'],
793
				'page'     => $page,
794
				'section'  => $section,
795
				'args'     => array(
796
					'type'     => 'text',
797
					'validate' => 'sanitize_validate_text',
798
					'desc'     => '',
799
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_API_VERSION',
800
					'default'  => $this->default_api_version,
801
				),
802
			),
803
			'object_filters'                 => array(
804
				'title'    => __( 'Limit Salesforce Objects', 'object-sync-for-salesforce' ),
805
				'callback' => $callbacks['checkboxes'],
806
				'page'     => $page,
807
				'section'  => $section,
808
				'args'     => array(
809
					'type'     => 'checkboxes',
810
					'validate' => 'sanitize_validate_text',
811
					'desc'     => __( 'Allows you to limit which Salesforce objects can be mapped', 'object-sync-for-salesforce' ),
812
					'items'    => array(
813
						'triggerable' => array(
814
							'text'    => __( 'Only Triggerable objects', 'object-sync-for-salesforce' ),
815
							'id'      => 'triggerable',
816
							'desc'    => '',
817
							'default' => $this->default_triggerable,
818
						),
819
						'updateable'  => array(
820
							'text'    => __( 'Only Updateable objects', 'object-sync-for-salesforce' ),
821
							'id'      => 'updateable',
822
							'desc'    => '',
823
							'default' => $this->default_updateable,
824
						),
825
					),
826
				),
827
			),
828
			'salesforce_field_display_value' => array(
829
				'title'    => __( 'Salesforce Field Display Value', 'object-sync-for-salesforce' ),
830
				'callback' => $callbacks['select'],
831
				'page'     => $page,
832
				'section'  => $section,
833
				'args'     => array(
834
					'type'     => 'select',
835
					'validate' => 'sanitize_validate_text',
836
					'desc'     => __( 'When choosing Salesforce fields to map, this value determines how the dropdown will identify Salesforce fields.', 'object-sync-for-salesforce' ),
837
					'constant' => '',
838
					'items'    => array(
839
						'field_label' => array(
840
							'text'  => __( 'Field Label', 'object-sync-for-salesforce' ),
841
							'value' => 'field_label',
842
						),
843
						'api_name'    => array(
844
							'text'  => __( 'API Name', 'object-sync-for-salesforce' ),
845
							'value' => 'api_name',
846
						),
847
					),
848
				),
849
			),
850
			'disable_mapped_fields'          => array(
851
				'title'    => __( 'Prevent Duplicate Field Mapping?', 'object-sync-for-salesforce' ),
852
				'callback' => $callbacks['text'],
853
				'page'     => $page,
854
				'section'  => $section,
855
				'args'     => array(
856
					'type'     => 'checkbox',
857
					'validate' => 'sanitize_text_field',
858
					'desc'     => __( 'If checked, any WordPress or Salesforce field that has already been mapped, or that is selected while creating or editing a fieldmap, cannot be mapped again.', 'object-sync-for-salesforce' ),
859
					'constant' => '',
860
				),
861
			),
862
			'pull_query_limit'               => array(
863
				'title'    => __( 'Pull Query Record Limit', 'object-sync-for-salesforce' ),
864
				'callback' => $callbacks['text'],
865
				'page'     => $page,
866
				'section'  => $section,
867
				'args'     => array(
868
					'type'     => 'number',
869
					'validate' => 'absint',
870
					'desc'     => __( 'Limit the number of records that can be pulled from Salesforce in a single query.', 'object-sync-for-salesforce' ),
871
					'constant' => '',
872
					'default'  => $this->default_pull_limit,
873
				),
874
			),
875
			'pull_throttle'                  => array(
876
				'title'    => __( 'Pull Throttle (In Seconds)', 'object-sync-for-salesforce' ),
877
				'callback' => $callbacks['text'],
878
				'page'     => $page,
879
				'section'  => $section,
880
				'args'     => array(
881
					'type'     => 'number',
882
					'validate' => 'sanitize_validate_text',
883
					'desc'     => __( 'Number of seconds to wait between repeated salesforce pulls. Prevents the webserver from becoming overloaded in case of too many cron runs, or webhook usage.', 'object-sync-for-salesforce' ),
884
					'constant' => '',
885
					'default'  => $this->default_pull_throttle,
886
				),
887
			),
888
		);
889
890
		// only show soap settings if the soap extension is enabled on the server.
891
		if ( true === $this->salesforce['soap_available'] ) {
892
			$salesforce_settings['use_soap']       = array(
893
				'title'    => __( 'Enable the Salesforce SOAP API?', 'object-sync-for-salesforce' ),
894
				'callback' => $callbacks['text'],
895
				'page'     => $page,
896
				'section'  => $section,
897
				'class'    => 'object-sync-for-salesforce-enable-soap',
898
				'args'     => array(
899
					'type'     => 'checkbox',
900
					'validate' => 'sanitize_text_field',
901
					'desc'     => __( 'Check this to enable the SOAP API and use it instead of the REST API when the plugin supports it. https://developer.salesforce.com/blogs/tech-pubs/2011/10/salesforce-apis-what-they-are-when-to-use-them.html to compare the two. Note: if you need to detect Salesforce merges in this plugin, you will need to enable SOAP.', 'object-sync-for-salesforce' ),
902
					'constant' => '',
903
				),
904
			);
905
			$salesforce_settings['soap_wsdl_path'] = array(
906
				'title'    => __( 'Path to SOAP WSDL File', 'object-sync-for-salesforce' ),
907
				'callback' => $callbacks['text'],
908
				'page'     => $page,
909
				'section'  => $section,
910
				'class'    => 'object-sync-for-salesforce-soap-wsdl-path',
911
				'args'     => array(
912
					'type'     => 'text',
913
					'validate' => 'sanitize_text_field',
914
					'desc'     => __( 'Optionally add a path to your own WSDL file. If you do not, the plugin will use the default partner.wsdl.xml from the Force.com toolkit.', 'object-sync-for-salesforce' ),
915
					'constant' => '',
916
				),
917
			);
918
		}
919
920
		$salesforce_settings['debug_mode']               = array(
921
			'title'    => __( 'Debug Mode?', 'object-sync-for-salesforce' ),
922
			'callback' => $callbacks['text'],
923
			'page'     => $page,
924
			'section'  => $section,
925
			'args'     => array(
926
				'type'     => 'checkbox',
927
				'validate' => 'sanitize_text_field',
928
				'desc'     => __( 'Debug mode can, combined with the Log Settings, log things like Salesforce API requests. It can create a lot of entries if enabled; it is not recommended to use it in a production environment.', 'object-sync-for-salesforce' ),
929
				'constant' => '',
930
			),
931
		);
932
		$salesforce_settings['delete_data_on_uninstall'] = array(
933
			'title'    => __( 'Delete Plugin Data on Uninstall?', 'object-sync-for-salesforce' ),
934
			'callback' => $callbacks['text'],
935
			'page'     => $page,
936
			'section'  => $section,
937
			'args'     => array(
938
				'type'     => 'checkbox',
939
				'validate' => 'sanitize_text_field',
940
				'desc'     => __( 'If checked, the plugin will delete the tables and other data it creates when you uninstall it. Unchecking this field can be useful if you need to reactivate the plugin for any reason without losing data.', 'object-sync-for-salesforce' ),
941
				'constant' => '',
942
			),
943
		);
944
945
		// if the user has authenticated with Salesforce, override the text field with a dropdown of available Salesforce API verisons.
946
		if ( true === is_object( $this->salesforce['sfapi'] ) && true === $this->salesforce['sfapi']->is_authorized() ) {
947
			$salesforce_settings['api_version'] = array(
948
				'title'    => __( 'Salesforce API Version', 'object-sync-for-salesforce' ),
949
				'callback' => $callbacks['select'],
950
				'page'     => $page,
951
				'section'  => $section,
952
				'args'     => array(
953
					'type'     => 'select',
954
					'validate' => 'sanitize_text_field',
955
					'desc'     => '',
956
					'constant' => 'OBJECT_SYNC_SF_SALESFORCE_API_VERSION',
957
					'items'    => $this->version_options(),
958
				),
959
			);
960
		}
961
962
		foreach ( $salesforce_settings as $key => $attributes ) {
963
			$id       = $this->option_prefix . $key;
964
			$name     = $this->option_prefix . $key;
965
			$title    = $attributes['title'];
966
			$callback = $attributes['callback'];
967
			$validate = $attributes['args']['validate'];
968
			$page     = $attributes['page'];
969
			$section  = $attributes['section'];
970
			$class    = isset( $attributes['class'] ) ? $attributes['class'] : '';
971
			$args     = array_merge(
972
				$attributes['args'],
973
				array(
974
					'title'     => $title,
975
					'id'        => $id,
976
					'label_for' => $id,
977
					'name'      => $name,
978
					'class'     => $class,
979
				)
980
			);
981
982
			// if there is a constant and it is defined, don't run a validate function.
983
			if ( isset( $attributes['args']['constant'] ) && defined( $attributes['args']['constant'] ) ) {
984
				$validate = '';
985
			}
986
987
			add_settings_field( $id, $title, $callback, $page, $section, $args );
988
			register_setting( $page, $id, array( $this, $validate ) );
989
		}
990
	}
991
992
	/**
993
	 * Fields for the Fieldmaps tab
994
	 * This runs add_settings_section once, as well as add_settings_field and register_setting methods for each option
995
	 *
996
	 * @param string $page what page we're on.
997
	 * @param string $section what section of the page.
998
	 * @param string $input_callback method to call.
999
	 */
1000
	private function fields_fieldmaps( $page, $section, $input_callback = '' ) {
1001
		add_settings_section( $page, ucwords( $page ), null, $page );
1002
	}
1003
1004
	/**
1005
	 * Fields for the Scheduling tab
1006
	 * This runs add_settings_section once, as well as add_settings_field and register_setting methods for each option
1007
	 *
1008
	 * @param string $page what page we're on.
1009
	 * @param string $section what section of the page.
1010
	 * @param array  $callbacks method to call.
1011
	 */
1012
	private function fields_scheduling( $page, $section, $callbacks ) {
1013
1014
		add_settings_section( 'batch', __( 'Batch Settings', 'object-sync-for-salesforce' ), null, $page );
1015
		$section           = 'batch';
1016
		$schedule_settings = array(
1017
			'action_scheduler_batch_size'         => array(
1018
				'title'    => __( 'Batch Size', 'object-sync-for-salesforce' ),
1019
				'callback' => $callbacks['text'],
1020
				'page'     => $page,
1021
				'section'  => $section,
1022
				'args'     => array(
1023
					'type'     => 'number',
1024
					'validate' => 'absint',
1025
					'default'  => 5,
1026
					'desc'     => __( 'Set how many actions (checking for data changes, syncing a record, etc. all count as individual actions) can be run in a batch. Start with a low number here, like 5, if you are unsure.', 'object-sync-for-salesforce' ),
1027
					'constant' => '',
1028
				),
1029
1030
			),
1031
			'action_scheduler_concurrent_batches' => array(
1032
				'title'    => __( 'Concurrent Batches', 'object-sync-for-salesforce' ),
1033
				'callback' => $callbacks['text'],
1034
				'page'     => $page,
1035
				'section'  => $section,
1036
				'args'     => array(
1037
					'type'     => 'number',
1038
					'validate' => 'absint',
1039
					'default'  => 3,
1040
					'desc'     => __( 'Set how many batches of actions can be run at once. Start with a low number here, like 3, if you are unsure.', 'object-sync-for-salesforce' ),
1041
					'constant' => '',
1042
				),
1043
			),
1044
		);
1045
1046
		foreach ( $this->schedulable_classes as $key => $value ) {
1047
			add_settings_section( $key, $value['label'], null, $page );
1048
			if ( isset( $value['initializer'] ) ) {
1049
				$schedule_settings[ $key . '_schedule_number' ] = array(
1050
					'title'    => __( 'Run Schedule Every', 'object-sync-for-salesforce' ),
1051
					'callback' => $callbacks['text'],
1052
					'page'     => $page,
1053
					'section'  => $key,
1054
					'args'     => array(
1055
						'type'     => 'number',
1056
						'validate' => 'absint',
1057
						'desc'     => '',
1058
						'constant' => '',
1059
					),
1060
				);
1061
				$schedule_settings[ $key . '_schedule_unit' ]   = array(
1062
					'title'    => __( 'Time Unit', 'object-sync-for-salesforce' ),
1063
					'callback' => $callbacks['select'],
1064
					'page'     => $page,
1065
					'section'  => $key,
1066
					'args'     => array(
1067
						'type'     => 'select',
1068
						'validate' => 'sanitize_validate_text',
1069
						'desc'     => '',
1070
						'items'    => array(
1071
							'minutes' => array(
1072
								'text'  => __( 'Minutes', 'object-sync-for-salesforce' ),
1073
								'value' => 'minutes',
1074
							),
1075
							'hours'   => array(
1076
								'text'  => __( 'Hours', 'object-sync-for-salesforce' ),
1077
								'value' => 'hours',
1078
							),
1079
							'days'    => array(
1080
								'text'  => __( 'Days', 'object-sync-for-salesforce' ),
1081
								'value' => 'days',
1082
							),
1083
						),
1084
					),
1085
				);
1086
			}
1087
			$schedule_settings[ $key . '_clear_button' ] = array(
1088
				// translators: $this->get_schedule_count is an integer showing how many items are in the current queue.
1089
				'title'    => sprintf( 'This Queue has ' . _n( '%s Item', '%s Items', $this->get_schedule_count( $key ), 'object-sync-for-salesforce' ), $this->get_schedule_count( $key ) ),
1090
				'callback' => $callbacks['link'],
1091
				'page'     => $page,
1092
				'section'  => $key,
1093
				'args'     => array(
1094
					'label'      => __( 'Clear this queue', 'object-sync-for-salesforce' ),
1095
					'desc'       => '',
1096
					'url'        => esc_url( '?page=' . $this->admin_settings_url_param . '&amp;tab=clear_schedule&amp;schedule_name=' . $key ),
1097
					'link_class' => 'button button-secondary',
1098
				),
1099
			);
1100
			foreach ( $schedule_settings as $key => $attributes ) {
1101
				$id       = $this->option_prefix . $key;
1102
				$name     = $this->option_prefix . $key;
1103
				$title    = $attributes['title'];
1104
				$callback = $attributes['callback'];
1105
				$page     = $attributes['page'];
1106
				$section  = $attributes['section'];
1107
				$args     = array_merge(
1108
					$attributes['args'],
1109
					array(
1110
						'title'     => $title,
1111
						'id'        => $id,
1112
						'label_for' => $id,
1113
						'name'      => $name,
1114
					)
1115
				);
1116
				add_settings_field( $id, $title, $callback, $page, $section, $args );
1117
				register_setting( $page, $id );
1118
			}
1119
		} // End foreach statement.
1120
	}
1121
1122
	/**
1123
	 * Fields for the Log Settings tab
1124
	 * This runs add_settings_section once, as well as add_settings_field and register_setting methods for each option
1125
	 *
1126
	 * @param string $page what page we're on.
1127
	 * @param string $section what section of the page.
1128
	 * @param array  $callbacks method to call.
1129
	 */
1130
	private function fields_log_settings( $page, $section, $callbacks ) {
1131
		add_settings_section( $page, ucwords( str_replace( '_', ' ', $page ) ), null, $page );
1132
		$log_settings = array(
1133
			'enable_logging'        => array(
1134
				'title'    => __( 'Enable Logging?', 'object-sync-for-salesforce' ),
1135
				'callback' => $callbacks['text'],
1136
				'page'     => $page,
1137
				'section'  => $section,
1138
				'args'     => array(
1139
					'type'     => 'checkbox',
1140
					'validate' => 'absint',
1141
					'desc'     => '',
1142
					'constant' => '',
1143
				),
1144
			),
1145
			'statuses_to_log'       => array(
1146
				'title'    => __( 'Statuses to Log', 'object-sync-for-salesforce' ),
1147
				'callback' => $callbacks['checkboxes'],
1148
				'page'     => $page,
1149
				'section'  => $section,
1150
				'args'     => array(
1151
					'type'     => 'checkboxes',
1152
					'validate' => 'sanitize_validate_text',
1153
					'desc'     => __( 'These are the statuses to log', 'object-sync-for-salesforce' ),
1154
					'items'    => array(
1155
						'error'   => array(
1156
							'text' => __( 'Error', 'object-sync-for-salesforce' ),
1157
							'id'   => 'error',
1158
							'desc' => '',
1159
						),
1160
						'success' => array(
1161
							'text' => __( 'Success', 'object-sync-for-salesforce' ),
1162
							'id'   => 'success',
1163
							'desc' => '',
1164
						),
1165
						'notice'  => array(
1166
							'text' => __( 'Notice', 'object-sync-for-salesforce' ),
1167
							'id'   => 'notice',
1168
							'desc' => '',
1169
						),
1170
						'debug'   => array(
1171
							'text' => __( 'Debug', 'object-sync-for-salesforce' ),
1172
							'id'   => 'debug',
1173
							'desc' => '',
1174
						),
1175
					),
1176
				),
1177
			),
1178
			'prune_logs'            => array(
1179
				'title'    => __( 'Automatically Delete Old Log Entries?', 'object-sync-for-salesforce' ),
1180
				'callback' => $callbacks['text'],
1181
				'page'     => $page,
1182
				'section'  => $section,
1183
				'args'     => array(
1184
					'type'     => 'checkbox',
1185
					'validate' => 'absint',
1186
					'desc'     => '',
1187
					'constant' => '',
1188
				),
1189
			),
1190
			'logs_how_old'          => array(
1191
				'title'    => __( 'Age to Delete Log Entries', 'object-sync-for-salesforce' ),
1192
				'callback' => $callbacks['text'],
1193
				'page'     => $page,
1194
				'section'  => $section,
1195
				'args'     => array(
1196
					'type'     => 'text',
1197
					'validate' => 'sanitize_validate_text',
1198
					'desc'     => __( 'If automatic deleting is enabled, it will affect logs this old.', 'object-sync-for-salesforce' ),
1199
					'default'  => '2 weeks',
1200
					'constant' => '',
1201
				),
1202
			),
1203
			'logs_how_often_number' => array(
1204
				'title'    => __( 'Check For Old Logs Every', 'object-sync-for-salesforce' ),
1205
				'callback' => $callbacks['text'],
1206
				'page'     => $page,
1207
				'section'  => $section,
1208
				'args'     => array(
1209
					'type'     => 'number',
1210
					'validate' => 'absint',
1211
					'desc'     => '',
1212
					'default'  => '1',
1213
					'constant' => '',
1214
				),
1215
			),
1216
			'logs_how_often_unit'   => array(
1217
				'title'    => __( 'Time Unit', 'object-sync-for-salesforce' ),
1218
				'callback' => $callbacks['select'],
1219
				'page'     => $page,
1220
				'section'  => $section,
1221
				'args'     => array(
1222
					'type'     => 'select',
1223
					'validate' => 'sanitize_validate_text',
1224
					'desc'     => __( 'These two fields are how often the site will check for logs to delete.', 'object-sync-for-salesforce' ),
1225
					'items'    => array(
1226
						'minutes' => array(
1227
							'text'  => __( 'Minutes', 'object-sync-for-salesforce' ),
1228
							'value' => 'minutes',
1229
						),
1230
						'hours'   => array(
1231
							'text'  => __( 'Hours', 'object-sync-for-salesforce' ),
1232
							'value' => 'hours',
1233
						),
1234
						'days'    => array(
1235
							'text'  => __( 'Days', 'object-sync-for-salesforce' ),
1236
							'value' => 'days',
1237
						),
1238
					),
1239
				),
1240
			),
1241
			'logs_how_many_number'  => array(
1242
				'title'    => __( 'Clear This Many Log Entries', 'object-sync-for-salesforce' ),
1243
				'callback' => $callbacks['text'],
1244
				'page'     => $page,
1245
				'section'  => $section,
1246
				'args'     => array(
1247
					'type'     => 'number',
1248
					'validate' => 'absint',
1249
					'desc'     => __( 'This number is how many log entries the plugin will try to clear at a time. If you do not enter a number, the default is 100.', 'object-sync-for-salesforce' ),
1250
					'default'  => '100',
1251
					'constant' => '',
1252
				),
1253
			),
1254
			'triggers_to_log'       => array(
1255
				'title'    => __( 'Triggers to Log', 'object-sync-for-salesforce' ),
1256
				'callback' => $callbacks['checkboxes'],
1257
				'page'     => $page,
1258
				'section'  => $section,
1259
				'args'     => array(
1260
					'type'     => 'checkboxes',
1261
					'validate' => 'sanitize_validate_text',
1262
					'desc'     => __( 'These are the triggers to log', 'object-sync-for-salesforce' ),
1263
					'items'    => array(
1264
						$this->mappings->sync_wordpress_create => array(
1265
							'text' => __( 'WordPress Create', 'object-sync-for-salesforce' ),
1266
							'id'   => 'wordpress_create',
1267
							'desc' => '',
1268
						),
1269
						$this->mappings->sync_wordpress_update => array(
1270
							'text' => __( 'WordPress Update', 'object-sync-for-salesforce' ),
1271
							'id'   => 'wordpress_update',
1272
							'desc' => '',
1273
						),
1274
						$this->mappings->sync_wordpress_delete => array(
1275
							'text' => __( 'WordPress Delete', 'object-sync-for-salesforce' ),
1276
							'id'   => 'wordpress_delete',
1277
							'desc' => '',
1278
						),
1279
						$this->mappings->sync_sf_create => array(
1280
							'text' => __( 'Salesforce Create', 'object-sync-for-salesforce' ),
1281
							'id'   => 'sf_create',
1282
							'desc' => '',
1283
						),
1284
						$this->mappings->sync_sf_update => array(
1285
							'text' => __( 'Salesforce Update', 'object-sync-for-salesforce' ),
1286
							'id'   => 'sf_update',
1287
							'desc' => '',
1288
						),
1289
						$this->mappings->sync_sf_delete => array(
1290
							'text' => __( 'Salesforce Delete', 'object-sync-for-salesforce' ),
1291
							'id'   => 'sf_delete',
1292
							'desc' => '',
1293
						),
1294
					),
1295
				),
1296
			),
1297
		);
1298
		foreach ( $log_settings as $key => $attributes ) {
1299
			$id       = $this->option_prefix . $key;
1300
			$name     = $this->option_prefix . $key;
1301
			$title    = $attributes['title'];
1302
			$callback = $attributes['callback'];
1303
			$page     = $attributes['page'];
1304
			$section  = $attributes['section'];
1305
			$args     = array_merge(
1306
				$attributes['args'],
1307
				array(
1308
					'title'     => $title,
1309
					'id'        => $id,
1310
					'label_for' => $id,
1311
					'name'      => $name,
1312
				)
1313
			);
1314
			add_settings_field( $id, $title, $callback, $page, $section, $args );
1315
			register_setting( $page, $id );
1316
		}
1317
	}
1318
1319
	/**
1320
	 * Fields for the Mapping Errors tab
1321
	 * This runs add_settings_section once, as well as add_settings_field and register_setting methods for each option
1322
	 *
1323
	 * @param string $page what page we're on.
1324
	 * @param string $section what section of the page.
1325
	 * @param array  $callbacks method to call.
1326
	 */
1327
	private function fields_errors( $page, $section, $callbacks ) {
1328
1329
		add_settings_section( $section, __( 'Mapping Error Settings', 'object-sync-for-salesforce' ), null, $page );
1330
		$error_settings = array(
1331
			'errors_per_page' => array(
1332
				'title'    => __( 'Errors per page', 'object-sync-for-salesforce' ),
1333
				'callback' => $callbacks['text'],
1334
				'page'     => $page,
1335
				'section'  => $section,
1336
				'args'     => array(
1337
					'type'     => 'number',
1338
					'validate' => 'absint',
1339
					'default'  => 50,
1340
					'desc'     => __( 'Set how many mapping errors to show on a single page.', 'object-sync-for-salesforce' ),
1341
					'constant' => '',
1342
				),
1343
			),
1344
		);
1345
1346
		foreach ( $error_settings as $key => $attributes ) {
1347
			$id       = $this->option_prefix . $key;
1348
			$name     = $this->option_prefix . $key;
1349
			$title    = $attributes['title'];
1350
			$callback = $attributes['callback'];
1351
			$page     = $attributes['page'];
1352
			$section  = $attributes['section'];
1353
			$args     = array_merge(
1354
				$attributes['args'],
1355
				array(
1356
					'title'     => $title,
1357
					'id'        => $id,
1358
					'label_for' => $id,
1359
					'name'      => $name,
1360
				)
1361
			);
1362
			add_settings_field( $id, $title, $callback, $page, $section, $args );
1363
			register_setting( $page, $id );
1364
		} // End foreach() method.
1365
	}
1366
1367
	/**
1368
	 * Create the notices, settings, and conditions by which admin notices should appear
1369
	 */
1370
	public function notices() {
1371
1372
		// before a notice is displayed, we should make sure we are on a page related to this plugin.
1373
		if ( ! isset( $_GET['page'] ) || $this->admin_settings_url_param !== $_GET['page'] ) {
1374
			return;
1375
		}
1376
1377
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
1378
1379
		$notices = array(
1380
			'permission'              => array(
1381
				'condition'   => ( false === $this->check_wordpress_admin_permissions() ),
1382
				'message'     => __( "Your account does not have permission to edit the Object Sync for Salesforce plugin's settings.", 'object-sync-for-salesforce' ),
1383
				'type'        => 'error',
1384
				'dismissible' => false,
1385
			),
1386
			'fieldmap'                => array(
1387
				'condition'   => isset( $get_data['transient'] ),
1388
				'message'     => __( 'Errors kept this fieldmap from being saved.', 'object-sync-for-salesforce' ),
1389
				'type'        => 'error',
1390
				'dismissible' => true,
1391
			),
1392
			'fieldmap_missing'        => array(
1393
				'condition'   => isset( $get_data['missing_fieldmap'] ),
1394
				'message'     => __( 'There is no fieldmap with the supplied ID. Instead, the list of all available fieldmaps is displayed.', 'object-sync-for-salesforce' ),
1395
				'type'        => 'error',
1396
				'dismissible' => true,
1397
			),
1398
			'object_map'              => array(
1399
				'condition'   => isset( $get_data['map_transient'] ),
1400
				'message'     => __( 'Errors kept this object map from being saved.', 'object-sync-for-salesforce' ),
1401
				'type'        => 'error',
1402
				'dismissible' => true,
1403
			),
1404
			'data_saved'              => array(
1405
				'condition'   => isset( $get_data['data_saved'] ) && 'true' === $get_data['data_saved'],
1406
				'message'     => __( 'This data was successfully saved.', 'object-sync-for-salesforce' ),
1407
				'type'        => 'success',
1408
				'dismissible' => true,
1409
			),
1410
			'data_save_partial'       => array(
1411
				'condition'   => isset( $get_data['data_saved'] ) && 'partial' === $get_data['data_saved'],
1412
				'message'     => __( 'This data was partially successfully saved. This means some of the data was unable to save. If you have enabled logging in the plugin settings, there should be a log entry with further details.', 'object-sync-for-salesforce' ),
1413
				'type'        => 'error',
1414
				'dismissible' => true,
1415
			),
1416
			'data_save_error'         => array(
1417
				'condition'   => isset( $get_data['data_saved'] ) && 'false' === $get_data['data_saved'],
1418
				'message'     => __( 'This data was not successfully saved. Try again.', 'object-sync-for-salesforce' ),
1419
				'type'        => 'error',
1420
				'dismissible' => true,
1421
			),
1422
			'mapping_error_transient' => array(
1423
				'condition'   => isset( $get_data['mapping_error_transient'] ),
1424
				'message'     => __( 'Errors kept these mapping errors from being deleted.', 'object-sync-for-salesforce' ),
1425
				'type'        => 'error',
1426
				'dismissible' => true,
1427
			),
1428
		);
1429
1430
		foreach ( $notices as $key => $value ) {
1431
1432
			$condition = (bool) $value['condition'];
1433
			$message   = $value['message'];
1434
1435
			if ( isset( $value['dismissible'] ) ) {
1436
				$dismissible = $value['dismissible'];
1437
			} else {
1438
				$dismissible = false;
1439
			}
1440
1441
			if ( isset( $value['type'] ) ) {
1442
				$type = $value['type'];
1443
			} else {
1444
				$type = '';
1445
			}
1446
1447
			if ( ! isset( $value['template'] ) ) {
1448
				$template = '';
1449
			}
1450
1451
			if ( $condition ) {
1452
				new Object_Sync_Sf_Admin_Notice( $condition, $message, $dismissible, $type, $template );
1453
			}
1454
		}
1455
1456
	}
1457
1458
	/**
1459
	 * Get all the Salesforce object settings for fieldmapping
1460
	 * This takes either the $_POST array via ajax, or can be directly called with a $data array
1461
	 *
1462
	 * @param array $data must contain a Salesforce object, can optionally contain a type.
1463
	 * @return array $object_settings
1464
	 */
1465
	public function get_salesforce_object_description( $data = array() ) {
1466
		$ajax = false;
1467
		if ( empty( $data ) ) {
1468
			$data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1469
			$ajax = true;
1470
		}
1471
1472
		$object_description = array();
1473
1474
		if ( ! empty( $data['salesforce_object'] ) ) {
1475
			$object = $this->salesforce['sfapi']->object_describe( esc_attr( $data['salesforce_object'] ) );
1476
1477
			$object_fields        = array();
1478
			$include_record_types = array();
1479
1480
			// these can come from ajax.
1481
			$include = isset( $data['include'] ) ? (array) $data['include'] : array();
1482
			$include = array_map( 'esc_attr', $include );
1483
1484
			if ( in_array( 'fields', $include, true ) || empty( $include ) ) {
1485
				$type = isset( $data['field_type'] ) ? esc_attr( $data['field_type'] ) : ''; // can come from ajax.
1486
1487
				// here, we should respect the decision of whether to show the API name or the label.
1488
				$display_value = get_option( $this->option_prefix . 'salesforce_field_display_value', 'field_label' );
1489
				if ( 'api_name' === $display_value ) {
1490
					$visible_label_field = 'name';
1491
				} else {
1492
					$visible_label_field = 'label';
1493
				}
1494
				$attributes = array( 'name', $visible_label_field );
1495
1496
				foreach ( $object['data']['fields'] as $key => $value ) {
1497
					if ( '' === $type || $type === $value['type'] ) {
1498
						$object_fields[ $key ] = $value;
1499
						if ( isset( $attributes ) ) {
1500
							$object_fields[ $key ] = array_intersect_key( $value, array_flip( $attributes ) );
1501
						}
1502
					}
1503
				}
1504
				$object_description['fields'] = $object_fields;
1505
			}
1506
1507
			if ( in_array( 'recordTypeInfos', $include, true ) ) {
1508
				if ( isset( $object['data']['recordTypeInfos'] ) && count( $object['data']['recordTypeInfos'] ) > 1 ) {
1509
					foreach ( $object['data']['recordTypeInfos'] as $type ) {
1510
						$object_record_types[ $type['recordTypeId'] ] = $type['name'];
1511
					}
1512
					$object_description['recordTypeInfos'] = $object_record_types;
1513
				}
1514
			}
1515
		}
1516
1517
		if ( true === $ajax ) {
1518
			wp_send_json_success( $object_description );
1519
		} else {
1520
			return $object_description;
1521
		}
1522
	}
1523
1524
	/**
1525
	 * Get all the Salesforce fields settings for fieldmapping
1526
	 * This takes either the $_POST array via ajax, or can be directly called with a $data array
1527
	 *
1528
	 * @param array $data must contain a Salesforce object unless it is Ajax, can optionally contain a type.
1529
	 * @return array $object_fields
1530
	 */
1531
	public function get_salesforce_object_fields( $data = array() ) {
1532
		$ajax      = false;
1533
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1534
		if ( empty( $data ) ) {
1535
			$salesforce_object = isset( $post_data['salesforce_object'] ) ? sanitize_text_field( wp_unslash( $post_data['salesforce_object'] ) ) : '';
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($post_data['salesforce_object']) can also be of type array; however, parameter $str of sanitize_text_field() 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

1535
			$salesforce_object = isset( $post_data['salesforce_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['salesforce_object'] ) ) : '';
Loading history...
1536
			$ajax              = true;
1537
			// here, we should respect the decision of whether to show the API name or the label.
1538
			$display_value = get_option( $this->option_prefix . 'salesforce_field_display_value', 'field_label' );
1539
			if ( 'api_name' === $display_value ) {
1540
				$visible_label_field = 'name';
1541
			} else {
1542
				$visible_label_field = 'label';
1543
			}
1544
			$attributes = array( 'name', $visible_label_field );
1545
		} else {
1546
			$salesforce_object = isset( $data['salesforce_object'] ) ? sanitize_text_field( wp_unslash( $data['salesforce_object'] ) ) : '';
1547
		}
1548
		$object_fields = array();
1549
		if ( ! empty( $salesforce_object ) ) {
1550
			$object               = $this->salesforce['sfapi']->object_describe( esc_attr( $salesforce_object ) );
1551
			$object_fields        = array();
1552
			$type                 = isset( $data['type'] ) ? esc_attr( $data['type'] ) : '';
1553
			$include_record_types = isset( $data['include_record_types'] ) ? esc_attr( $data['include_record_types'] ) : false;
1554
			foreach ( $object['data']['fields'] as $key => $value ) {
1555
				if ( '' === $type || $type === $value['type'] ) {
1556
					$object_fields[ $key ] = $value;
1557
					if ( isset( $attributes ) ) {
1558
						$object_fields[ $key ] = array_intersect_key( $value, array_flip( $attributes ) );
1559
					}
1560
				}
1561
			}
1562
			if ( true === $include_record_types ) {
0 ignored issues
show
introduced by
The condition true === $include_record_types is always false.
Loading history...
1563
				$object_record_types = array();
1564
				if ( isset( $object['data']['recordTypeInfos'] ) && count( $object['data']['recordTypeInfos'] ) > 1 ) {
1565
					foreach ( $object['data']['recordTypeInfos'] as $type ) {
1566
						$object_record_types[ $type['recordTypeId'] ] = $type['name'];
1567
					}
1568
				}
1569
			}
1570
		}
1571
1572
		if ( true === $ajax ) {
1573
			$ajax_response = array(
1574
				'fields' => $object_fields,
1575
			);
1576
			wp_send_json_success( $ajax_response );
1577
		} else {
1578
			return $object_fields;
1579
		}
1580
1581
	}
1582
1583
	/**
1584
	 * Get WordPress object fields for fieldmapping
1585
	 * This takes either the $_POST array via ajax, or can be directly called with a $wordpress_object field
1586
	 *
1587
	 * @param string $wordpress_object is the name of the WordPress object.
1588
	 * @return array $object_fields
1589
	 */
1590
	public function get_wordpress_object_fields( $wordpress_object = '' ) {
1591
		$ajax      = false;
1592
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1593
		if ( empty( $wordpress_object ) ) {
1594
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( wp_unslash( $post_data['wordpress_object'] ) ) : '';
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($post_data['wordpress_object']) can also be of type array; however, parameter $str of sanitize_text_field() 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

1594
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1595
			$ajax             = true;
1596
		}
1597
1598
		$object_fields = $this->wordpress->get_wordpress_object_fields( $wordpress_object );
1599
1600
		if ( true === $ajax ) {
1601
			$ajax_response = array(
1602
				'fields' => $object_fields,
1603
			);
1604
			wp_send_json_success( $ajax_response );
1605
		} else {
1606
			return $object_fields;
1607
		}
1608
	}
1609
1610
	/**
1611
	 * Manually push the WordPress object to Salesforce
1612
	 * This takes either the $_POST array via ajax, or can be directly called with $wordpress_object and $wordpress_id fields
1613
	 *
1614
	 * @param string $wordpress_object is the name of the WordPress object.
1615
	 * @param int    $wordpress_id is the ID of the WordPress record.
1616
	 * @param bool   $force_return Force the method to return json instead of outputting it.
1617
	 */
1618
	public function push_to_salesforce( $wordpress_object = '', $wordpress_id = '', $force_return = false ) {
1619
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1620
		if ( empty( $wordpress_object ) && empty( $wordpress_id ) ) {
1621
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( wp_unslash( $post_data['wordpress_object'] ) ) : '';
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($post_data['wordpress_object']) can also be of type array; however, parameter $str of sanitize_text_field() 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

1621
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1622
			$wordpress_id     = isset( $post_data['wordpress_id'] ) ? absint( $post_data['wordpress_id'] ) : '';
1623
		}
1624
1625
		// clarify what that variable is in this context.
1626
		$object_type = $wordpress_object;
1627
1628
		// When objects are already mapped, there is a Salesforce id as well. Otherwise, it's blank.
1629
		$salesforce_id = isset( $post_data['salesforce_id'] ) ? sanitize_text_field( $post_data['salesforce_id'] ) : '';
1630
		if ( '' === $salesforce_id ) {
1631
			$method = 'POST';
1632
		} else {
1633
			$method = 'PUT';
1634
		}
1635
1636
		$result = $this->push->manual_push( $object_type, $wordpress_id, $method );
1637
1638
		if ( false === $force_return && ! empty( $post_data['wordpress_object'] ) && ! empty( $post_data['wordpress_id'] ) ) {
1639
			wp_send_json_success( $result );
1640
		} else {
1641
			return $result;
1642
		}
1643
1644
	}
1645
1646
	/**
1647
	 * Manually pull the Salesforce object into WordPress
1648
	 * This takes either the $_POST array via ajax, or can be directly called with $salesforce_id fields
1649
	 *
1650
	 * @param string $salesforce_id is the ID of the Salesforce record.
1651
	 * @param string $wordpress_object is the name of the WordPress object.
1652
	 */
1653
	public function pull_from_salesforce( $salesforce_id = '', $wordpress_object = '' ) {
1654
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1655
		if ( empty( $wordpress_object ) && empty( $salesforce_id ) ) {
1656
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( wp_unslash( $post_data['wordpress_object'] ) ) : '';
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($post_data['wordpress_object']) can also be of type array; however, parameter $str of sanitize_text_field() 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

1656
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1657
			$salesforce_id    = isset( $post_data['salesforce_id'] ) ? sanitize_text_field( wp_unslash( $post_data['salesforce_id'] ) ) : '';
1658
		}
1659
		$type   = $this->salesforce['sfapi']->get_sobject_type( $salesforce_id );
1660
		$result = $this->pull->manual_pull( $type, $salesforce_id, $wordpress_object ); // we want the wp object to make sure we get the right fieldmap.
1661
		if ( ! empty( $post_data ) ) {
1662
			wp_send_json_success( $result );
1663
		} else {
1664
			return $result;
1665
		}
1666
	}
1667
1668
	/**
1669
	 * Manually pull the Salesforce object into WordPress
1670
	 * This takes an id for a mapping object row
1671
	 *
1672
	 * @param int $mapping_id is the ID of the mapping object record.
1673
	 */
1674
	public function refresh_mapped_data( $mapping_id = '' ) {
1675
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1676
		if ( empty( $mapping_id ) ) {
1677
			$mapping_id = isset( $post_data['mapping_id'] ) ? absint( $post_data['mapping_id'] ) : '';
1678
		}
1679
		$result = $this->mappings->get_all_object_maps(
1680
			array(
1681
				'id' => $mapping_id,
1682
			)
1683
		);
1684
1685
		$object_map = array();
1686
1687
		// result is an array of arrays, not just one array.
1688
		if ( 1 === count( $result ) ) {
1689
			$object_map = $result[0];
1690
		}
1691
1692
		if ( ! empty( $post_data ) ) {
1693
			wp_send_json_success( $object_map );
1694
		} else {
1695
			return $object_map;
1696
		}
1697
	}
1698
1699
	/**
1700
	 * Prepare fieldmap data and redirect after processing
1701
	 * This runs when the create or update forms are submitted
1702
	 * It is public because it depends on an admin hook
1703
	 * It then calls the Object_Sync_Sf_Mapping class and sends prepared data over to it, then redirects to the correct page
1704
	 * This method does include error handling, by loading the submission in a transient if there is an error, and then deleting it upon success
1705
	 */
1706
	public function prepare_fieldmap_data() {
1707
		$error     = false;
1708
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1709
		$cachekey  = wp_json_encode( $post_data );
1710
		if ( false !== $cachekey ) {
1711
			$cachekey = md5( $cachekey );
1712
		}
1713
1714
		if ( ! isset( $post_data['label'] ) || ! isset( $post_data['salesforce_object'] ) || ! isset( $post_data['wordpress_object'] ) ) {
1715
			$error = true;
1716
		}
1717
		if ( true === $error ) {
1718
			$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1719
			if ( '' !== $cachekey ) {
1720
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&transient=' . $cachekey;
0 ignored issues
show
Bug introduced by
Are you sure $cachekey of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

1720
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1721
			}
1722
		} else { // there are no errors
1723
			// send the row to the fieldmap class
1724
			// if it is add or clone, use the create method.
1725
			$method            = esc_attr( $post_data['method'] );
1726
			$salesforce_fields = $this->get_salesforce_object_fields(
1727
				array(
1728
					'salesforce_object' => $post_data['salesforce_object'],
1729
				)
1730
			);
1731
			$wordpress_fields  = $this->get_wordpress_object_fields( $post_data['wordpress_object'] );
1732
			if ( 'add' === $method || 'clone' === $method ) {
1733
				$result = $this->mappings->create_fieldmap( $post_data, $wordpress_fields, $salesforce_fields );
1734
			} elseif ( 'edit' === $method ) { // if it is edit, use the update method.
1735
				$id     = esc_attr( $post_data['id'] );
1736
				$result = $this->mappings->update_fieldmap( $post_data, $wordpress_fields, $salesforce_fields, $id );
1737
			}
1738
			if ( false === $result ) { // if the database didn't save, it's still an error.
1739
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1740
				if ( '' !== $cachekey ) {
1741
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&transient=' . $cachekey;
1742
				}
1743
			} else {
1744
				// if the user has saved a fieldmap, clear the currently running query value if there is one.
1745
				if ( '' !== get_option( $this->option_prefix . 'currently_pulling_query_' . $post_data['salesforce_object'], '' ) ) {
1746
					$this->pull->clear_current_type_query( $post_data['salesforce_object'] );
1747
				}
1748
				if ( isset( $post_data['transient'] ) ) { // there was previously an error saved. can delete it now.
1749
					$this->sfwp_transients->delete( esc_attr( $post_data['map_transient'] ) );
1750
				}
1751
				// then send the user to the list of fieldmaps.
1752
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1753
			}
1754
		}
1755
		wp_safe_redirect( $url );
1756
		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...
1757
	}
1758
1759
	/**
1760
	 * Delete fieldmap data and redirect after processing
1761
	 * This runs when the delete link is clicked, after the user confirms
1762
	 * It is public because it depends on an admin hook
1763
	 * It then calls the Object_Sync_Sf_Mapping class and the delete method
1764
	 */
1765
	public function delete_fieldmap() {
1766
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1767
		if ( $post_data['id'] ) {
1768
			$result = $this->mappings->delete_fieldmap( $post_data['id'] );
1769
			if ( true === $result ) {
1770
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1771
			} else {
1772
				$url = esc_url_raw( $post_data['redirect_url_error'] . '&id=' . $post_data['id'] );
1773
			}
1774
			wp_safe_redirect( $url );
1775
			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...
1776
		}
1777
	}
1778
1779
	/**
1780
	 * Prepare object data and redirect after processing
1781
	 * This runs when the update form is submitted
1782
	 * It is public because it depends on an admin hook
1783
	 * It then calls the Object_Sync_Sf_Mapping class and sends prepared data over to it, then redirects to the correct page
1784
	 * This method does include error handling, by loading the submission in a transient if there is an error, and then deleting it upon success
1785
	 */
1786
	public function prepare_object_map_data() {
1787
		$error     = false;
1788
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1789
		$cachekey  = wp_json_encode( $post_data );
1790
		if ( false !== $cachekey ) {
1791
			$cachekey = md5( $cachekey );
1792
		}
1793
1794
		if ( ! isset( $post_data['wordpress_id'] ) || ! isset( $post_data['salesforce_id'] ) ) {
1795
			$error = true;
1796
		}
1797
		if ( true === $error ) {
1798
			$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1799
			if ( '' !== $cachekey ) {
1800
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&map_transient=' . $cachekey;
0 ignored issues
show
Bug introduced by
Are you sure $cachekey of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

1800
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&map_transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1801
			}
1802
		} else { // there are no errors
1803
			// send the row to the object map class.
1804
			$method = esc_attr( $post_data['method'] );
1805
			if ( 'edit' === $method ) { // if it is edit, use the update method.
1806
				$id     = esc_attr( $post_data['id'] );
1807
				$result = $this->mappings->update_object_map( $post_data, $id );
1808
			}
1809
			if ( false === $result ) { // if the database didn't save, it's still an error.
1810
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1811
				if ( '' !== $cachekey ) {
1812
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&map_transient=' . $cachekey;
1813
				}
1814
			} else {
1815
				if ( isset( $post_data['map_transient'] ) ) { // there was previously an error saved. can delete it now.
1816
					$this->sfwp_transients->delete( esc_attr( $post_data['map_transient'] ) );
1817
				}
1818
				// then send the user to the success redirect url.
1819
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1820
			}
1821
		}
1822
		wp_safe_redirect( $url );
1823
		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...
1824
	}
1825
1826
	/**
1827
	 * Delete object map data and redirect after processing
1828
	 * This runs when the delete link is clicked on an error row, after the user confirms
1829
	 * It is public because it depends on an admin hook
1830
	 * It then calls the Object_Sync_Sf_Mapping class and the delete method
1831
	 */
1832
	public function delete_object_map() {
1833
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1834
		if ( isset( $post_data['id'] ) ) {
1835
			$result = $this->mappings->delete_object_map( $post_data['id'] );
1836
			if ( true === $result ) {
1837
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1838
			} else {
1839
				$url = esc_url_raw( $post_data['redirect_url_error'] . '&id=' . $post_data['id'] );
1840
			}
1841
			wp_safe_redirect( $url );
1842
			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...
1843
		} elseif ( $post_data['delete'] ) {
1844
			$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1845
			$cachekey  = wp_json_encode( $post_data );
1846
			if ( false !== $cachekey ) {
1847
				$cachekey = md5( $cachekey );
1848
			}
1849
			$error = false;
1850
			if ( ! isset( $post_data['delete'] ) ) {
1851
				$error = true;
1852
			}
1853
			if ( true === $error ) {
1854
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1855
				if ( '' !== $cachekey ) {
1856
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&mapping_error_transient=' . $cachekey;
0 ignored issues
show
Bug introduced by
Are you sure $cachekey of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

1856
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&mapping_error_transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1857
				}
1858
			} else { // there are no errors.
1859
				$result = $this->mappings->delete_object_map( array_keys( $post_data['delete'] ) );
1860
				if ( true === $result ) {
1861
					$url = esc_url_raw( $post_data['redirect_url_success'] );
1862
				}
1863
1864
				if ( false === $result ) { // if the database didn't save, it's still an error.
1865
					$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1866
					if ( '' !== $cachekey ) {
1867
						$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&mapping_error_transient=' . $cachekey;
1868
					}
1869
				} else {
1870
					if ( isset( $post_data['mapping_error_transient'] ) ) { // there was previously an error saved. can delete it now.
1871
						$this->sfwp_transients->delete( esc_attr( $post_data['mapping_error_transient'] ) );
1872
					}
1873
					// then send the user to the list of fieldmaps.
1874
					$url = esc_url_raw( $post_data['redirect_url_success'] );
1875
				}
1876
			}
1877
			wp_safe_redirect( $url );
1878
			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...
1879
		}
1880
	}
1881
1882
	/**
1883
	 * Import a json file and use it for plugin data
1884
	 */
1885
	public function import_json_file() {
1886
1887
		if ( ! wp_verify_nonce( $_POST['object_sync_for_salesforce_nonce_import'], 'object_sync_for_salesforce_nonce_import' ) ) {
1888
			return;
1889
		}
1890
		if ( ! current_user_can( 'manage_options' ) ) {
1891
			return;
1892
		}
1893
		$path      = $_FILES['import_file']['name'];
1894
		$extension = pathinfo( $path, PATHINFO_EXTENSION );
1895
		if ( 'json' !== $extension ) {
1896
			wp_die( esc_html__( 'Please upload a valid .json file', 'object-sync-for-salesforce' ) );
1897
		}
1898
1899
		$import_file = $_FILES['import_file']['tmp_name'];
1900
		if ( empty( $import_file ) ) {
1901
			wp_die( esc_html__( 'Please upload a file to import', 'object-sync-for-salesforce' ) );
1902
		}
1903
1904
		// Retrieve the data from the file and convert the json object to an array.
1905
		$data = (array) json_decode( file_get_contents( $import_file ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
1906
1907
		$overwrite = isset( $_POST['overwrite'] ) ? esc_attr( $_POST['overwrite'] ) : '';
1908
		if ( true === filter_var( $overwrite, FILTER_VALIDATE_BOOLEAN ) ) {
1909
			if ( isset( $data['fieldmaps'] ) ) {
1910
				$fieldmaps = $this->mappings->get_fieldmaps();
1911
				foreach ( $fieldmaps as $fieldmap ) {
1912
					$id     = $fieldmap['id'];
1913
					$delete = $this->mappings->delete_fieldmap( $id );
1914
				}
1915
			}
1916
			if ( isset( $data['object_maps'] ) ) {
1917
				$object_maps = $this->mappings->get_all_object_maps();
1918
				foreach ( $object_maps as $object_map ) {
1919
					$id     = $object_map['id'];
1920
					$delete = $this->mappings->delete_object_map( $id );
1921
				}
1922
			}
1923
			if ( isset( $data['plugin_settings'] ) ) {
1924
				foreach ( $data['plugin_settings'] as $key => $value ) {
1925
					delete_option( $value['option_name'] );
1926
				}
1927
			}
1928
		}
1929
1930
		$success = true;
1931
1932
		if ( isset( $data['fieldmaps'] ) ) {
1933
			$successful_fieldmaps = array();
1934
			$error_fieldmaps      = array();
1935
			foreach ( $data['fieldmaps'] as $fieldmap ) {
1936
				unset( $fieldmap['id'] );
1937
				$create = $this->mappings->create_fieldmap( $fieldmap );
1938
				if ( false === $create ) {
1939
					$success = false;
1940
				}
1941
				if ( false === $create ) {
1942
					$error_fieldmaps[] = $object_map;
1943
				} else {
1944
					$successful_fieldmaps[] = $create;
1945
				}
1946
			}
1947
		}
1948
1949
		if ( isset( $data['object_maps'] ) ) {
1950
			$successful_object_maps = array();
1951
			$error_object_maps      = array();
1952
			foreach ( $data['object_maps'] as $object_map ) {
1953
				unset( $object_map['id'] );
1954
				if ( isset( $object_map['object_type'] ) ) {
1955
					$sf_sync_trigger = $this->mappings->sync_sf_create;
1956
					$create          = $this->pull->salesforce_pull_process_records( $object_map['object_type'], $object_map['salesforce_id'], $sf_sync_trigger );
1957
				} else {
1958
					$create = $this->mappings->create_object_map( $object_map );
1959
				}
1960
				if ( false === $create ) {
1961
					$error_object_maps[] = $object_map;
1962
				} else {
1963
					$successful_object_maps[] = $create;
1964
				}
1965
			}
1966
		}
1967
1968
		if ( isset( $data['plugin_settings'] ) ) {
1969
			foreach ( $data['plugin_settings'] as $key => $value ) {
1970
				update_option( $value['option_name'], maybe_unserialize( $value['option_value'] ), $value['autoload'] );
1971
			}
1972
		}
1973
1974
		if ( ! empty( $error_fieldmaps ) && ! empty( $error_object_maps ) ) {
1975
			$status = 'error';
1976
			if ( isset( $this->logging ) ) {
1977
				$logging = $this->logging;
1978
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
1979
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
0 ignored issues
show
Unused Code introduced by
The call to Object_Sync_Sf_Logging::__construct() has too many arguments starting with $this->wpdb. ( Ignorable by Annotation )

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

1979
				$logging = /** @scrutinizer ignore-call */ new Object_Sync_Sf_Logging( $this->wpdb, $this->version );

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
1980
			}
1981
1982
			$body = sprintf( esc_html__( 'These are the import items that were not able to save: ', 'object-sync-for-salesforce' ) . '<ul>' );
1983
			foreach ( $error_fieldmaps as $fieldmap ) {
1984
				$body .= sprintf(
1985
					// translators: placeholders are: 1) the fieldmap row ID, 2) the Salesforce object type, 3) the WordPress object type.
1986
					'<li>' . esc_html__( 'Fieldmap id (if it exists): %1$s. Salesforce object type: %2$s. WordPress object type: %3$s', 'object-sync-for-salesforce' ) . '</li>',
1987
					isset( $fieldmap['id'] ) ? absint( $fieldmap['id'] ) : '',
1988
					esc_attr( $fieldmap['salesforce_object'] ),
1989
					esc_attr( $fieldmap['wordpress_object'] )
1990
				);
1991
			}
1992
			foreach ( $error_object_maps as $mapping_object ) {
1993
				$body .= sprintf(
1994
					// translators: placeholders are: 1) the mapping object row ID, 2) the ID of the Salesforce object, 3) the WordPress object type.
1995
					'<li>' . esc_html__( 'Mapping object id (if it exists): %1$s. Salesforce Id: %2$s. WordPress object type: %3$s', 'object-sync-for-salesforce' ) . '</li>',
1996
					isset( $mapping_object['id'] ) ? absint( $mapping_object['id'] ) : '',
1997
					esc_attr( $mapping_object['salesforce_id'] ),
1998
					esc_attr( $mapping_object['wordpress_object'] )
1999
				);
2000
			}
2001
			$body .= sprintf( '</ul>' );
2002
2003
			$logging->setup(
2004
				sprintf(
2005
					// translators: %1$s is the log status.
2006
					esc_html__( '%1$s on import: some of the rows were unable to save. Read this post for details.', 'object-sync-for-salesforce' ),
2007
					ucfirst( esc_attr( $status ) )
2008
				),
2009
				$body,
2010
				0,
2011
				0,
2012
				$status
2013
			);
2014
		}
2015
2016
		if ( empty( $error_fieldmaps ) && empty( $error_object_maps ) && ( ! empty( $successful_fieldmaps ) || ! empty( $successful_object_maps ) ) ) {
2017
			$this->clear_cache( false );
2018
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=true' ) );
2019
			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...
2020
		} elseif ( ! empty( $error_fieldmaps ) && ! empty( $successful_fieldmaps ) ) {
2021
			$this->clear_cache( false );
2022
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=partial' ) );
2023
		} elseif ( ! empty( $error_object_maps ) && ! empty( $successful_object_maps ) ) {
2024
			$this->clear_cache( false );
2025
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=partial' ) );
2026
		} else {
2027
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=false' ) );
2028
			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...
2029
		}
2030
2031
	}
2032
2033
	/**
2034
	 * Create a json file for exporting
2035
	 */
2036
	public function export_json_file() {
2037
2038
		if ( ! wp_verify_nonce( $_POST['object_sync_for_salesforce_nonce_export'], 'object_sync_for_salesforce_nonce_export' ) ) {
2039
			return;
2040
		}
2041
		if ( ! current_user_can( 'manage_options' ) ) {
2042
			return;
2043
		}
2044
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
2045
		$export    = array();
2046
		if ( in_array( 'fieldmaps', $post_data['export'], true ) ) {
2047
			$export['fieldmaps'] = $this->mappings->get_fieldmaps();
2048
		}
2049
		if ( in_array( 'object_maps', $post_data['export'], true ) ) {
2050
			$export['object_maps'] = $this->mappings->get_all_object_maps();
2051
		}
2052
		if ( in_array( 'plugin_settings', $post_data['export'], true ) ) {
2053
			$wpdb                      = $this->wpdb;
2054
			$export_results            = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->base_prefix}options` WHERE option_name LIKE %s;", $wpdb->esc_like( $this->option_prefix ) . '%' ), ARRAY_A );
2055
			$export['plugin_settings'] = $export_results;
2056
		}
2057
		nocache_headers();
2058
		header( 'Content-Type: application/json; charset=utf-8' );
2059
		header( 'Content-Disposition: attachment; filename=object-sync-for-salesforce-data-export-' . gmdate( 'm-d-Y' ) . '.json' );
2060
		header( 'Expires: 0' );
2061
		echo wp_json_encode( $export );
0 ignored issues
show
Bug introduced by
Are you sure wp_json_encode($export) of type false|string can be used in echo? ( Ignorable by Annotation )

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

2061
		echo /** @scrutinizer ignore-type */ wp_json_encode( $export );
Loading history...
2062
		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...
2063
	}
2064
2065
	/**
2066
	 * Default display for <input> fields
2067
	 *
2068
	 * @param array $args is the arguments to create the field.
2069
	 */
2070
	public function display_input_field( $args ) {
2071
		$type    = $args['type'];
2072
		$id      = $args['label_for'];
2073
		$name    = $args['name'];
2074
		$desc    = $args['desc'];
2075
		$checked = '';
2076
2077
		$class = 'regular-text';
2078
2079
		if ( 'checkbox' === $type ) {
2080
			$class = 'checkbox';
2081
		}
2082
2083
		if ( isset( $args['class'] ) ) {
2084
			$class = $args['class'];
2085
		}
2086
2087
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2088
			$value = esc_attr( get_option( $id, '' ) );
0 ignored issues
show
Bug introduced by
It seems like get_option($id, '') can also be of type false; however, parameter $text of esc_attr() 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

2088
			$value = esc_attr( /** @scrutinizer ignore-type */ get_option( $id, '' ) );
Loading history...
2089
			if ( 'checkbox' === $type ) {
2090
				$value = filter_var( get_option( $id, false ), FILTER_VALIDATE_BOOLEAN );
2091
				if ( true === $value ) {
2092
					$checked = 'checked ';
2093
				}
2094
				$value = 1;
2095
			}
2096
			if ( '' === $value && isset( $args['default'] ) && '' !== $args['default'] ) {
2097
				$value = $args['default'];
2098
			}
2099
2100
			echo sprintf(
2101
				'<input type="%1$s" value="%2$s" name="%3$s" id="%4$s" class="%5$s"%6$s>',
2102
				esc_attr( $type ),
2103
				esc_attr( $value ),
2104
				esc_attr( $name ),
2105
				esc_attr( $id ),
2106
				sanitize_html_class( $class . esc_html( ' code' ) ),
2107
				esc_html( $checked )
2108
			);
2109
			if ( '' !== $desc ) {
2110
				echo sprintf(
2111
					'<p class="description">%1$s</p>',
2112
					esc_html( $desc )
2113
				);
2114
			}
2115
		} else {
2116
			echo sprintf(
2117
				'<p><code>%1$s</code></p>',
2118
				esc_html__( 'Defined in wp-config.php', 'object-sync-for-salesforce' )
2119
			);
2120
		}
2121
	}
2122
2123
	/**
2124
	 * Display for multiple checkboxes
2125
	 * Above method can handle a single checkbox as it is
2126
	 *
2127
	 * @param array $args is the arguments to create the checkboxes.
2128
	 */
2129
	public function display_checkboxes( $args ) {
2130
		$type    = 'checkbox';
2131
		$name    = $args['name'];
2132
		$options = get_option( $name, array() );
2133
		foreach ( $args['items'] as $key => $value ) {
2134
			$text    = $value['text'];
2135
			$id      = $value['id'];
2136
			$desc    = $value['desc'];
2137
			$checked = '';
2138
			if ( is_array( $options ) && in_array( (string) $key, $options, true ) ) {
2139
				$checked = 'checked';
2140
			} elseif ( is_array( $options ) && empty( $options ) ) {
2141
				if ( isset( $value['default'] ) && true === $value['default'] ) {
2142
					$checked = 'checked';
2143
				}
2144
			}
2145
			echo sprintf(
2146
				'<div class="checkbox"><label><input type="%1$s" value="%2$s" name="%3$s[]" id="%4$s"%5$s>%6$s</label></div>',
2147
				esc_attr( $type ),
2148
				esc_attr( $key ),
2149
				esc_attr( $name ),
2150
				esc_attr( $id ),
2151
				esc_html( $checked ),
2152
				esc_html( $text )
2153
			);
2154
			if ( '' !== $desc ) {
2155
				echo sprintf(
2156
					'<p class="description">%1$s</p>',
2157
					esc_html( $desc )
2158
				);
2159
			}
2160
		}
2161
	}
2162
2163
	/**
2164
	 * Display for a dropdown
2165
	 *
2166
	 * @param array $args is the arguments needed to create the dropdown.
2167
	 */
2168
	public function display_select( $args ) {
2169
		$type = $args['type'];
2170
		$id   = $args['label_for'];
2171
		$name = $args['name'];
2172
		$desc = $args['desc'];
2173
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2174
			$current_value = get_option( $name );
2175
2176
			echo sprintf(
2177
				'<div class="select"><select id="%1$s" name="%2$s"><option value="">- ' . esc_html__( 'Select one', 'object-sync-for-salesforce' ) . ' -</option>',
2178
				esc_attr( $id ),
2179
				esc_attr( $name )
2180
			);
2181
2182
			foreach ( $args['items'] as $key => $value ) {
2183
				$text     = $value['text'];
2184
				$value    = $value['value'];
2185
				$selected = '';
2186
				if ( $key === $current_value || $value === $current_value ) {
2187
					$selected = ' selected';
2188
				}
2189
2190
				echo sprintf(
2191
					'<option value="%1$s"%2$s>%3$s</option>',
2192
					esc_attr( $value ),
2193
					esc_attr( $selected ),
2194
					esc_html( $text )
2195
				);
2196
2197
			}
2198
			echo '</select>';
2199
			if ( '' !== $desc ) {
2200
				echo sprintf(
2201
					'<p class="description">%1$s</p>',
2202
					esc_html( $desc )
2203
				);
2204
			}
2205
			echo '</div>';
2206
		} else {
2207
			echo sprintf(
2208
				'<p><code>%1$s</code></p>',
2209
				esc_html__( 'Defined in wp-config.php', 'object-sync-for-salesforce' )
2210
			);
2211
		}
2212
	}
2213
2214
	/**
2215
	 * Dropdown formatted list of Salesforce API versions
2216
	 *
2217
	 * @return array $args is the array of API versions for the dropdown.
2218
	 */
2219
	private function version_options() {
2220
		$args = array();
2221
		if ( defined( 'OBJECT_SYNC_SF_SALESFORCE_API_VERSION' ) || ! isset( $_GET['page'] ) || sanitize_key( $_GET['page'] ) !== $this->admin_settings_url_param ) {
2222
			return $args;
2223
		}
2224
		$versions = $this->salesforce['sfapi']->get_api_versions();
2225
		foreach ( $versions['data'] as $key => $value ) {
2226
			$args[] = array(
2227
				'value' => $value['version'],
2228
				'text'  => $value['label'] . ' (' . $value['version'] . ')',
2229
			);
2230
		}
2231
		return $args;
2232
	}
2233
2234
	/**
2235
	 * Default display for <a href> links
2236
	 *
2237
	 * @param array $args is the arguments to make the link.
2238
	 */
2239
	public function display_link( $args ) {
2240
		$label = $args['label'];
2241
		$desc  = $args['desc'];
2242
		$url   = $args['url'];
2243
		if ( isset( $args['link_class'] ) ) {
2244
			echo sprintf(
2245
				'<p><a class="%1$s" href="%2$s">%3$s</a></p>',
2246
				esc_attr( $args['link_class'] ),
2247
				esc_url( $url ),
2248
				esc_html( $label )
2249
			);
2250
		} else {
2251
			echo sprintf(
2252
				'<p><a href="%1$s">%2$s</a></p>',
2253
				esc_url( $url ),
2254
				esc_html( $label )
2255
			);
2256
		}
2257
2258
		if ( '' !== $desc ) {
2259
			echo sprintf(
2260
				'<p class="description">%1$s</p>',
2261
				esc_html( $desc )
2262
			);
2263
		}
2264
2265
	}
2266
2267
	/**
2268
	 * Allow for a standard sanitize/validate method. We could use more specific ones if need be, but this one provides a baseline.
2269
	 *
2270
	 * @param string $option is the option value.
2271
	 * @return string $option is the sanitized option value.
2272
	 */
2273
	public function sanitize_validate_text( $option ) {
2274
		if ( is_array( $option ) ) {
0 ignored issues
show
introduced by
The condition is_array($option) is always false.
Loading history...
2275
			$options = array();
2276
			foreach ( $option as $key => $value ) {
2277
				$options[ $key ] = sanitize_text_field( $value );
2278
			}
2279
			return $options;
2280
		}
2281
		$option = sanitize_text_field( $option );
2282
		return $option;
2283
	}
2284
2285
	/**
2286
	 * Run a demo of Salesforce API call on the authenticate tab after WordPress has authenticated with it
2287
	 *
2288
	 * @param object $sfapi this is the Salesforce API object.
2289
	 */
2290
	private function status( $sfapi ) {
2291
2292
		$versions = $sfapi->get_api_versions();
2293
2294
		// format this array into text so users can see the versions.
2295
		if ( true === $versions['cached'] ) {
2296
			$versions_is_cached = esc_html__( 'This list is cached, and', 'object-sync-for-salesforce' );
2297
		} else {
2298
			$versions_is_cached = esc_html__( 'This list is not cached, but', 'object-sync-for-salesforce' );
2299
		}
2300
2301
		if ( true === $versions['from_cache'] ) {
2302
			$versions_from_cache = esc_html__( 'items were loaded from the cache', 'object-sync-for-salesforce' );
2303
		} else {
2304
			$versions_from_cache = esc_html__( 'items were not loaded from the cache', 'object-sync-for-salesforce' );
2305
		}
2306
2307
		$versions_apicall_summary = sprintf(
2308
			// translators: 1) $versions_is_cached is the "This list is/is not cached, and/but" line, 2) $versions_from_cache is the "items were/were not loaded from the cache" line.
2309
			esc_html__( 'Available Salesforce API versions. %1$s %2$s. This is not an authenticated request, so it does not touch the Salesforce token.', 'object-sync-for-salesforce' ),
2310
			$versions_is_cached,
2311
			$versions_from_cache
2312
		);
2313
2314
		$contacts = $sfapi->query( 'SELECT Name, Id from Contact LIMIT 100' );
2315
2316
		// format this array into html so users can see the contacts.
2317
		if ( true === $contacts['cached'] ) {
2318
			$contacts_is_cached = esc_html__( 'They are cached, and', 'object-sync-for-salesforce' );
2319
		} else {
2320
			$contacts_is_cached = esc_html__( 'They are not cached, but', 'object-sync-for-salesforce' );
2321
		}
2322
2323
		if ( true === $contacts['from_cache'] ) {
2324
			$contacts_from_cache = esc_html__( 'they were loaded from the cache', 'object-sync-for-salesforce' );
2325
		} else {
2326
			$contacts_from_cache = esc_html__( 'they were not loaded from the cache', 'object-sync-for-salesforce' );
2327
		}
2328
2329
		if ( true === $contacts['is_redo'] ) {
2330
			$contacts_refreshed_token = esc_html__( 'This request did require refreshing the Salesforce token', 'object-sync-for-salesforce' );
2331
		} else {
2332
			$contacts_refreshed_token = esc_html__( 'This request did not require refreshing the Salesforce token', 'object-sync-for-salesforce' );
2333
		}
2334
2335
		// display contact summary if there are any contacts.
2336
		if ( 0 < absint( $contacts['data']['totalSize'] ) ) {
2337
			$contacts_apicall_summary = sprintf(
2338
				// translators: 1) $contacts['data']['totalSize'] is the number of items loaded, 2) $contacts['data']['records'][0]['attributes']['type'] is the name of the Salesforce object, 3) $contacts_is_cached is the "They are/are not cached, and/but" line, 4) $contacts_from_cache is the "they were/were not loaded from the cache" line, 5) is the "this request did/did not require refreshing the Salesforce token" line.
2339
				esc_html__( 'Salesforce successfully returned %1$s %2$s records. %3$s %4$s. %5$s.', 'object-sync-for-salesforce' ),
2340
				absint( $contacts['data']['totalSize'] ),
2341
				esc_html( $contacts['data']['records'][0]['attributes']['type'] ),
2342
				$contacts_is_cached,
2343
				$contacts_from_cache,
2344
				$contacts_refreshed_token
2345
			);
2346
		} else {
2347
			$contacts_apicall_summary = '';
2348
		}
2349
2350
		require_once plugin_dir_path( $this->file ) . '/templates/admin/status.php';
2351
2352
	}
2353
2354
	/**
2355
	 * Deauthorize WordPress from Salesforce.
2356
	 * This deletes the tokens from the database; it does not currently do anything in Salesforce
2357
	 * For this plugin at this time, that is the decision we are making: don't do any kind of authorization stuff inside Salesforce
2358
	 */
2359
	private function logout() {
2360
		$delete_access_token = delete_option( $this->option_prefix . 'access_token' );
2361
		if ( true === $delete_access_token ) {
2362
			$this->access_token = '';
2363
		}
2364
		$delete_instance_url = delete_option( $this->option_prefix . 'instance_url' );
2365
		if ( true === $delete_instance_url ) {
2366
			$this->instance_url = '';
2367
		}
2368
		$delete_refresh_token = delete_option( $this->option_prefix . 'refresh_token' );
2369
		if ( true === $delete_refresh_token ) {
2370
			$this->refresh_token = '';
2371
		}
2372
		echo sprintf(
2373
			'<p>You have been logged out. You can use the <a href="%1$s">%2$s</a> tab to log in again.</p>',
2374
			esc_url( get_admin_url( null, 'options-general.php?page' . $this->admin_settings_url_param . '&tab=authorize' ) ),
2375
			esc_html__( 'Authorize', 'object-sync-for-salesforce' )
2376
		);
2377
	}
2378
2379
	/**
2380
	 * Ajax call to clear the plugin cache.
2381
	 */
2382
	public function clear_sfwp_cache() {
2383
		$result   = $this->clear_cache( true );
2384
		$response = array(
2385
			'message' => $result['message'],
2386
			'success' => $result['success'],
2387
		);
2388
		wp_send_json_success( $response );
2389
	}
2390
2391
	/**
2392
	 * Clear the plugin's cache.
2393
	 * This uses the flush method contained in the WordPress cache to clear all of this plugin's cached data.
2394
	 *
2395
	 * @param bool $ajax Whether this is an Ajax request or not.
2396
	 * @return array
2397
	 */
2398
	private function clear_cache( $ajax = false ) {
2399
		$result  = $this->wordpress->sfwp_transients->flush();
2400
		$success = $result['success'];
2401
		if ( 0 < $result['count'] ) {
2402
			if ( true === $success ) {
2403
				$message = __( 'The plugin cache has been cleared.', 'object-sync-for-salesforce' );
2404
			} else {
2405
				$message = __( 'There was an error clearing the plugin cache. Try refreshing this page.', 'object-sync-for-salesforce' );
2406
			}
2407
		} else {
2408
			$success = true;
2409
			$message = __( 'The cache was not cleared because it is empty. You can try again later.', 'object-sync-for-salesforce' );
2410
		}
2411
		if ( false === $ajax ) {
2412
			echo '<p>' . esc_html( $message ) . '</p>';
2413
		} else {
2414
			return array(
2415
				'message' => esc_html( $message ),
2416
				'success' => $success,
2417
			);
2418
		}
2419
	}
2420
2421
	/**
2422
	 * Check WordPress Admin permissions
2423
	 * Check if the current user is allowed to access the Salesforce plugin options
2424
	 */
2425
	private function check_wordpress_admin_permissions() {
2426
2427
		// one programmatic way to give this capability to additional user roles is the
2428
		// object_sync_for_salesforce_roles_configure_salesforce hook
2429
		// it runs on activation of this plugin, and will assign the below capability to any role
2430
		// coming from the hook.
2431
2432
		// alternatively, other roles can get this capability in whatever other way you like
2433
		// point is: to administer this plugin, you need this capability.
2434
2435
		if ( ! current_user_can( 'configure_salesforce' ) ) {
2436
			return false;
2437
		} else {
2438
			return true;
2439
		}
2440
2441
	}
2442
2443
	/**
2444
	 * Show what we know about this user's relationship to a Salesforce object, if any
2445
	 *
2446
	 * @param object $user this is the user object from WordPress.
2447
	 */
2448
	public function show_salesforce_user_fields( $user ) {
2449
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
2450
		if ( true === $this->check_wordpress_admin_permissions() ) {
2451
			$mappings = $this->mappings->load_all_by_wordpress( 'user', $user->ID );
2452
			$fieldmap = $this->mappings->get_fieldmaps(
2453
				null, // id field must be null for multiples.
2454
				array(
2455
					'wordpress_object' => 'user',
2456
				)
2457
			);
2458
			if ( count( $mappings ) > 0 ) {
2459
				foreach ( $mappings as $mapping ) {
2460
					if ( isset( $mapping['id'] ) && ! isset( $get_data['edit_salesforce_mapping'] ) && ! isset( $get_data['delete_salesforce_mapping'] ) ) {
2461
						require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce.php';
2462
					} elseif ( ! empty( $fieldmap ) ) { // is the user mapped to something already?
2463
						if ( isset( $get_data['edit_salesforce_mapping'] ) && true === filter_var( $get_data['edit_salesforce_mapping'], FILTER_VALIDATE_BOOLEAN ) ) {
2464
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-change.php';
2465
						} elseif ( isset( $get_data['delete_salesforce_mapping'] ) && true === filter_var( $get_data['delete_salesforce_mapping'], FILTER_VALIDATE_BOOLEAN ) ) {
2466
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-delete.php';
2467
						} else {
2468
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-map.php';
2469
						}
2470
					}
2471
				}
2472
			} else {
2473
				require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-map.php';
2474
			}
2475
		}
2476
	}
2477
2478
	/**
2479
	 * If the user profile has been mapped to Salesforce, do it
2480
	 *
2481
	 * @param int $user_id the ID of the WordPress user.
2482
	 */
2483
	public function save_salesforce_user_fields( $user_id ) {
2484
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
2485
		if ( isset( $post_data['salesforce_update_mapped_user'] ) && true === filter_var( $post_data['salesforce_update_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2486
			$mapping_objects = $this->mappings->get_all_object_maps(
2487
				array(
2488
					'wordpress_id'     => $user_id,
2489
					'wordpress_object' => 'user',
2490
				)
2491
			);
2492
			foreach ( $mapping_objects as $mapping_object ) {
2493
				$mapping_object['salesforce_id'] = $post_data['salesforce_id'];
2494
				$result                          = $this->mappings->update_object_map( $mapping_object, $mapping_object['id'] );
2495
			}
2496
		} elseif ( isset( $post_data['salesforce_create_mapped_user'] ) && true === filter_var( $post_data['salesforce_create_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2497
			// if a Salesforce ID was entered.
2498
			if ( isset( $post_data['salesforce_id'] ) && ! empty( $post_data['salesforce_id'] ) ) {
2499
				$mapping_object = $this->create_object_map( $user_id, 'user', $post_data['salesforce_id'] );
2500
			} elseif ( isset( $post_data['push_new_user_to_salesforce'] ) ) {
2501
				// otherwise, create a new record in Salesforce.
2502
				$result = $this->push_to_salesforce( 'user', $user_id );
2503
			}
2504
		} elseif ( isset( $post_data['salesforce_delete_mapped_user'] ) && true === filter_var( $post_data['salesforce_delete_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2505
			// if a Salesforce ID was entered.
2506
			if ( isset( $post_data['mapping_id'] ) && ! empty( $post_data['mapping_id'] ) ) {
2507
				$delete = $this->mappings->delete_object_map( $post_data['mapping_id'] );
2508
			}
2509
		}
2510
	}
2511
2512
	/**
2513
	 * Render tabs for settings pages in admin
2514
	 *
2515
	 * @param array  $tabs is the tabs for the settings menu.
2516
	 * @param string $tab is a single tab.
2517
	 */
2518
	private function tabs( $tabs, $tab = '' ) {
2519
2520
		$get_data        = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
2521
		$consumer_key    = $this->login_credentials['consumer_key'];
2522
		$consumer_secret = $this->login_credentials['consumer_secret'];
2523
		$callback_url    = $this->login_credentials['callback_url'];
2524
2525
		$current_tab = $tab;
2526
		echo '<h2 class="nav-tab-wrapper">';
2527
		foreach ( $tabs as $tab_key => $tab_caption ) {
2528
			$active = $current_tab === $tab_key ? ' nav-tab-active' : '';
2529
2530
			if ( true === $this->salesforce['is_authorized'] ) {
2531
				echo sprintf(
2532
					'<a class="nav-tab%1$s" href="%2$s">%3$s</a>',
2533
					esc_attr( $active ),
2534
					esc_url( '?page=' . $this->admin_settings_url_param . '&tab=' . $tab_key ),
2535
					esc_html( $tab_caption )
2536
				);
2537
			} elseif ( 'settings' === $tab_key || ( 'authorize' === $tab_key && isset( $consumer_key ) && isset( $consumer_secret ) && ! empty( $consumer_key ) && ! empty( $consumer_secret ) ) ) {
2538
				echo sprintf(
2539
					'<a class="nav-tab%1$s" href="%2$s">%3$s</a>',
2540
					esc_attr( $active ),
2541
					esc_url( '?page=' . $this->admin_settings_url_param . '&tab=' . $tab_key ),
2542
					esc_html( $tab_caption )
2543
				);
2544
			}
2545
		}
2546
		echo '</h2>';
2547
2548
		if ( isset( $get_data['tab'] ) ) {
2549
			$tab = sanitize_key( $get_data['tab'] );
2550
		} else {
2551
			$tab = '';
2552
		}
2553
	}
2554
2555
	/**
2556
	 * Clear schedule
2557
	 * This clears the schedule if the user clicks the button
2558
	 *
2559
	 * @param string $schedule_name is the name of the schedule being cleared.
2560
	 */
2561
	private function clear_schedule( $schedule_name = '' ) {
2562
		if ( '' !== $schedule_name ) {
2563
			$this->queue->cancel( $schedule_name );
2564
			// translators: $schedule_name is the name of the current queue. Defaults: salesforce_pull, salesforce_push, salesforce.
2565
			echo sprintf( esc_html__( 'You have cleared the %s schedule.', 'object-sync-for-salesforce' ), esc_html( $schedule_name ) );
2566
		} else {
2567
			echo esc_html__( 'You need to specify the name of the schedule you want to clear.', 'object-sync-for-salesforce' );
2568
		}
2569
	}
2570
2571
	/**
2572
	 * Get count of schedule items
2573
	 *
2574
	 * @param string $schedule_name is the name of the schedule.
2575
	 * @return int $count
2576
	 */
2577
	private function get_schedule_count( $schedule_name = '' ) {
2578
		if ( '' !== $schedule_name ) {
2579
			$count       = count(
2580
				$this->queue->search(
2581
					array(
2582
						'group'  => $schedule_name,
2583
						'status' => ActionScheduler_Store::STATUS_PENDING,
2584
					),
2585
					'ARRAY_A'
2586
				)
2587
			);
2588
			$group_count = count(
2589
				$this->queue->search(
2590
					array(
2591
						'group'  => $schedule_name . $this->action_group_suffix,
2592
						'status' => ActionScheduler_Store::STATUS_PENDING,
2593
					),
2594
					'ARRAY_A'
2595
				)
2596
			);
2597
			return $count + $group_count;
2598
		} else {
2599
			return 0;
2600
		}
2601
	}
2602
2603
	/**
2604
	 * Create an object map between a WordPress object and a Salesforce object
2605
	 *
2606
	 * @param int    $wordpress_id Unique identifier for the WordPress object.
2607
	 * @param string $wordpress_object What kind of object is it.
2608
	 * @param string $salesforce_id Unique identifier for the Salesforce object.
2609
	 * @param string $action Did we push or pull.
2610
	 * @return int   $wpdb->insert_id This is the database row for the map object
2611
	 */
2612
	private function create_object_map( $wordpress_id, $wordpress_object, $salesforce_id, $action = '' ) {
2613
		// Create object map and save it.
2614
		$mapping_object = $this->mappings->create_object_map(
2615
			array(
2616
				'wordpress_id'      => $wordpress_id, // wordpress unique id.
2617
				'salesforce_id'     => $salesforce_id, // salesforce unique id. we don't care what kind of object it is at this point.
2618
				'wordpress_object'  => $wordpress_object, // keep track of what kind of wp object this is.
2619
				'last_sync'         => current_time( 'mysql' ),
2620
				'last_sync_action'  => $action,
2621
				'last_sync_status'  => $this->mappings->status_success,
2622
				'last_sync_message' => __( 'Mapping object updated via function: ', 'object-sync-for-salesforce' ) . __FUNCTION__,
2623
			)
2624
		);
2625
2626
		return $mapping_object;
2627
2628
	}
2629
2630
}
2631