Passed
Pull Request — master (#404)
by Jonathan
03:28 queued 11s
created

Object_Sync_Sf_Admin   F

Complexity

Total Complexity 330

Size/Duplication

Total Lines 2587
Duplicated Lines 0 %

Importance

Changes 11
Bugs 2 Features 0
Metric Value
wmc 330
eloc 1462
c 11
b 2
f 0
dl 0
loc 2587
rs 0.8

45 Methods

Rating   Name   Duplication   Size   Complexity  
A fields_fieldmaps() 0 2 1
A fields_errors() 0 37 2
C notices() 0 77 11
C get_salesforce_object_description() 0 56 17
D get_salesforce_object_fields() 0 48 17
A get_wordpress_object_fields() 0 17 4
A set_action_schedule() 0 20 2
A add_actions() 0 52 2
A plugin_action_links() 0 6 2
A create_admin_menu() 0 3 1
A __construct() 0 37 2
A admin_scripts_and_styles() 0 26 2
A change_action_schedule() 0 10 1
A initial_action_schedule() 0 24 2
A salesforce_settings_forms() 0 22 3
F show_admin_page() 0 220 54
A clear_schedule() 0 7 2
A delete_fieldmap() 0 11 3
C delete_object_map() 0 47 12
C prepare_fieldmap_data() 0 51 14
C save_salesforce_user_fields() 0 25 13
A pull_from_salesforce() 0 12 6
B export_json_file() 0 27 6
B display_select() 0 42 7
F import_json_file() 0 121 30
A get_schedule_count() 0 23 2
B push_to_salesforce() 0 24 10
B status() 0 61 7
A clear_cache() 0 19 4
A display_link() 0 23 3
B display_checkboxes() 0 29 9
A clear_sfwp_cache() 0 7 1
B prepare_object_map_data() 0 38 10
A check_wordpress_admin_permissions() 0 14 2
A refresh_mapped_data() 0 22 5
B tabs() 0 34 11
C fields_settings() 0 286 8
C show_salesforce_user_fields() 0 26 12
A create_object_map() 0 15 1
A sanitize_validate_text() 0 10 3
A version_options() 0 13 5
A logout() 0 17 4
B display_input_field() 0 49 11
B fields_scheduling() 0 106 4
B fields_log_settings() 0 186 2

How to fix   Complexity   

Complex Class

Complex classes like Object_Sync_Sf_Admin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Object_Sync_Sf_Admin, and based on these observations, apply Extract Interface, too.

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

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

505
						$data          = esc_html( /** @scrutinizer ignore-type */ wp_unslash( $get_data['code'] ) );
Loading history...
506
						$is_authorized = $this->salesforce['sfapi']->request_token( $data );
507
						?>
508
						<script>window.location = '<?php echo esc_url_raw( $callback_url ); ?>'</script>
509
						<?php
510
					} elseif ( true === $this->salesforce['is_authorized'] ) {
511
							require_once plugin_dir_path( $this->file ) . '/templates/admin/authorized.php';
512
							$this->status( $this->salesforce['sfapi'] );
513
					} elseif ( true === is_object( $this->salesforce['sfapi'] ) && isset( $consumer_key ) && isset( $consumer_secret ) ) {
514
						?>
515
						<p><a class="button button-primary" href="<?php echo esc_url( $this->salesforce['sfapi']->get_authorization_code() ); ?>"><?php echo esc_html__( 'Connect to Salesforce', 'object-sync-for-salesforce' ); ?></a></p>
516
						<?php
517
					} else {
518
						$url    = esc_url( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=settings' ) );
519
						$anchor = esc_html__( 'Settings', 'object-sync-for-salesforce' );
520
						// translators: placeholders are for the settings tab link: 1) the url, and 2) the anchor text.
521
						$message = sprintf( esc_html__( 'Salesforce needs to be authorized to connect to this website but the credentials are missing. Use the <a href="%1$s">%2$s</a> tab to add them.', 'object-sync-for-salesforce' ), $url, $anchor );
522
						require_once plugin_dir_path( $this->file ) . '/templates/admin/error.php';
523
					}
524
					break;
525
				case 'fieldmaps':
526
					if ( isset( $get_data['method'] ) ) {
527
528
						$method      = sanitize_key( $get_data['method'] );
529
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps&method=' . $method );
530
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps' );
531
532
						$disable_mapped_fields = get_option( $this->option_prefix . 'disable_mapped_fields', false );
533
						$disable_mapped_fields = filter_var( $disable_mapped_fields, FILTER_VALIDATE_BOOLEAN );
534
						$fieldmap_class        = 'fieldmap';
535
						if ( true === $disable_mapped_fields ) {
536
							$fieldmap_class .= ' fieldmap-disable-mapped-fields';
537
						}
538
539
						if ( isset( $get_data['transient'] ) ) {
540
							$transient = sanitize_key( $get_data['transient'] );
541
							$posted    = $this->sfwp_transients->get( $transient );
542
						}
543
544
						if ( isset( $posted ) && is_array( $posted ) ) {
545
							$map = $posted;
546
						} elseif ( 'edit' === $method || 'clone' === $method || 'delete' === $method ) {
547
							$map = $this->mappings->get_fieldmaps( isset( $get_data['id'] ) ? sanitize_key( $get_data['id'] ) : '' );
548
						}
549
550
						if ( isset( $map ) && is_array( $map ) ) {
551
							$label                           = $map['label'];
552
							$salesforce_object               = $map['salesforce_object'];
553
							$salesforce_record_types_allowed = maybe_unserialize( $map['salesforce_record_types_allowed'] );
554
							$salesforce_record_type_default  = $map['salesforce_record_type_default'];
555
							$wordpress_object                = $map['wordpress_object'];
556
							$pull_trigger_field              = $map['pull_trigger_field'];
557
							$fieldmap_fields                 = $map['fields'];
558
							$sync_triggers                   = $map['sync_triggers'];
559
							$push_async                      = $map['push_async'];
560
							$push_drafts                     = $map['push_drafts'];
561
							$pull_to_drafts                  = $map['pull_to_drafts'];
562
							$weight                          = $map['weight'];
563
						}
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
						$fieldmaps = $this->mappings->get_fieldmaps();
572
						require_once plugin_dir_path( $this->file ) . '/templates/admin/fieldmaps-list.php';
573
					} // End if statement.
574
					break;
575
				case 'logout':
576
					$this->logout();
577
					break;
578
				case 'clear_cache':
579
					$this->clear_cache();
580
					break;
581
				case 'clear_schedule':
582
					if ( isset( $get_data['schedule_name'] ) ) {
583
						$schedule_name = sanitize_key( $get_data['schedule_name'] );
584
					}
585
					$this->clear_schedule( $schedule_name );
586
					break;
587
				case 'settings':
588
					require_once plugin_dir_path( $this->file ) . '/templates/admin/settings.php';
589
					break;
590
				case 'mapping_errors':
591
					if ( isset( $get_data['method'] ) ) {
592
593
						$method      = sanitize_key( $get_data['method'] );
594
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors&method=' . $method );
595
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors' );
596
597
						if ( isset( $get_data['map_transient'] ) ) {
598
							$transient = sanitize_key( $get_data['map_transient'] );
599
							$posted    = $this->sfwp_transients->get( $transient );
600
						}
601
602
						if ( isset( $posted ) && is_array( $posted ) ) {
603
							$map_row = $posted;
604
						} elseif ( 'edit' === $method || 'delete' === $method ) {
605
							$map_row = $this->mappings->get_failed_object_map( isset( $get_data['id'] ) ? sanitize_key( $get_data['id'] ) : '' );
606
						}
607
608
						if ( isset( $map_row ) && is_array( $map_row ) ) {
609
							$salesforce_id = $map_row['salesforce_id'];
610
							$wordpress_id  = $map_row['wordpress_id'];
611
						}
612
613
						if ( 'edit' === $method ) {
614
							require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors-edit.php';
615
						} elseif ( 'delete' === $method ) {
616
							require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors-delete.php';
617
						}
618
					} else {
619
620
						if ( isset( $get_data['mapping_error_transient'] ) ) {
621
							$transient = sanitize_key( $get_data['mapping_error_transient'] );
622
							$posted    = $this->sfwp_transients->get( $transient );
623
						}
624
625
						$ids_string = '';
626
						$ids        = array();
627
						if ( isset( $posted['delete'] ) ) {
628
							$ids_string = maybe_serialize( $posted['delete'] );
629
							$ids        = $posted['delete'];
630
						}
631
632
						$error_url   = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors&ids=' . $ids_string );
633
						$success_url = get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=mapping_errors' );
634
						require_once plugin_dir_path( $this->file ) . '/templates/admin/mapping-errors.php';
635
					}
636
					break;
637
				case 'import-export':
638
					require_once plugin_dir_path( $this->file ) . '/templates/admin/import-export.php';
639
					break;
640
				default:
641
					$include_settings = apply_filters( $this->option_prefix . 'settings_tab_include_settings', true, $tab );
642
					$content_before   = apply_filters( $this->option_prefix . 'settings_tab_content_before', null, $tab );
643
					$content_after    = apply_filters( $this->option_prefix . 'settings_tab_content_after', null, $tab );
644
					if ( null !== $content_before ) {
645
						echo esc_html( $content_before );
646
					}
647
					if ( true === $include_settings ) {
648
						require_once plugin_dir_path( $this->file ) . '/templates/admin/settings.php';
649
					}
650
					if ( null !== $content_after ) {
651
						echo esc_html( $content_after );
652
					}
653
					break;
654
			} // End switch statement.
655
		} catch ( SalesforceApiException $ex ) {
0 ignored issues
show
Bug introduced by
The type SalesforceApiException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

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

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

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

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

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

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

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

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

2035
		echo /** @scrutinizer ignore-type */ wp_json_encode( $export );
Loading history...
2036
		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...
2037
	}
2038
2039
	/**
2040
	 * Default display for <input> fields
2041
	 *
2042
	 * @param array $args is the arguments to create the field.
2043
	 */
2044
	public function display_input_field( $args ) {
2045
		$type    = $args['type'];
2046
		$id      = $args['label_for'];
2047
		$name    = $args['name'];
2048
		$desc    = $args['desc'];
2049
		$checked = '';
2050
2051
		$class = 'regular-text';
2052
2053
		if ( 'checkbox' === $type ) {
2054
			$class = 'checkbox';
2055
		}
2056
2057
		if ( isset( $args['class'] ) ) {
2058
			$class = $args['class'];
2059
		}
2060
2061
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2062
			$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

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