Passed
Push — 459-fix-wordpress-logging ( 2b31bb...84875e )
by Jonathan
05:52 queued 02:40
created

Object_Sync_Sf_Admin::fields_fieldmaps()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 3
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
		add_action( 'wp_ajax_delete_salesforce_api_version', array( $this, 'delete_salesforce_api_version' ) );
291
292
		// we add a Salesforce box on user profiles.
293
		add_action( 'edit_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
294
		add_action( 'show_user_profile', array( $this, 'show_salesforce_user_fields' ), 10, 1 );
295
296
		// and we can update Salesforce fields on the user profile box.
297
		add_action( 'personal_options_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
298
		add_action( 'edit_user_profile_update', array( $this, 'save_salesforce_user_fields' ), 10, 1 );
299
300
		// when either field for schedule settings changes.
301
		foreach ( $this->schedulable_classes as $key => $value ) {
302
			// if the user doesn't have any action schedule tasks, let's not leave them empty.
303
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'initial_action_schedule' ), 10, 3 );
304
			add_filter( 'pre_update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'initial_action_schedule' ), 10, 3 );
305
306
			// this is if the user is changing their tasks.
307
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_number', array( $this, 'change_action_schedule' ), 10, 3 );
308
			add_filter( 'update_option_' . $this->option_prefix . $key . '_schedule_unit', array( $this, 'change_action_schedule' ), 10, 3 );
309
		}
310
311
		// when ActionScheduler runs its migration, resave the schedule options.
312
		add_action( 'action_scheduler/migration_complete', array( $this, 'resave_action_schedules' ) );
313
314
		// handle post requests for object maps.
315
		add_action( 'admin_post_delete_object_map', array( $this, 'delete_object_map' ) );
316
		add_action( 'admin_post_post_object_map', array( $this, 'prepare_object_map_data' ) );
317
318
		// import and export plugin data.
319
		add_action( 'admin_post_object_sync_for_salesforce_import', array( $this, 'import_json_file' ) );
320
		add_action( 'admin_post_object_sync_for_salesforce_export', array( $this, 'export_json_file' ) );
321
322
	}
323
324
	/**
325
	 * Display a Settings link on the main Plugins page
326
	 *
327
	 * @param array  $links the array of links for the main plugins page.
328
	 * @param string $file the filename.
329
	 * @return array $links the array of links for the main plugins page
330
	 */
331
	public function plugin_action_links( $links, $file ) {
332
		if ( plugin_basename( $this->file ) === $file ) {
333
			$settings = '<a href="' . get_admin_url() . 'options-general.php?page=' . $this->admin_settings_url_param . '">' . __( 'Settings', 'object-sync-for-salesforce' ) . '</a>';
334
			array_unshift( $links, $settings );
335
		}
336
		return $links;
337
	}
338
339
	/**
340
	 * Admin styles. Load the CSS and JavaScript for the plugin's settings
341
	 */
342
	public function admin_scripts_and_styles() {
343
344
		// Developers might not want to bother with select2 or selectwoo, so we allow that to be changeable.
345
		$select_library = apply_filters( $this->option_prefix . 'select_library', 'selectwoo' );
346
347
		/*
348
		 * example to modify the select library
349
		 * add_filter( 'object_sync_for_salesforce_select_library', 'select_library', 10, 1 );
350
		 * function select_library( $select_library ) {
351
		 * 	$select_library = 'select2';
352
		 *  // this could also be empty; in that case we would just use default browser select
353
		 * 	return $select_library;
354
		 * }
355
		*/
356
357
		$javascript_dependencies = array( 'jquery' );
358
		$css_dependencies        = array();
359
		if ( '' !== $select_library ) {
360
			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 );
361
			$javascript_dependencies[] = $select_library . 'js';
362
			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' );
363
			$css_dependencies[] = $select_library . 'css';
364
		}
365
366
		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 );
367
		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' );
368
	}
369
370
	/**
371
	 * Initial recurring tasks for ActionScheduler
372
	 *
373
	 * @param string $new_schedule the new, unserialized option value.
374
	 * @param string $old_schedule the old option value.
375
	 * @param string $option_name option name.
376
	 * @return string $new_schedule
377
	 */
378
	public function initial_action_schedule( $new_schedule, $old_schedule, $option_name ) {
379
380
		// get the current schedule name from the task, based on pattern in the foreach.
381
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
382
		$schedule_name     = $matches[1];
383
		$action_group_name = $schedule_name . $this->action_group_suffix;
384
385
		// make sure there are no tasks already.
386
		$current_tasks = as_get_scheduled_actions(
387
			array(
388
				'hook'  => $this->schedulable_classes[ $schedule_name ]['initializer'],
389
				'group' => $action_group_name,
390
			),
391
			ARRAY_A
392
		);
393
394
		// exit if there are already tasks; they'll be saved if the option data changed.
395
		if ( ! empty( $current_tasks ) ) {
396
			return $new_schedule;
397
		}
398
399
		$this->set_action_schedule( $schedule_name, $action_group_name );
400
401
		return $new_schedule;
402
403
	}
404
405
	/**
406
	 * Update recurring tasks for ActionScheduler if options change
407
	 *
408
	 * @param string $old_schedule the old option value.
409
	 * @param string $new_schedule the new, unserialized option value.
410
	 * @param string $option_name option name.
411
	 */
412
	public function change_action_schedule( $old_schedule, $new_schedule, $option_name ) {
413
414
		// this method does not run if the option's data is unchanged.
415
416
		// get the current schedule name from the task, based on pattern in the foreach.
417
		preg_match( '/' . $this->option_prefix . '(.*)_schedule/', $option_name, $matches );
418
		$schedule_name     = $matches[1];
419
		$action_group_name = $schedule_name . $this->action_group_suffix;
420
421
		$this->set_action_schedule( $schedule_name, $action_group_name );
422
423
	}
424
425
	/**
426
	 * Set up recurring tasks for ActionScheduler
427
	 *
428
	 * @param string $schedule_name the name of the schedule.
429
	 * @param string $action_group_name the group's name.
430
	 */
431
	private function set_action_schedule( $schedule_name, $action_group_name ) {
432
		// exit if there is no initializer property on this schedule.
433
		if ( ! isset( $this->schedulable_classes[ $schedule_name ]['initializer'] ) ) {
434
			return;
435
		}
436
437
		// cancel previous task.
438
		$this->queue->cancel(
439
			$this->schedulable_classes[ $schedule_name ]['initializer'],
440
			array(),
441
			$action_group_name
442
		);
443
444
		// create new recurring task for ActionScheduler to check for data to pull from Salesforce.
445
		$this->queue->schedule_recurring(
446
			time(), // plugin seems to expect UTC.
447
			$this->queue->get_frequency( $schedule_name, 'seconds' ),
448
			$this->schedulable_classes[ $schedule_name ]['initializer'],
449
			array(),
450
			$action_group_name
451
		);
452
	}
453
454
	/**
455
	 * When it finishes its migration, resave the scheduled tasks for ActionScheduler.
456
	 */
457
	public function resave_action_schedules() {
458
		// for each schedulable action, go ahead and resave it.
459
		$schedules_updated  = array();
460
		$schedules_restored = array();
461
		foreach ( $this->schedulable_classes as $key => $value ) {
462
			// make sure it has an initializer property; this is used on recurring tasks.
463
			if ( isset( $value['initializer'] ) ) {
464
				// toggle the schedule number setting.
465
				$schedule_option_name  = $this->option_prefix . $key . '_schedule_number';
466
				$previous_option_value = get_option( $schedule_option_name, 0 );
467
				$previous_option_value = filter_var( $previous_option_value, FILTER_SANITIZE_NUMBER_INT );
468
				$new_option_value      = $previous_option_value + 1;
469
				$schedule_updated      = update_option( $schedule_option_name, $new_option_value );
470
				if ( true === $schedule_updated ) {
471
					$schedules_updated[] = $key;
472
					$schedule_restored   = update_option( $schedule_option_name, $previous_option_value );
473
					if ( true === $schedule_restored ) {
474
						$schedules_restored[] = $key;
475
					}
476
				}
477
			}
478
		}
479
480
		// create a log entry from the updated scheduled tasks.
481
		if ( ! empty( $schedules_updated ) || ! empty( $schedules_restored ) ) {
482
			$status = 'success';
483
		} else {
484
			$status = 'error';
485
		}
486
		$body = sprintf( esc_html__( 'These are the scheduled tasks that were updated: ', 'object-sync-for-salesforce' ) . '<ul>' );
487
		foreach ( $schedules_updated as $schedule_updated ) {
488
			$body .= sprintf(
489
				// translators: placeholders are: 1) the schedule name.
490
				'<li>' . esc_html__( 'Schedule name: %1$s.', 'object-sync-for-salesforce' ) . '</li>',
491
				esc_attr( $schedule_updated )
492
			);
493
		}
494
		$body .= '</ul>';
495
		$body .= sprintf( esc_html__( 'These are the scheduled tasks that have the same frequency as they had pre-migration: ', 'object-sync-for-salesforce' ) . '<ul>' );
496
		foreach ( $schedules_restored as $schedule_restored ) {
497
			$body .= sprintf(
498
				// translators: placeholders are: 1) the schedule name.
499
				'<li>' . esc_html__( 'Schedule name: %1$s.', 'object-sync-for-salesforce' ) . '</li>',
500
				esc_attr( $schedule_restored )
501
			);
502
		}
503
		$body .= '</ul>';
504
		$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' ) );
505
		$body .= sprintf(
506
			// translators: %1$s is the schedule settings URL.
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' ),
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

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

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

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

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

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

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

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

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

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

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

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