Passed
Push — 459-fix-wordpress-logging ( 1305d1...c79244 )
by Jonathan
08:55 queued 05:46
created

Object_Sync_Sf_Admin   F

Complexity

Total Complexity 357

Size/Duplication

Total Lines 2725
Duplicated Lines 0 %

Importance

Changes 19
Bugs 4 Features 0
Metric Value
wmc 357
eloc 1526
c 19
b 4
f 0
dl 0
loc 2725
rs 0.8

48 Methods

Rating   Name   Duplication   Size   Complexity  
A clear_schedule() 0 7 2
A check_wordpress_ssl() 0 25 6
C save_salesforce_user_fields() 0 25 13
B export_json_file() 0 27 6
B display_select() 0 42 7
A get_schedule_count() 0 23 2
A status() 0 39 5
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
A check_wordpress_ssl_support() 0 13 3
A check_wordpress_admin_permissions() 0 14 2
B tabs() 0 34 11
C show_salesforce_user_fields() 0 26 12
A create_object_map() 0 15 1
A sanitize_validate_text() 0 10 3
A logout() 0 17 4
B display_input_field() 0 49 11
A set_action_schedule() 0 20 2
A add_actions() 0 55 2
A plugin_action_links() 0 6 2
A __construct() 0 41 1
A admin_scripts_and_styles() 0 26 2
A change_action_schedule() 0 10 1
A initial_action_schedule() 0 24 2
A delete_fieldmap() 0 11 3
A salesforce_settings_forms() 0 22 3
C delete_object_map() 0 47 12
F show_admin_page() 0 220 58
C prepare_fieldmap_data() 0 51 14
B display_notices() 0 33 8
A pull_from_salesforce() 0 12 6
A create_admin_menu() 0 3 1
F import_json_file() 0 147 41
A fields_fieldmaps() 0 2 1
B push_to_salesforce() 0 24 10
C get_salesforce_object_description() 0 56 17
B notices_data() 0 82 7
B resave_action_schedules() 0 63 9
B prepare_object_map_data() 0 38 10
B fields_scheduling() 0 106 4
A fields_errors() 0 37 2
A refresh_mapped_data() 0 22 5
B fields_settings() 0 256 6
B fields_log_settings() 0 186 2
A get_wordpress_object_fields() 0 17 4
D get_salesforce_object_fields() 0 48 17

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
	 * Data for admin notices
138
	 *
139
	 * @var array
140
	 */
141
	public $notices_data;
142
143
	/**
144
	 * Salesforce access token
145
	 *
146
	 * @var string
147
	 */
148
	private $access_token;
149
150
	/**
151
	 * Salesforce instance URL
152
	 *
153
	 * @var string
154
	 */
155
	private $instance_url;
156
157
	/**
158
	 * Salesforce refresh token
159
	 *
160
	 * @var string
161
	 */
162
	private $refresh_token;
163
164
	/**
165
	 * Default path for the Salesforce authorize URL
166
	 *
167
	 * @var string
168
	 */
169
	public $default_authorize_url_path;
170
171
	/**
172
	 * Default path for the Salesforce token URL
173
	 *
174
	 * @var string
175
	 */
176
	public $default_token_url_path;
177
178
	/**
179
	 * What version of the Salesforce API should be the default on the settings screen.
180
	 * Users can edit what version is used, but they won't see a correct list of all their available versions until WordPress has
181
	 * been authenticated with Salesforce.
182
	 *
183
	 * @var string
184
	 * @deprecated as of 2.2.0; will be removed in version 3.0. This property will stay until 3.0.0 because it is a public value and it could be accessed by other code.
185
	 */
186
	public $default_api_version;
187
188
	/**
189
	 * Default max number of pull records. Users can edit this.
190
	 *
191
	 * @var int
192
	 */
193
	public $default_pull_limit;
194
195
	/**
196
	 * Default throttle for how often to pull from Salesforce. Users can edit this.
197
	 *
198
	 * @var int
199
	 */
200
	public $default_pull_throttle;
201
202
	/**
203
	 * Default for whether to limit to triggerable items. Users can edit this.
204
	 *
205
	 * @var bool
206
	 */
207
	public $default_triggerable;
208
209
	/**
210
	 * Default for whether to limit to items that can be updated. Users can edit this.
211
	 *
212
	 * @var bool
213
	 */
214
	public $default_updateable;
215
216
	/**
217
	 * Constructor for admin class
218
	 */
219
	public function __construct() {
220
		$this->version             = object_sync_for_salesforce()->version;
221
		$this->file                = object_sync_for_salesforce()->file;
222
		$this->wpdb                = object_sync_for_salesforce()->wpdb;
223
		$this->slug                = object_sync_for_salesforce()->slug;
224
		$this->option_prefix       = object_sync_for_salesforce()->option_prefix;
225
		$this->action_group_suffix = object_sync_for_salesforce()->action_group_suffix;
226
227
		$this->login_credentials   = object_sync_for_salesforce()->login_credentials;
228
		$this->wordpress           = object_sync_for_salesforce()->wordpress;
229
		$this->salesforce          = object_sync_for_salesforce()->salesforce;
230
		$this->mappings            = object_sync_for_salesforce()->mappings;
231
		$this->push                = object_sync_for_salesforce()->push;
232
		$this->pull                = object_sync_for_salesforce()->pull;
233
		$this->logging             = object_sync_for_salesforce()->logging;
234
		$this->schedulable_classes = object_sync_for_salesforce()->schedulable_classes;
235
		$this->queue               = object_sync_for_salesforce()->queue;
236
237
		// set the Salesforce API version.
238
		// as of version 2.2.0, this is set by the plugin and is not configurable in the interface.
239
		// this class variable will be removed in 3.0.0.
240
		$this->default_api_version = $this->login_credentials['rest_api_version'];
0 ignored issues
show
Deprecated Code introduced by
The property Object_Sync_Sf_Admin::$default_api_version has been deprecated: as of 2.2.0; will be removed in version 3.0. This property will stay until 3.0.0 because it is a public value and it could be accessed by other code. ( Ignorable by Annotation )

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

240
		/** @scrutinizer ignore-deprecated */ $this->default_api_version = $this->login_credentials['rest_api_version'];

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
241
242
		$this->sfwp_transients          = object_sync_for_salesforce()->wordpress->sfwp_transients;
243
		$this->admin_settings_url_param = 'object-sync-salesforce-admin';
244
		$this->notices_data             = $this->notices_data();
245
246
		// default authorize url path.
247
		$this->default_authorize_url_path = '/services/oauth2/authorize';
248
		// default token url path.
249
		$this->default_token_url_path = '/services/oauth2/token';
250
		// default pull record limit.
251
		$this->default_pull_limit = 25;
252
		// default pull throttle for avoiding going over api limits.
253
		$this->default_pull_throttle = 5;
254
		// default setting for triggerable items.
255
		$this->default_triggerable = true;
256
		// default setting for updateable items.
257
		$this->default_updateable = true;
258
259
		$this->add_actions();
260
	}
261
262
	/**
263
	 * Create the action hooks to create the admin pages.
264
	 */
265
	public function add_actions() {
266
267
		// settings link.
268
		add_filter( 'plugin_action_links', array( $this, 'plugin_action_links' ), 10, 5 );
269
270
		// CSS and Javascript.
271
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts_and_styles' ) );
272
273
		// Settings API forms and notices.
274
		add_action( 'admin_menu', array( $this, 'create_admin_menu' ) );
275
		add_action( 'admin_init', array( $this, 'salesforce_settings_forms' ) );
276
		add_action( 'admin_init', array( $this, 'display_notices' ) );
277
		add_action( 'admin_post_post_fieldmap', array( $this, 'prepare_fieldmap_data' ) );
278
		add_action( 'admin_post_delete_fieldmap', array( $this, 'delete_fieldmap' ) );
279
280
		// Ajax for fieldmap forms.
281
		add_action( 'wp_ajax_get_salesforce_object_description', array( $this, 'get_salesforce_object_description' ), 10, 1 );
282
		add_action( 'wp_ajax_get_salesforce_object_fields', array( $this, 'get_salesforce_object_fields' ), 10, 1 );
283
		add_action( 'wp_ajax_get_wordpress_object_fields', array( $this, 'get_wordpress_object_fields' ), 10, 1 );
284
285
		// Ajax events that can be manually called.
286
		add_action( 'wp_ajax_push_to_salesforce', array( $this, 'push_to_salesforce' ), 10, 3 );
287
		add_action( 'wp_ajax_pull_from_salesforce', array( $this, 'pull_from_salesforce' ), 10, 2 );
288
		add_action( 'wp_ajax_refresh_mapped_data', array( $this, 'refresh_mapped_data' ), 10, 1 );
289
		add_action( 'wp_ajax_clear_sfwp_cache', array( $this, 'clear_sfwp_cache' ) );
290
291
		// we add a Salesforce box on user profiles.
292
		add_action( 'edit_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
293
		add_action( 'show_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
294
295
		// and we can update Salesforce fields on the user profile box.
296
		add_action( 'personal_options_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
297
		add_action( 'edit_user_profile_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
298
299
		// when either field for schedule settings changes.
300
		foreach ( $this->schedulable_classes as $key => $value ) {
301
			// if the user doesn't have any action schedule tasks, let's not leave them empty.
302
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'initial_action_schedule' ), 10, 3 );
303
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'initial_action_schedule' ), 10, 3 );
304
305
			// this is if the user is changing their tasks.
306
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'change_action_schedule' ), 10, 3 );
307
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'change_action_schedule' ), 10, 3 );
308
		}
309
310
		// when ActionScheduler runs its migration, resave the schedule options.
311
		add_action( 'action_scheduler/migration_complete', array( $this, 'resave_action_schedules' ) );
312
313
		// handle post requests for object maps.
314
		add_action( 'admin_post_delete_object_map', array( $this, 'delete_object_map' ) );
315
		add_action( 'admin_post_post_object_map', array( $this, 'prepare_object_map_data' ) );
316
317
		// import and export plugin data.
318
		add_action( 'admin_post_object_sync_for_salesforce_import', array( $this, 'import_json_file' ) );
319
		add_action( 'admin_post_object_sync_for_salesforce_export', array( $this, 'export_json_file' ) );
320
321
	}
322
323
	/**
324
	 * Display a Settings link on the main Plugins page
325
	 *
326
	 * @param array  $links the array of links for the main plugins page.
327
	 * @param string $file the filename.
328
	 * @return array $links the array of links for the main plugins page
329
	 */
330
	public function plugin_action_links( $links, $file ) {
331
		if ( plugin_basename( $this->file ) === $file ) {
332
			$settings = '<a href="' . get_admin_url() . 'options-general.php?page=' . $this->admin_settings_url_param . '">' . __( 'Settings', 'object-sync-for-salesforce' ) . '</a>';
333
			array_unshift( $links, $settings );
334
		}
335
		return $links;
336
	}
337
338
	/**
339
	 * Admin styles. Load the CSS and JavaScript for the plugin's settings
340
	 */
341
	public function admin_scripts_and_styles() {
342
343
		// Developers might not want to bother with select2 or selectwoo, so we allow that to be changeable.
344
		$select_library = apply_filters( $this->option_prefix . 'select_library', 'selectwoo' );
345
346
		/*
347
		 * example to modify the select library
348
		 * add_filter( 'object_sync_for_salesforce_select_library', 'select_library', 10, 1 );
349
		 * function select_library( $select_library ) {
350
		 * 	$select_library = 'select2';
351
		 *  // this could also be empty; in that case we would just use default browser select
352
		 * 	return $select_library;
353
		 * }
354
		*/
355
356
		$javascript_dependencies = array( 'jquery' );
357
		$css_dependencies        = array();
358
		if ( '' !== $select_library ) {
359
			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 );
360
			$javascript_dependencies[] = $select_library . 'js';
361
			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' );
362
			$css_dependencies[] = $select_library . 'css';
363
		}
364
365
		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 );
366
		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' );
367
	}
368
369
	/**
370
	 * Initial recurring tasks for ActionScheduler
371
	 *
372
	 * @param string $new_schedule the new, unserialized option value.
373
	 * @param string $old_schedule the old option value.
374
	 * @param string $option_name option name.
375
	 * @return string $new_schedule
376
	 */
377
	public function initial_action_schedule( $new_schedule, $old_schedule, $option_name ) {
378
379
		// get the current schedule name from the task, based on pattern in the foreach.
380
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
381
		$schedule_name     = $matches[1];
382
		$action_group_name = $schedule_name . $this->action_group_suffix;
383
384
		// make sure there are no tasks already.
385
		$current_tasks = as_get_scheduled_actions(
386
			array(
387
				'hook'  => $this->schedulable_classes[ $schedule_name ]['initializer'],
388
				'group' => $action_group_name,
389
			),
390
			ARRAY_A
391
		);
392
393
		// exit if there are already tasks; they'll be saved if the option data changed.
394
		if ( ! empty( $current_tasks ) ) {
395
			return $new_schedule;
396
		}
397
398
		$this->set_action_schedule( $schedule_name, $action_group_name );
399
400
		return $new_schedule;
401
402
	}
403
404
	/**
405
	 * Update recurring tasks for ActionScheduler if options change
406
	 *
407
	 * @param string $old_schedule the old option value.
408
	 * @param string $new_schedule the new, unserialized option value.
409
	 * @param string $option_name option name.
410
	 */
411
	public function change_action_schedule( $old_schedule, $new_schedule, $option_name ) {
412
413
		// this method does not run if the option's data is unchanged.
414
415
		// get the current schedule name from the task, based on pattern in the foreach.
416
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
417
		$schedule_name     = $matches[1];
418
		$action_group_name = $schedule_name . $this->action_group_suffix;
419
420
		$this->set_action_schedule( $schedule_name, $action_group_name );
421
422
	}
423
424
	/**
425
	 * Set up recurring tasks for ActionScheduler
426
	 *
427
	 * @param string $schedule_name the name of the schedule.
428
	 * @param string $action_group_name the group's name.
429
	 */
430
	private function set_action_schedule( $schedule_name, $action_group_name ) {
431
		// exit if there is no initializer property on this schedule.
432
		if ( ! isset( $this->schedulable_classes[ $schedule_name ]['initializer'] ) ) {
433
			return;
434
		}
435
436
		// cancel previous task.
437
		$this->queue->cancel(
438
			$this->schedulable_classes[ $schedule_name ]['initializer'],
439
			array(),
440
			$action_group_name
441
		);
442
443
		// create new recurring task for ActionScheduler to check for data to pull from Salesforce.
444
		$this->queue->schedule_recurring(
445
			time(), // plugin seems to expect UTC.
446
			$this->queue->get_frequency( $schedule_name, 'seconds' ),
447
			$this->schedulable_classes[ $schedule_name ]['initializer'],
448
			array(),
449
			$action_group_name
450
		);
451
	}
452
453
	/**
454
	 * When it finishes its migration, resave the scheduled tasks for ActionScheduler.
455
	 */
456
	public function resave_action_schedules() {
457
		// for each schedulable action, go ahead and resave it.
458
		$schedules_updated  = array();
459
		$schedules_restored = array();
460
		foreach ( $this->schedulable_classes as $key => $value ) {
461
			// make sure it has an initializer property; this is used on recurring tasks.
462
			if ( isset( $value['initializer'] ) ) {
463
				// toggle the schedule number setting.
464
				$schedule_option_name  = $this->option_prefix . $key . '_schedule_number';
465
				$previous_option_value = get_option( $schedule_option_name, 0 );
466
				$previous_option_value = filter_var( $previous_option_value, FILTER_SANITIZE_NUMBER_INT );
467
				$new_option_value      = $previous_option_value + 1;
468
				$schedule_updated      = update_option( $schedule_option_name, $new_option_value );
469
				if ( true === $schedule_updated ) {
470
					$schedules_updated[] = $key;
471
					$schedule_restored   = update_option( $schedule_option_name, $previous_option_value );
472
					if ( true === $schedule_restored ) {
473
						$schedules_restored[] = $key;
474
					}
475
				}
476
			}
477
		}
478
479
		// create a log entry from the updated scheduled tasks.
480
		if ( ! empty( $schedules_updated ) || ! empty( $schedules_restored ) ) {
481
			$status = 'success';
482
		} else {
483
			$status = 'error';
484
		}
485
		$body = sprintf( esc_html__( 'These are the scheduled tasks that were updated: ', 'object-sync-for-salesforce' ) . '<ul>' );
486
		foreach ( $schedules_updated as $schedule_updated ) {
487
			$body .= sprintf(
488
				// translators: placeholders are: 1) the schedule name.
489
				'<li>' . esc_html__( 'Schedule name: %1$s.', 'object-sync-for-salesforce' ) . '</li>',
490
				esc_attr( $schedule_updated )
491
			);
492
		}
493
		$body .= '</ul>';
494
		$body .= sprintf( esc_html__( 'These are the scheduled tasks that have the same frequency as they had pre-migration: ', 'object-sync-for-salesforce' ) . '<ul>' );
495
		foreach ( $schedules_restored as $schedule_restored ) {
496
			$body .= sprintf(
497
				// translators: placeholders are: 1) the schedule name.
498
				'<li>' . esc_html__( 'Schedule name: %1$s.', 'object-sync-for-salesforce' ) . '</li>',
499
				esc_attr( $schedule_restored )
500
			);
501
		}
502
		$body .= '</ul>';
503
		$body .= sprintf( esc_html__( 'If any tasks were not updated, or were not able to keep the same frequency they had before, go to the Scheduling tab to update them.', 'object-sync-for-salesforce' ) );
504
		$body .= sprintf(
505
			// translators: %1$s is the schedule settings URL.
506
			wp_kses_post( 'If any tasks were not updated, or were not able to keep the same frequency they had before, go to the <a href="' . admin_url( 'options-general.php?page=object-sync-salesforce-admin&tab=schedule' ) . '">%1$s</a> tab to update them.', 'object-sync-for-salesforce' ),
0 ignored issues
show
Unused Code introduced by
The call to wp_kses_post() has too many arguments starting with 'object-sync-for-salesforce'. ( Ignorable by Annotation )

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

506
			/** @scrutinizer ignore-call */ 
507
   wp_kses_post( 'If any tasks were not updated, or were not able to keep the same frequency they had before, go to the <a href="' . admin_url( 'options-general.php?page=object-sync-salesforce-admin&tab=schedule' ) . '">%1$s</a> tab to update them.', 'object-sync-for-salesforce' ),

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...
507
			esc_html__( 'Scheduling', 'object-sync-for-salesforce' )
508
		);
509
		$this->logging->setup(
510
			sprintf(
511
				// translators: %1$s is the log status, %2$s is the name of a WordPress object. %3$s is the id of that object.
512
				esc_html__( '%1$s ActionScheduler: the ActionScheduler library has completed its migration. See the log entry content for status on each recurring task.', 'object-sync-for-salesforce' ),
513
				ucfirst( esc_attr( $status ) )
514
			),
515
			$body,
516
			0,
517
			0,
518
			$status
519
		);
520
	}
521
522
	/**
523
	 * Create the WordPress admin options page
524
	 */
525
	public function create_admin_menu() {
526
		$title = __( 'Salesforce', 'object-sync-for-salesforce' );
527
		add_options_page( $title, $title, 'configure_salesforce', $this->admin_settings_url_param, array( $this, 'show_admin_page' ) );
528
	}
529
530
	/**
531
	 * Render the admin pages in WordPress. This also allows other plugins to add tabs to this plugin's settings screen
532
	 */
533
	public function show_admin_page() {
534
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
535
		echo '<div class="wrap">';
536
		echo '<h1>' . esc_html( get_admin_page_title() ) . '</h1>';
537
		$allowed = $this->check_wordpress_admin_permissions();
538
		if ( false === $allowed ) {
539
			return;
540
		}
541
		$tabs = array(
542
			'settings'      => __( 'Settings', 'object-sync-for-salesforce' ),
543
			'authorize'     => __( 'Authorize', 'object-sync-for-salesforce' ),
544
			'fieldmaps'     => __( 'Fieldmaps', 'object-sync-for-salesforce' ),
545
			'schedule'      => __( 'Scheduling', 'object-sync-for-salesforce' ),
546
			'import-export' => __( 'Import &amp; Export', 'object-sync-for-salesforce' ),
547
		); // this creates the tabs for the admin.
548
549
		// optionally make tab(s) for logging and log settings.
550
		$logging_enabled      = get_option( $this->option_prefix . 'enable_logging', false );
551
		$tabs['log_settings'] = __( 'Log Settings', 'object-sync-for-salesforce' );
552
553
		$mapping_errors       = $this->mappings->get_failed_object_maps();
554
		$mapping_errors_total = isset( $mapping_errors['total'] ) ? $mapping_errors['total'] : 0;
555
		if ( 0 < $mapping_errors_total ) {
556
			$tabs['mapping_errors'] = __( 'Mapping Errors', 'object-sync-for-salesforce' );
557
		}
558
559
		// filter for extending the tabs available on the page
560
		// currently it will go into the default switch case for $tab.
561
		$tabs = apply_filters( $this->option_prefix . 'settings_tabs', $tabs );
562
563
		$tab = isset( $get_data['tab'] ) ? sanitize_key( $get_data['tab'] ) : 'settings';
564
		$this->tabs( $tabs, $tab );
565
566
		$consumer_key    = $this->login_credentials['consumer_key'];
567
		$consumer_secret = $this->login_credentials['consumer_secret'];
568
		$callback_url    = $this->login_credentials['callback_url'];
569
570
		if ( true !== $this->salesforce['is_authorized'] ) {
571
			$url     = esc_url( $callback_url );
572
			$anchor  = esc_html__( 'Authorize tab', 'object-sync-for-salesforce' );
573
			$message = sprintf( 'Salesforce needs to be authorized to connect to this website. Use the <a href="%s">%s</a> to connect.', $url, $anchor );
574
			require plugin_dir_path( $this->file ) . '/templates/admin/error.php';
575
		}
576
577
		if ( 0 === count( $this->mappings->get_fieldmaps() ) ) {
578
			$url     = esc_url( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=fieldmaps' ) );
579
			$anchor  = esc_html__( 'Fieldmaps tab', 'object-sync-for-salesforce' );
580
			$message = sprintf( 'No fieldmaps exist yet. Use the <a href="%s">%s</a> to map WordPress and Salesforce objects to each other.', $url, $anchor );
581
			require plugin_dir_path( $this->file ) . '/templates/admin/error.php';
582
		}
583
584
		try {
585
			switch ( $tab ) {
586
				case 'authorize':
587
					if ( isset( $get_data['code'] ) ) {
588
						// this string is an oauth token.
589
						$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

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

1631
			$salesforce_object = isset( $post_data['salesforce_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['salesforce_object'] ) ) : '';
Loading history...
1632
			$ajax              = true;
1633
			// here, we should respect the decision of whether to show the API name or the label.
1634
			$display_value = get_option( $this->option_prefix . 'salesforce_field_display_value', 'field_label' );
1635
			if ( 'api_name' === $display_value ) {
1636
				$visible_label_field = 'name';
1637
			} else {
1638
				$visible_label_field = 'label';
1639
			}
1640
			$attributes = array( 'name', $visible_label_field );
1641
		} else {
1642
			$salesforce_object = isset( $data['salesforce_object'] ) ? sanitize_text_field( wp_unslash( $data['salesforce_object'] ) ) : '';
1643
		}
1644
		$object_fields = array();
1645
		if ( ! empty( $salesforce_object ) ) {
1646
			$object               = $this->salesforce['sfapi']->object_describe( esc_attr( $salesforce_object ) );
1647
			$object_fields        = array();
1648
			$type                 = isset( $data['type'] ) ? esc_attr( $data['type'] ) : '';
1649
			$include_record_types = isset( $data['include_record_types'] ) ? esc_attr( $data['include_record_types'] ) : false;
1650
			foreach ( $object['data']['fields'] as $key => $value ) {
1651
				if ( '' === $type || $type === $value['type'] ) {
1652
					$object_fields[ $key ] = $value;
1653
					if ( isset( $attributes ) ) {
1654
						$object_fields[ $key ] = array_intersect_key( $value, array_flip( $attributes ) );
1655
					}
1656
				}
1657
			}
1658
			if ( true === $include_record_types ) {
0 ignored issues
show
introduced by
The condition true === $include_record_types is always false.
Loading history...
1659
				$object_record_types = array();
1660
				if ( isset( $object['data']['recordTypeInfos'] ) && count( $object['data']['recordTypeInfos'] ) > 1 ) {
1661
					foreach ( $object['data']['recordTypeInfos'] as $type ) {
1662
						$object_record_types[ $type['recordTypeId'] ] = $type['name'];
1663
					}
1664
				}
1665
			}
1666
		}
1667
1668
		if ( true === $ajax ) {
1669
			$ajax_response = array(
1670
				'fields' => $object_fields,
1671
			);
1672
			wp_send_json_success( $ajax_response );
1673
		} else {
1674
			return $object_fields;
1675
		}
1676
1677
	}
1678
1679
	/**
1680
	 * Get WordPress object fields for fieldmapping
1681
	 * This takes either the $_POST array via ajax, or can be directly called with a $wordpress_object field
1682
	 *
1683
	 * @param string $wordpress_object is the name of the WordPress object.
1684
	 * @return array $object_fields
1685
	 */
1686
	public function get_wordpress_object_fields( $wordpress_object = '' ) {
1687
		$ajax      = false;
1688
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1689
		if ( empty( $wordpress_object ) ) {
1690
			$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

1690
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1691
			$ajax             = true;
1692
		}
1693
1694
		$object_fields = $this->wordpress->get_wordpress_object_fields( $wordpress_object );
1695
1696
		if ( true === $ajax ) {
1697
			$ajax_response = array(
1698
				'fields' => $object_fields,
1699
			);
1700
			wp_send_json_success( $ajax_response );
1701
		} else {
1702
			return $object_fields;
1703
		}
1704
	}
1705
1706
	/**
1707
	 * Manually push the WordPress object to Salesforce
1708
	 * This takes either the $_POST array via ajax, or can be directly called with $wordpress_object and $wordpress_id fields
1709
	 *
1710
	 * @param string $wordpress_object is the name of the WordPress object.
1711
	 * @param int    $wordpress_id is the ID of the WordPress record.
1712
	 * @param bool   $force_return Force the method to return json instead of outputting it.
1713
	 */
1714
	public function push_to_salesforce( $wordpress_object = '', $wordpress_id = '', $force_return = false ) {
1715
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1716
		if ( empty( $wordpress_object ) && empty( $wordpress_id ) ) {
1717
			$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

1717
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1718
			$wordpress_id     = isset( $post_data['wordpress_id'] ) ? absint( $post_data['wordpress_id'] ) : '';
1719
		}
1720
1721
		// clarify what that variable is in this context.
1722
		$object_type = $wordpress_object;
1723
1724
		// When objects are already mapped, there is a Salesforce id as well. Otherwise, it's blank.
1725
		$salesforce_id = isset( $post_data['salesforce_id'] ) ? sanitize_text_field( $post_data['salesforce_id'] ) : '';
1726
		if ( '' === $salesforce_id ) {
1727
			$method = 'POST';
1728
		} else {
1729
			$method = 'PUT';
1730
		}
1731
1732
		$result = $this->push->manual_push( $object_type, $wordpress_id, $method );
1733
1734
		if ( false === $force_return && ! empty( $post_data['wordpress_object'] ) && ! empty( $post_data['wordpress_id'] ) ) {
1735
			wp_send_json_success( $result );
1736
		} else {
1737
			return $result;
1738
		}
1739
1740
	}
1741
1742
	/**
1743
	 * Manually pull the Salesforce object into WordPress
1744
	 * This takes either the $_POST array via ajax, or can be directly called with $salesforce_id fields
1745
	 *
1746
	 * @param string $salesforce_id is the ID of the Salesforce record.
1747
	 * @param string $wordpress_object is the name of the WordPress object.
1748
	 */
1749
	public function pull_from_salesforce( $salesforce_id = '', $wordpress_object = '' ) {
1750
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1751
		if ( empty( $wordpress_object ) && empty( $salesforce_id ) ) {
1752
			$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

1752
			$wordpress_object = isset( $post_data['wordpress_object'] ) ? sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $post_data['wordpress_object'] ) ) : '';
Loading history...
1753
			$salesforce_id    = isset( $post_data['salesforce_id'] ) ? sanitize_text_field( wp_unslash( $post_data['salesforce_id'] ) ) : '';
1754
		}
1755
		$type   = $this->salesforce['sfapi']->get_sobject_type( $salesforce_id );
1756
		$result = $this->pull->manual_pull( $type, $salesforce_id, $wordpress_object ); // we want the wp object to make sure we get the right fieldmap.
1757
		if ( ! empty( $post_data ) ) {
1758
			wp_send_json_success( $result );
1759
		} else {
1760
			return $result;
1761
		}
1762
	}
1763
1764
	/**
1765
	 * Manually pull the Salesforce object into WordPress
1766
	 * This takes an id for a mapping object row
1767
	 *
1768
	 * @param int $mapping_id is the ID of the mapping object record.
1769
	 */
1770
	public function refresh_mapped_data( $mapping_id = '' ) {
1771
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1772
		if ( empty( $mapping_id ) ) {
1773
			$mapping_id = isset( $post_data['mapping_id'] ) ? absint( $post_data['mapping_id'] ) : '';
1774
		}
1775
		$result = $this->mappings->get_all_object_maps(
1776
			array(
1777
				'id' => $mapping_id,
1778
			)
1779
		);
1780
1781
		$object_map = array();
1782
1783
		// result is an array of arrays, not just one array.
1784
		if ( 1 === count( $result ) ) {
1785
			$object_map = $result[0];
1786
		}
1787
1788
		if ( ! empty( $post_data ) ) {
1789
			wp_send_json_success( $object_map );
1790
		} else {
1791
			return $object_map;
1792
		}
1793
	}
1794
1795
	/**
1796
	 * Prepare fieldmap data and redirect after processing
1797
	 * This runs when the create or update forms are submitted
1798
	 * It is public because it depends on an admin hook
1799
	 * It then calls the Object_Sync_Sf_Mapping class and sends prepared data over to it, then redirects to the correct page
1800
	 * This method does include error handling, by loading the submission in a transient if there is an error, and then deleting it upon success
1801
	 */
1802
	public function prepare_fieldmap_data() {
1803
		$error     = false;
1804
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1805
		$cachekey  = wp_json_encode( $post_data );
1806
		if ( false !== $cachekey ) {
1807
			$cachekey = md5( $cachekey );
1808
		}
1809
1810
		if ( ! isset( $post_data['label'] ) || ! isset( $post_data['salesforce_object'] ) || ! isset( $post_data['wordpress_object'] ) ) {
1811
			$error = true;
1812
		}
1813
		if ( true === $error ) {
1814
			$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1815
			if ( '' !== $cachekey ) {
1816
				$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

1816
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1817
			}
1818
		} else { // there are no errors
1819
			// send the row to the fieldmap class
1820
			// if it is add or clone, use the create method.
1821
			$method            = esc_attr( $post_data['method'] );
1822
			$salesforce_fields = $this->get_salesforce_object_fields(
1823
				array(
1824
					'salesforce_object' => $post_data['salesforce_object'],
1825
				)
1826
			);
1827
			$wordpress_fields  = $this->get_wordpress_object_fields( $post_data['wordpress_object'] );
1828
			if ( 'add' === $method || 'clone' === $method ) {
1829
				$result = $this->mappings->create_fieldmap( $post_data, $wordpress_fields, $salesforce_fields );
1830
			} elseif ( 'edit' === $method ) { // if it is edit, use the update method.
1831
				$id     = esc_attr( $post_data['id'] );
1832
				$result = $this->mappings->update_fieldmap( $post_data, $wordpress_fields, $salesforce_fields, $id );
1833
			}
1834
			if ( false === $result ) { // if the database didn't save, it's still an error.
1835
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1836
				if ( '' !== $cachekey ) {
1837
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&transient=' . $cachekey;
1838
				}
1839
			} else {
1840
				// if the user has saved a fieldmap, clear the currently running query value if there is one.
1841
				if ( '' !== get_option( $this->option_prefix . 'currently_pulling_query_' . $post_data['salesforce_object'], '' ) ) {
1842
					$this->pull->clear_current_type_query( $post_data['salesforce_object'] );
1843
				}
1844
				if ( isset( $post_data['transient'] ) ) { // there was previously an error saved. can delete it now.
1845
					$this->sfwp_transients->delete( esc_attr( $post_data['map_transient'] ) );
1846
				}
1847
				// then send the user to the list of fieldmaps.
1848
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1849
			}
1850
		}
1851
		wp_safe_redirect( $url );
1852
		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...
1853
	}
1854
1855
	/**
1856
	 * Delete fieldmap data and redirect after processing
1857
	 * This runs when the delete link is clicked, after the user confirms
1858
	 * It is public because it depends on an admin hook
1859
	 * It then calls the Object_Sync_Sf_Mapping class and the delete method
1860
	 */
1861
	public function delete_fieldmap() {
1862
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1863
		if ( $post_data['id'] ) {
1864
			$result = $this->mappings->delete_fieldmap( $post_data['id'] );
1865
			if ( true === $result ) {
1866
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1867
			} else {
1868
				$url = esc_url_raw( $post_data['redirect_url_error'] . '&id=' . $post_data['id'] );
1869
			}
1870
			wp_safe_redirect( $url );
1871
			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...
1872
		}
1873
	}
1874
1875
	/**
1876
	 * Prepare object data and redirect after processing
1877
	 * This runs when the update form is submitted
1878
	 * It is public because it depends on an admin hook
1879
	 * It then calls the Object_Sync_Sf_Mapping class and sends prepared data over to it, then redirects to the correct page
1880
	 * This method does include error handling, by loading the submission in a transient if there is an error, and then deleting it upon success
1881
	 */
1882
	public function prepare_object_map_data() {
1883
		$error     = false;
1884
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1885
		$cachekey  = wp_json_encode( $post_data );
1886
		if ( false !== $cachekey ) {
1887
			$cachekey = md5( $cachekey );
1888
		}
1889
1890
		if ( ! isset( $post_data['wordpress_id'] ) || ! isset( $post_data['salesforce_id'] ) ) {
1891
			$error = true;
1892
		}
1893
		if ( true === $error ) {
1894
			$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1895
			if ( '' !== $cachekey ) {
1896
				$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

1896
				$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&map_transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1897
			}
1898
		} else { // there are no errors
1899
			// send the row to the object map class.
1900
			$method = esc_attr( $post_data['method'] );
1901
			if ( 'edit' === $method ) { // if it is edit, use the update method.
1902
				$id     = esc_attr( $post_data['id'] );
1903
				$result = $this->mappings->update_object_map( $post_data, $id );
1904
			}
1905
			if ( false === $result ) { // if the database didn't save, it's still an error.
1906
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1907
				if ( '' !== $cachekey ) {
1908
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&map_transient=' . $cachekey;
1909
				}
1910
			} else {
1911
				if ( isset( $post_data['map_transient'] ) ) { // there was previously an error saved. can delete it now.
1912
					$this->sfwp_transients->delete( esc_attr( $post_data['map_transient'] ) );
1913
				}
1914
				// then send the user to the success redirect url.
1915
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1916
			}
1917
		}
1918
		wp_safe_redirect( $url );
1919
		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...
1920
	}
1921
1922
	/**
1923
	 * Delete object map data and redirect after processing
1924
	 * This runs when the delete link is clicked on an error row, after the user confirms
1925
	 * It is public because it depends on an admin hook
1926
	 * It then calls the Object_Sync_Sf_Mapping class and the delete method
1927
	 */
1928
	public function delete_object_map() {
1929
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1930
		if ( isset( $post_data['id'] ) ) {
1931
			$result = $this->mappings->delete_object_map( $post_data['id'] );
1932
			if ( true === $result ) {
1933
				$url = esc_url_raw( $post_data['redirect_url_success'] );
1934
			} else {
1935
				$url = esc_url_raw( $post_data['redirect_url_error'] . '&id=' . $post_data['id'] );
1936
			}
1937
			wp_safe_redirect( $url );
1938
			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...
1939
		} elseif ( $post_data['delete'] ) {
1940
			$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
1941
			$cachekey  = wp_json_encode( $post_data );
1942
			if ( false !== $cachekey ) {
1943
				$cachekey = md5( $cachekey );
1944
			}
1945
			$error = false;
1946
			if ( ! isset( $post_data['delete'] ) ) {
1947
				$error = true;
1948
			}
1949
			if ( true === $error ) {
1950
				$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1951
				if ( '' !== $cachekey ) {
1952
					$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

1952
					$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&mapping_error_transient=' . /** @scrutinizer ignore-type */ $cachekey;
Loading history...
1953
				}
1954
			} else { // there are no errors.
1955
				$result = $this->mappings->delete_object_map( array_keys( $post_data['delete'] ) );
1956
				if ( true === $result ) {
1957
					$url = esc_url_raw( $post_data['redirect_url_success'] );
1958
				}
1959
1960
				if ( false === $result ) { // if the database didn't save, it's still an error.
1961
					$this->sfwp_transients->set( $cachekey, $post_data, $this->wordpress->options['cache_expiration'] );
1962
					if ( '' !== $cachekey ) {
1963
						$url = esc_url_raw( $post_data['redirect_url_error'] ) . '&mapping_error_transient=' . $cachekey;
1964
					}
1965
				} else {
1966
					if ( isset( $post_data['mapping_error_transient'] ) ) { // there was previously an error saved. can delete it now.
1967
						$this->sfwp_transients->delete( esc_attr( $post_data['mapping_error_transient'] ) );
1968
					}
1969
					// then send the user to the list of fieldmaps.
1970
					$url = esc_url_raw( $post_data['redirect_url_success'] );
1971
				}
1972
			}
1973
			wp_safe_redirect( $url );
1974
			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...
1975
		}
1976
	}
1977
1978
	/**
1979
	 * Import a json file and use it for plugin data
1980
	 */
1981
	public function import_json_file() {
1982
1983
		if ( ! wp_verify_nonce( $_POST['object_sync_for_salesforce_nonce_import'], 'object_sync_for_salesforce_nonce_import' ) ) {
1984
			return;
1985
		}
1986
		if ( ! current_user_can( 'manage_options' ) ) {
1987
			return;
1988
		}
1989
		$path      = $_FILES['import_file']['name'];
1990
		$extension = pathinfo( $path, PATHINFO_EXTENSION );
1991
		if ( 'json' !== $extension ) {
1992
			wp_die( esc_html__( 'Please upload a valid .json file', 'object-sync-for-salesforce' ) );
1993
		}
1994
1995
		$import_file = $_FILES['import_file']['tmp_name'];
1996
		if ( empty( $import_file ) ) {
1997
			wp_die( esc_html__( 'Please upload a file to import', 'object-sync-for-salesforce' ) );
1998
		}
1999
2000
		// Retrieve the data from the file and convert the json object to an array.
2001
		$data = (array) json_decode( file_get_contents( $import_file ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
2002
2003
		$overwrite = isset( $_POST['overwrite'] ) ? esc_attr( $_POST['overwrite'] ) : '';
2004
		if ( true === filter_var( $overwrite, FILTER_VALIDATE_BOOLEAN ) ) {
2005
			if ( isset( $data['fieldmaps'] ) ) {
2006
				$fieldmaps = $this->mappings->get_fieldmaps();
2007
				foreach ( $fieldmaps as $fieldmap ) {
2008
					$id     = $fieldmap['id'];
2009
					$delete = $this->mappings->delete_fieldmap( $id );
2010
				}
2011
			}
2012
			if ( isset( $data['object_maps'] ) ) {
2013
				$object_maps = $this->mappings->get_all_object_maps();
2014
				foreach ( $object_maps as $object_map ) {
2015
					$id     = $object_map['id'];
2016
					$delete = $this->mappings->delete_object_map( $id );
2017
				}
2018
			}
2019
			if ( isset( $data['plugin_settings'] ) ) {
2020
				foreach ( $data['plugin_settings'] as $key => $value ) {
2021
					delete_option( $value['option_name'] );
2022
				}
2023
			}
2024
		}
2025
2026
		// if the option says to, set all the imported fieldmaps to inactive.
2027
		$import_fieldmaps_inactive = isset( $_POST['import_fieldmaps_inactive'] ) ? esc_attr( $_POST['import_fieldmaps_inactive'] ) : '';
2028
		if ( true === filter_var( $import_fieldmaps_inactive, FILTER_VALIDATE_BOOLEAN ) ) {
2029
			if ( isset( $data['fieldmaps'] ) ) {
2030
				foreach ( $data['fieldmaps'] as $key => $fieldmap ) {
2031
					$data['fieldmaps'][ $key ]['fieldmap_status'] = 'inactive';
2032
				}
2033
			}
2034
		}
2035
2036
		$success = true;
2037
2038
		if ( isset( $data['fieldmaps'] ) ) {
2039
			$successful_fieldmaps = array();
2040
			$error_fieldmaps      = array();
2041
			foreach ( $data['fieldmaps'] as $fieldmap ) {
2042
				unset( $fieldmap['id'] );
2043
				$create = $this->mappings->create_fieldmap( $fieldmap );
2044
				if ( false === $create ) {
2045
					$success = false;
2046
				}
2047
				if ( false === $create ) {
2048
					$error_fieldmaps[] = $fieldmap;
2049
				} else {
2050
					$successful_fieldmaps[] = $create;
2051
				}
2052
			}
2053
		}
2054
2055
		if ( isset( $data['object_maps'] ) ) {
2056
			$successful_object_maps = array();
2057
			$error_object_maps      = array();
2058
			foreach ( $data['object_maps'] as $object_map ) {
2059
				unset( $object_map['id'] );
2060
				if ( isset( $object_map['object_type'] ) ) {
2061
					$sf_sync_trigger = $this->mappings->sync_sf_create;
2062
					$create          = $this->pull->salesforce_pull_process_records( $object_map['object_type'], $object_map['salesforce_id'], $sf_sync_trigger );
2063
				} else {
2064
					$create = $this->mappings->create_object_map( $object_map );
2065
				}
2066
				if ( false === $create ) {
2067
					$error_object_maps[] = $object_map;
2068
				} else {
2069
					$successful_object_maps[] = $create;
2070
				}
2071
			}
2072
		}
2073
2074
		if ( isset( $data['plugin_settings'] ) ) {
2075
			foreach ( $data['plugin_settings'] as $key => $value ) {
2076
				update_option( $value['option_name'], maybe_unserialize( $value['option_value'] ), $value['autoload'] );
2077
			}
2078
		}
2079
2080
		if ( ! empty( $error_fieldmaps ) && ! empty( $error_object_maps ) ) {
2081
			$status = 'error';
2082
			$body   = sprintf( esc_html__( 'These are the import items that were not able to save: ', 'object-sync-for-salesforce' ) . '<ul>' );
2083
			foreach ( $error_fieldmaps as $fieldmap ) {
2084
				$body .= sprintf(
2085
					// translators: placeholders are: 1) the fieldmap row ID, 2) the Salesforce object type, 3) the WordPress object type.
2086
					'<li>' . esc_html__( 'Fieldmap id (if it exists): %1$s. Salesforce object type: %2$s. WordPress object type: %3$s', 'object-sync-for-salesforce' ) . '</li>',
2087
					isset( $fieldmap['id'] ) ? absint( $fieldmap['id'] ) : '',
2088
					esc_attr( $fieldmap['salesforce_object'] ),
2089
					esc_attr( $fieldmap['wordpress_object'] )
2090
				);
2091
			}
2092
			foreach ( $error_object_maps as $mapping_object ) {
2093
				$body .= sprintf(
2094
					// translators: placeholders are: 1) the mapping object row ID, 2) the ID of the Salesforce object, 3) the WordPress object type.
2095
					'<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>',
2096
					isset( $mapping_object['id'] ) ? absint( $mapping_object['id'] ) : '',
2097
					esc_attr( $mapping_object['salesforce_id'] ),
2098
					esc_attr( $mapping_object['wordpress_object'] )
2099
				);
2100
			}
2101
			$body .= sprintf( '</ul>' );
2102
			$this->logging->setup(
2103
				sprintf(
2104
					// translators: %1$s is the log status.
2105
					esc_html__( '%1$s on import: some of the rows were unable to save. Read this post for details.', 'object-sync-for-salesforce' ),
2106
					ucfirst( esc_attr( $status ) )
2107
				),
2108
				$body,
2109
				0,
2110
				0,
2111
				$status
2112
			);
2113
		}
2114
2115
		if ( empty( $error_fieldmaps ) && empty( $error_object_maps ) && ( ! empty( $successful_fieldmaps ) || ! empty( $successful_object_maps ) ) ) {
2116
			$this->clear_cache( false );
2117
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=true' ) );
2118
			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...
2119
		} elseif ( ! empty( $error_fieldmaps ) && ! empty( $successful_fieldmaps ) ) {
2120
			$this->clear_cache( false );
2121
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=partial' ) );
2122
		} elseif ( ! empty( $error_object_maps ) && ! empty( $successful_object_maps ) ) {
2123
			$this->clear_cache( false );
2124
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=partial' ) );
2125
		} else {
2126
			wp_safe_redirect( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=import-export&data_saved=false' ) );
2127
			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...
2128
		}
2129
2130
	}
2131
2132
	/**
2133
	 * Create a json file for exporting
2134
	 */
2135
	public function export_json_file() {
2136
2137
		if ( ! wp_verify_nonce( $_POST['object_sync_for_salesforce_nonce_export'], 'object_sync_for_salesforce_nonce_export' ) ) {
2138
			return;
2139
		}
2140
		if ( ! current_user_can( 'manage_options' ) ) {
2141
			return;
2142
		}
2143
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
2144
		$export    = array();
2145
		if ( in_array( 'fieldmaps', $post_data['export'], true ) ) {
2146
			$export['fieldmaps'] = $this->mappings->get_fieldmaps();
2147
		}
2148
		if ( in_array( 'object_maps', $post_data['export'], true ) ) {
2149
			$export['object_maps'] = $this->mappings->get_all_object_maps();
2150
		}
2151
		if ( in_array( 'plugin_settings', $post_data['export'], true ) ) {
2152
			$wpdb                      = $this->wpdb;
2153
			$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 );
2154
			$export['plugin_settings'] = $export_results;
2155
		}
2156
		nocache_headers();
2157
		header( 'Content-Type: application/json; charset=utf-8' );
2158
		header( 'Content-Disposition: attachment; filename=object-sync-for-salesforce-data-export-' . gmdate( 'm-d-Y' ) . '.json' );
2159
		header( 'Expires: 0' );
2160
		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

2160
		echo /** @scrutinizer ignore-type */ wp_json_encode( $export );
Loading history...
2161
		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...
2162
	}
2163
2164
	/**
2165
	 * Default display for <input> fields
2166
	 *
2167
	 * @param array $args is the arguments to create the field.
2168
	 */
2169
	public function display_input_field( $args ) {
2170
		$type    = $args['type'];
2171
		$id      = $args['label_for'];
2172
		$name    = $args['name'];
2173
		$desc    = $args['desc'];
2174
		$checked = '';
2175
2176
		$class = 'regular-text';
2177
2178
		if ( 'checkbox' === $type ) {
2179
			$class = 'checkbox';
2180
		}
2181
2182
		if ( isset( $args['class'] ) ) {
2183
			$class = $args['class'];
2184
		}
2185
2186
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2187
			$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

2187
			$value = esc_attr( /** @scrutinizer ignore-type */ get_option( $id, '' ) );
Loading history...
2188
			if ( 'checkbox' === $type ) {
2189
				$value = filter_var( get_option( $id, false ), FILTER_VALIDATE_BOOLEAN );
2190
				if ( true === $value ) {
2191
					$checked = 'checked ';
2192
				}
2193
				$value = 1;
2194
			}
2195
			if ( '' === $value && isset( $args['default'] ) && '' !== $args['default'] ) {
2196
				$value = $args['default'];
2197
			}
2198
2199
			echo sprintf(
2200
				'<input type="%1$s" value="%2$s" name="%3$s" id="%4$s" class="%5$s"%6$s>',
2201
				esc_attr( $type ),
2202
				esc_attr( $value ),
2203
				esc_attr( $name ),
2204
				esc_attr( $id ),
2205
				sanitize_html_class( $class . esc_html( ' code' ) ),
2206
				esc_html( $checked )
2207
			);
2208
			if ( '' !== $desc ) {
2209
				echo sprintf(
2210
					'<p class="description">%1$s</p>',
2211
					esc_html( $desc )
2212
				);
2213
			}
2214
		} else {
2215
			echo sprintf(
2216
				'<p><code>%1$s</code></p>',
2217
				esc_html__( 'Defined in wp-config.php', 'object-sync-for-salesforce' )
2218
			);
2219
		}
2220
	}
2221
2222
	/**
2223
	 * Display for multiple checkboxes
2224
	 * Above method can handle a single checkbox as it is
2225
	 *
2226
	 * @param array $args is the arguments to create the checkboxes.
2227
	 */
2228
	public function display_checkboxes( $args ) {
2229
		$type    = 'checkbox';
2230
		$name    = $args['name'];
2231
		$options = get_option( $name, array() );
2232
		foreach ( $args['items'] as $key => $value ) {
2233
			$text    = $value['text'];
2234
			$id      = $value['id'];
2235
			$desc    = $value['desc'];
2236
			$checked = '';
2237
			if ( is_array( $options ) && in_array( (string) $key, $options, true ) ) {
2238
				$checked = 'checked';
2239
			} elseif ( is_array( $options ) && empty( $options ) ) {
2240
				if ( isset( $value['default'] ) && true === $value['default'] ) {
2241
					$checked = 'checked';
2242
				}
2243
			}
2244
			echo sprintf(
2245
				'<div class="checkbox"><label><input type="%1$s" value="%2$s" name="%3$s[]" id="%4$s"%5$s>%6$s</label></div>',
2246
				esc_attr( $type ),
2247
				esc_attr( $key ),
2248
				esc_attr( $name ),
2249
				esc_attr( $id ),
2250
				esc_html( $checked ),
2251
				esc_html( $text )
2252
			);
2253
			if ( '' !== $desc ) {
2254
				echo sprintf(
2255
					'<p class="description">%1$s</p>',
2256
					esc_html( $desc )
2257
				);
2258
			}
2259
		}
2260
	}
2261
2262
	/**
2263
	 * Display for a dropdown
2264
	 *
2265
	 * @param array $args is the arguments needed to create the dropdown.
2266
	 */
2267
	public function display_select( $args ) {
2268
		$type = $args['type'];
2269
		$id   = $args['label_for'];
2270
		$name = $args['name'];
2271
		$desc = $args['desc'];
2272
		if ( ! isset( $args['constant'] ) || ! defined( $args['constant'] ) ) {
2273
			$current_value = get_option( $name );
2274
2275
			echo sprintf(
2276
				'<div class="select"><select id="%1$s" name="%2$s"><option value="">- ' . esc_html__( 'Select one', 'object-sync-for-salesforce' ) . ' -</option>',
2277
				esc_attr( $id ),
2278
				esc_attr( $name )
2279
			);
2280
2281
			foreach ( $args['items'] as $key => $value ) {
2282
				$text     = $value['text'];
2283
				$value    = $value['value'];
2284
				$selected = '';
2285
				if ( $key === $current_value || $value === $current_value ) {
2286
					$selected = ' selected';
2287
				}
2288
2289
				echo sprintf(
2290
					'<option value="%1$s"%2$s>%3$s</option>',
2291
					esc_attr( $value ),
2292
					esc_attr( $selected ),
2293
					esc_html( $text )
2294
				);
2295
2296
			}
2297
			echo '</select>';
2298
			if ( '' !== $desc ) {
2299
				echo sprintf(
2300
					'<p class="description">%1$s</p>',
2301
					esc_html( $desc )
2302
				);
2303
			}
2304
			echo '</div>';
2305
		} else {
2306
			echo sprintf(
2307
				'<p><code>%1$s</code></p>',
2308
				esc_html__( 'Defined in wp-config.php', 'object-sync-for-salesforce' )
2309
			);
2310
		}
2311
	}
2312
2313
	/**
2314
	 * Default display for <a href> links
2315
	 *
2316
	 * @param array $args is the arguments to make the link.
2317
	 */
2318
	public function display_link( $args ) {
2319
		$label = $args['label'];
2320
		$desc  = $args['desc'];
2321
		$url   = $args['url'];
2322
		if ( isset( $args['link_class'] ) ) {
2323
			echo sprintf(
2324
				'<p><a class="%1$s" href="%2$s">%3$s</a></p>',
2325
				esc_attr( $args['link_class'] ),
2326
				esc_url( $url ),
2327
				esc_html( $label )
2328
			);
2329
		} else {
2330
			echo sprintf(
2331
				'<p><a href="%1$s">%2$s</a></p>',
2332
				esc_url( $url ),
2333
				esc_html( $label )
2334
			);
2335
		}
2336
2337
		if ( '' !== $desc ) {
2338
			echo sprintf(
2339
				'<p class="description">%1$s</p>',
2340
				esc_html( $desc )
2341
			);
2342
		}
2343
2344
	}
2345
2346
	/**
2347
	 * Allow for a standard sanitize/validate method. We could use more specific ones if need be, but this one provides a baseline.
2348
	 *
2349
	 * @param string $option is the option value.
2350
	 * @return string $option is the sanitized option value.
2351
	 */
2352
	public function sanitize_validate_text( $option ) {
2353
		if ( is_array( $option ) ) {
0 ignored issues
show
introduced by
The condition is_array($option) is always false.
Loading history...
2354
			$options = array();
2355
			foreach ( $option as $key => $value ) {
2356
				$options[ $key ] = sanitize_text_field( $value );
2357
			}
2358
			return $options;
2359
		}
2360
		$option = sanitize_text_field( $option );
2361
		return $option;
2362
	}
2363
2364
	/**
2365
	 * Run a demo of Salesforce API call on the authenticate tab after WordPress has authenticated with it
2366
	 *
2367
	 * @param object $sfapi this is the Salesforce API object.
2368
	 */
2369
	private function status( $sfapi ) {
2370
2371
		$contacts = $sfapi->query( 'SELECT Name, Id from Contact LIMIT 100' );
2372
2373
		// format this array into html so users can see the contacts.
2374
		if ( true === $contacts['cached'] ) {
2375
			$contacts_is_cached = esc_html__( 'They are cached, and', 'object-sync-for-salesforce' );
2376
		} else {
2377
			$contacts_is_cached = esc_html__( 'They are not cached, but', 'object-sync-for-salesforce' );
2378
		}
2379
2380
		if ( true === $contacts['from_cache'] ) {
2381
			$contacts_from_cache = esc_html__( 'they were loaded from the cache', 'object-sync-for-salesforce' );
2382
		} else {
2383
			$contacts_from_cache = esc_html__( 'they were not loaded from the cache', 'object-sync-for-salesforce' );
2384
		}
2385
2386
		if ( true === $contacts['is_redo'] ) {
2387
			$contacts_refreshed_token = esc_html__( 'This request did require refreshing the Salesforce token', 'object-sync-for-salesforce' );
2388
		} else {
2389
			$contacts_refreshed_token = esc_html__( 'This request did not require refreshing the Salesforce token', 'object-sync-for-salesforce' );
2390
		}
2391
2392
		// display contact summary if there are any contacts.
2393
		if ( 0 < absint( $contacts['data']['totalSize'] ) ) {
2394
			$contacts_apicall_summary = sprintf(
2395
				// 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.
2396
				esc_html__( 'Salesforce successfully returned %1$s %2$s records. %3$s %4$s. %5$s.', 'object-sync-for-salesforce' ),
2397
				absint( $contacts['data']['totalSize'] ),
2398
				esc_html( $contacts['data']['records'][0]['attributes']['type'] ),
2399
				$contacts_is_cached,
2400
				$contacts_from_cache,
2401
				$contacts_refreshed_token
2402
			);
2403
		} else {
2404
			$contacts_apicall_summary = '';
2405
		}
2406
2407
		require_once plugin_dir_path( $this->file ) . '/templates/admin/status.php';
2408
2409
	}
2410
2411
	/**
2412
	 * Deauthorize WordPress from Salesforce.
2413
	 * This deletes the tokens from the database; it does not currently do anything in Salesforce
2414
	 * For this plugin at this time, that is the decision we are making: don't do any kind of authorization stuff inside Salesforce
2415
	 */
2416
	private function logout() {
2417
		$delete_access_token = delete_option( $this->option_prefix . 'access_token' );
2418
		if ( true === $delete_access_token ) {
2419
			$this->access_token = '';
2420
		}
2421
		$delete_instance_url = delete_option( $this->option_prefix . 'instance_url' );
2422
		if ( true === $delete_instance_url ) {
2423
			$this->instance_url = '';
2424
		}
2425
		$delete_refresh_token = delete_option( $this->option_prefix . 'refresh_token' );
2426
		if ( true === $delete_refresh_token ) {
2427
			$this->refresh_token = '';
2428
		}
2429
		echo sprintf(
2430
			'<p>You have been logged out. You can use the <a href="%1$s">%2$s</a> tab to log in again.</p>',
2431
			esc_url( get_admin_url( null, 'options-general.php?page=' . $this->admin_settings_url_param . '&tab=authorize' ) ),
2432
			esc_html__( 'Authorize', 'object-sync-for-salesforce' )
2433
		);
2434
	}
2435
2436
	/**
2437
	 * Ajax call to clear the plugin cache.
2438
	 */
2439
	public function clear_sfwp_cache() {
2440
		$result   = $this->clear_cache( true );
2441
		$response = array(
2442
			'message' => $result['message'],
2443
			'success' => $result['success'],
2444
		);
2445
		wp_send_json_success( $response );
2446
	}
2447
2448
	/**
2449
	 * Clear the plugin's cache.
2450
	 * This uses the flush method contained in the WordPress cache to clear all of this plugin's cached data.
2451
	 *
2452
	 * @param bool $ajax Whether this is an Ajax request or not.
2453
	 * @return array
2454
	 */
2455
	private function clear_cache( $ajax = false ) {
2456
		$result  = $this->wordpress->sfwp_transients->flush();
2457
		$success = $result['success'];
2458
		if ( 0 < $result['count'] ) {
2459
			if ( true === $success ) {
2460
				$message = __( 'The plugin cache has been cleared.', 'object-sync-for-salesforce' );
2461
			} else {
2462
				$message = __( 'There was an error clearing the plugin cache. Try refreshing this page.', 'object-sync-for-salesforce' );
2463
			}
2464
		} else {
2465
			$success = true;
2466
			$message = __( 'The cache was not cleared because it is empty. You can try again later.', 'object-sync-for-salesforce' );
2467
		}
2468
		if ( false === $ajax ) {
2469
			echo '<p>' . esc_html( $message ) . '</p>';
2470
		} else {
2471
			return array(
2472
				'message' => esc_html( $message ),
2473
				'success' => $success,
2474
			);
2475
		}
2476
	}
2477
2478
	/**
2479
	 * Check WordPress Admin permissions
2480
	 * Check if the current user is allowed to access the Salesforce plugin options
2481
	 */
2482
	private function check_wordpress_admin_permissions() {
2483
2484
		// one programmatic way to give this capability to additional user roles is the
2485
		// object_sync_for_salesforce_roles_configure_salesforce hook
2486
		// it runs on activation of this plugin, and will assign the below capability to any role
2487
		// coming from the hook.
2488
2489
		// alternatively, other roles can get this capability in whatever other way you like
2490
		// point is: to administer this plugin, you need this capability.
2491
2492
		if ( ! current_user_can( 'configure_salesforce' ) ) {
2493
			return false;
2494
		} else {
2495
			return true;
2496
		}
2497
2498
	}
2499
2500
	/**
2501
	 * Check WordPress SSL status.
2502
	 * HTTPS is required to connect to Salesforce.
2503
	 *
2504
	 * @return bool $secure_admin
2505
	 */
2506
	private function check_wordpress_ssl() {
2507
2508
		// the wp_is_using_https() function was added in WordPress 5.7.
2509
		if ( ! function_exists( 'wp_is_using_https' ) ) {
2510
			return true;
2511
		}
2512
2513
		// the whole site is already using SSL.
2514
		if ( true === wp_is_using_https() ) {
2515
			return true;
2516
		}
2517
2518
		$secure_admin = false;
2519
2520
		// the admin is already forced to use SSL.
2521
		if ( true === FORCE_SSL_ADMIN ) {
0 ignored issues
show
introduced by
The condition true === FORCE_SSL_ADMIN is always false.
Loading history...
2522
			$secure_admin = true;
2523
		}
2524
2525
		// the server reports that the current URL is using HTTPS.
2526
		if ( isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ) {
2527
			$secure_admin = true;
2528
		}
2529
2530
		return $secure_admin;
2531
	}
2532
2533
	/**
2534
	 * Check WordPress SSL support.
2535
	 * This allows us to show a different message if SSL is supported, but is not in use.
2536
	 *
2537
	 * @return bool $https_supported
2538
	 */
2539
	private function check_wordpress_ssl_support() {
2540
2541
		// the wp_is_https_supported() function was added in WordPress 5.7.
2542
		if ( ! function_exists( 'wp_is_https_supported' ) ) {
2543
			return true;
2544
		}
2545
2546
		if ( true === wp_is_https_supported() ) {
2547
			return true;
2548
		}
2549
2550
		$https_supported = false;
2551
		return $https_supported;
2552
2553
	}
2554
2555
	/**
2556
	 * Show what we know about this user's relationship to a Salesforce object, if any
2557
	 *
2558
	 * @param object $user this is the user object from WordPress.
2559
	 */
2560
	public function show_salesforce_user_fields( $user ) {
2561
		$get_data = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
2562
		if ( true === $this->check_wordpress_admin_permissions() ) {
2563
			$mappings = $this->mappings->load_all_by_wordpress( 'user', $user->ID );
2564
			$fieldmap = $this->mappings->get_fieldmaps(
2565
				null, // id field must be null for multiples.
2566
				array(
2567
					'wordpress_object' => 'user',
2568
				)
2569
			);
2570
			if ( count( $mappings ) > 0 ) {
2571
				foreach ( $mappings as $mapping ) {
2572
					if ( isset( $mapping['id'] ) && ! isset( $get_data['edit_salesforce_mapping'] ) && ! isset( $get_data['delete_salesforce_mapping'] ) ) {
2573
						require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce.php';
2574
					} elseif ( ! empty( $fieldmap ) ) { // is the user mapped to something already?
2575
						if ( isset( $get_data['edit_salesforce_mapping'] ) && true === filter_var( $get_data['edit_salesforce_mapping'], FILTER_VALIDATE_BOOLEAN ) ) {
2576
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-change.php';
2577
						} elseif ( isset( $get_data['delete_salesforce_mapping'] ) && true === filter_var( $get_data['delete_salesforce_mapping'], FILTER_VALIDATE_BOOLEAN ) ) {
2578
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-delete.php';
2579
						} else {
2580
							require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-map.php';
2581
						}
2582
					}
2583
				}
2584
			} else {
2585
				require_once plugin_dir_path( $this->file ) . '/templates/admin/user-profile-salesforce-map.php';
2586
			}
2587
		}
2588
	}
2589
2590
	/**
2591
	 * If the user profile has been mapped to Salesforce, do it
2592
	 *
2593
	 * @param int $user_id the ID of the WordPress user.
2594
	 */
2595
	public function save_salesforce_user_fields( $user_id ) {
2596
		$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
2597
		if ( isset( $post_data['salesforce_update_mapped_user'] ) && true === filter_var( $post_data['salesforce_update_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2598
			$mapping_objects = $this->mappings->get_all_object_maps(
2599
				array(
2600
					'wordpress_id'     => $user_id,
2601
					'wordpress_object' => 'user',
2602
				)
2603
			);
2604
			foreach ( $mapping_objects as $mapping_object ) {
2605
				$mapping_object['salesforce_id'] = $post_data['salesforce_id'];
2606
				$result                          = $this->mappings->update_object_map( $mapping_object, $mapping_object['id'] );
2607
			}
2608
		} elseif ( isset( $post_data['salesforce_create_mapped_user'] ) && true === filter_var( $post_data['salesforce_create_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2609
			// if a Salesforce ID was entered.
2610
			if ( isset( $post_data['salesforce_id'] ) && ! empty( $post_data['salesforce_id'] ) ) {
2611
				$mapping_object = $this->create_object_map( $user_id, 'user', $post_data['salesforce_id'] );
2612
			} elseif ( isset( $post_data['push_new_user_to_salesforce'] ) ) {
2613
				// otherwise, create a new record in Salesforce.
2614
				$result = $this->push_to_salesforce( 'user', $user_id );
2615
			}
2616
		} elseif ( isset( $post_data['salesforce_delete_mapped_user'] ) && true === filter_var( $post_data['salesforce_delete_mapped_user'], FILTER_VALIDATE_BOOLEAN ) ) {
2617
			// if a Salesforce ID was entered.
2618
			if ( isset( $post_data['mapping_id'] ) && ! empty( $post_data['mapping_id'] ) ) {
2619
				$delete = $this->mappings->delete_object_map( $post_data['mapping_id'] );
2620
			}
2621
		}
2622
	}
2623
2624
	/**
2625
	 * Render tabs for settings pages in admin
2626
	 *
2627
	 * @param array  $tabs is the tabs for the settings menu.
2628
	 * @param string $tab is a single tab.
2629
	 */
2630
	private function tabs( $tabs, $tab = '' ) {
2631
2632
		$get_data        = filter_input_array( INPUT_GET, FILTER_SANITIZE_STRING );
2633
		$consumer_key    = $this->login_credentials['consumer_key'];
2634
		$consumer_secret = $this->login_credentials['consumer_secret'];
2635
		$callback_url    = $this->login_credentials['callback_url'];
2636
2637
		$current_tab = $tab;
2638
		echo '<h2 class="nav-tab-wrapper">';
2639
		foreach ( $tabs as $tab_key => $tab_caption ) {
2640
			$active = $current_tab === $tab_key ? ' nav-tab-active' : '';
2641
2642
			if ( true === $this->salesforce['is_authorized'] ) {
2643
				echo sprintf(
2644
					'<a class="nav-tab%1$s" href="%2$s">%3$s</a>',
2645
					esc_attr( $active ),
2646
					esc_url( '?page=' . $this->admin_settings_url_param . '&tab=' . $tab_key ),
2647
					esc_html( $tab_caption )
2648
				);
2649
			} elseif ( 'settings' === $tab_key || ( 'authorize' === $tab_key && isset( $consumer_key ) && isset( $consumer_secret ) && ! empty( $consumer_key ) && ! empty( $consumer_secret ) ) ) {
2650
				echo sprintf(
2651
					'<a class="nav-tab%1$s" href="%2$s">%3$s</a>',
2652
					esc_attr( $active ),
2653
					esc_url( '?page=' . $this->admin_settings_url_param . '&tab=' . $tab_key ),
2654
					esc_html( $tab_caption )
2655
				);
2656
			}
2657
		}
2658
		echo '</h2>';
2659
2660
		if ( isset( $get_data['tab'] ) ) {
2661
			$tab = sanitize_key( $get_data['tab'] );
2662
		} else {
2663
			$tab = '';
2664
		}
2665
	}
2666
2667
	/**
2668
	 * Clear schedule
2669
	 * This clears the schedule if the user clicks the button
2670
	 *
2671
	 * @param string $schedule_name is the name of the schedule being cleared.
2672
	 */
2673
	private function clear_schedule( $schedule_name = '' ) {
2674
		if ( '' !== $schedule_name ) {
2675
			$this->queue->cancel( $schedule_name );
2676
			// translators: $schedule_name is the name of the current queue. Defaults: salesforce_pull, salesforce_push, salesforce.
2677
			echo sprintf( esc_html__( 'You have cleared the %s schedule.', 'object-sync-for-salesforce' ), esc_html( $schedule_name ) );
2678
		} else {
2679
			echo esc_html__( 'You need to specify the name of the schedule you want to clear.', 'object-sync-for-salesforce' );
2680
		}
2681
	}
2682
2683
	/**
2684
	 * Get count of schedule items
2685
	 *
2686
	 * @param string $schedule_name is the name of the schedule.
2687
	 * @return int $count
2688
	 */
2689
	private function get_schedule_count( $schedule_name = '' ) {
2690
		if ( '' !== $schedule_name ) {
2691
			$count       = count(
2692
				$this->queue->search(
2693
					array(
2694
						'group'  => $schedule_name,
2695
						'status' => ActionScheduler_Store::STATUS_PENDING,
2696
					),
2697
					'ARRAY_A'
2698
				)
2699
			);
2700
			$group_count = count(
2701
				$this->queue->search(
2702
					array(
2703
						'group'  => $schedule_name . $this->action_group_suffix,
2704
						'status' => ActionScheduler_Store::STATUS_PENDING,
2705
					),
2706
					'ARRAY_A'
2707
				)
2708
			);
2709
			return $count + $group_count;
2710
		} else {
2711
			return 0;
2712
		}
2713
	}
2714
2715
	/**
2716
	 * Create an object map between a WordPress object and a Salesforce object
2717
	 *
2718
	 * @param int    $wordpress_id Unique identifier for the WordPress object.
2719
	 * @param string $wordpress_object What kind of object is it.
2720
	 * @param string $salesforce_id Unique identifier for the Salesforce object.
2721
	 * @param string $action Did we push or pull.
2722
	 * @return int   $wpdb->insert_id This is the database row for the map object
2723
	 */
2724
	private function create_object_map( $wordpress_id, $wordpress_object, $salesforce_id, $action = '' ) {
2725
		// Create object map and save it.
2726
		$mapping_object = $this->mappings->create_object_map(
2727
			array(
2728
				'wordpress_id'      => $wordpress_id, // wordpress unique id.
2729
				'salesforce_id'     => $salesforce_id, // salesforce unique id. we don't care what kind of object it is at this point.
2730
				'wordpress_object'  => $wordpress_object, // keep track of what kind of wp object this is.
2731
				'last_sync'         => current_time( 'mysql' ),
2732
				'last_sync_action'  => $action,
2733
				'last_sync_status'  => $this->mappings->status_success,
2734
				'last_sync_message' => __( 'Mapping object updated via function: ', 'object-sync-for-salesforce' ) . __FUNCTION__,
2735
			)
2736
		);
2737
2738
		return $mapping_object;
2739
2740
	}
2741
2742
}
2743