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

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

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

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

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

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

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

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

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

2063
		echo /** @scrutinizer ignore-type */ wp_json_encode( $export );
Loading history...
2064
		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...
2065
	}
2066
2067
	/**
2068
	 * Default display for <input> fields
2069
	 *
2070
	 * @param array $args is the arguments to create the field.
2071
	 */
2072
	public function display_input_field( $args ) {
2073
		$type    = $args['type'];
2074
		$id      = $args['label_for'];
2075
		$name    = $args['name'];
2076
		$desc    = $args['desc'];
2077
		$checked = '';
2078
2079
		$class = 'regular-text';
2080
2081
		if ( 'checkbox' === $type ) {
2082
			$class = 'checkbox';
2083
		}
2084
2085
		if ( isset( $args['class'] ) ) {
2086
			$class = $args['class'];
2087
		}
2088
2089
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2090
			$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

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