Passed
Push — 422-fieldmap-inactive-field ( 979c02...767187 )
by Jonathan
03:10
created

Object_Sync_Sf_Mapping::map_params()   F

Complexity

Conditions 48
Paths 12454

Size

Total Lines 218
Code Lines 117

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 48
eloc 117
c 2
b 1
f 0
nc 12454
nop 6
dl 0
loc 218
rs 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Map objects and records between WordPress and Salesforce
4
 *
5
 * @class   Object_Sync_Sf_Mapping
6
 * @package Object_Sync_Salesforce
7
 */
8
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * Object_Sync_Sf_Mapping class.
13
 */
14
class Object_Sync_Sf_Mapping {
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
	 * Object_Sync_Sf_Logging class
53
	 *
54
	 * @var object
55
	 */
56
	public $logging;
57
58
	/**
59
	 * The database table for fieldmaps
60
	 *
61
	 * @var string
62
	 */
63
	public $fieldmap_table;
64
65
	/**
66
	 * The database table for object maps
67
	 *
68
	 * @var string
69
	 */
70
	public $object_map_table;
71
72
	/**
73
	 * Possible status values for fieldmaps
74
	 *
75
	 * @var array
76
	 */
77
	public $fieldmap_statuses;
78
79
	/**
80
	 * The active status values for fieldmaps
81
	 *
82
	 * @var string
83
	 */
84
	public $active_fieldmap_conditions;
85
86
	/**
87
	 * Bitmap value for when sync is off
88
	 *
89
	 * @var string
90
	 */
91
	public $sync_off;
92
93
	/**
94
	 * Bitmap value for when sync is is on for WordPress create events
95
	 *
96
	 * @var string
97
	 */
98
	public $sync_wordpress_create;
99
100
	/**
101
	 * Bitmap value for when sync is is on for WordPress update events
102
	 *
103
	 * @var string
104
	 */
105
	public $sync_wordpress_update;
106
107
	/**
108
	 * Bitmap value for when sync is is on for WordPress delete events
109
	 *
110
	 * @var string
111
	 */
112
	public $sync_wordpress_delete;
113
114
	/**
115
	 * Bitmap value for when sync is is on for Salesforce create events
116
	 *
117
	 * @var string
118
	 */
119
	public $sync_sf_create;
120
121
	/**
122
	 * Bitmap value for when sync is is on for Salesforce update events
123
	 *
124
	 * @var string
125
	 */
126
	public $sync_sf_update;
127
128
	/**
129
	 * Bitmap value for when sync is is on for Salesforce delete events
130
	 *
131
	 * @var string
132
	 */
133
	public $sync_sf_delete;
134
135
	/**
136
	 * Which events are run by WordPress
137
	 *
138
	 * @var string
139
	 */
140
	public $wordpress_events;
141
142
	/**
143
	 * Which events are run by Salesforce
144
	 *
145
	 * @var string
146
	 */
147
	public $salesforce_events;
148
149
	/**
150
	 * The direction from WordPress to Salesforce
151
	 *
152
	 * @var string
153
	 */
154
	public $direction_wordpress_sf;
155
156
	/**
157
	 * The direction from Salesforce to WordPress
158
	 *
159
	 * @var string
160
	 */
161
	public $direction_sf_wordpress;
162
163
	/**
164
	 * The direction to sync both ways
165
	 *
166
	 * @var string
167
	 */
168
	public $direction_sync;
169
170
	/**
171
	 * WordPress directions, including sync
172
	 *
173
	 * @var string
174
	 */
175
	public $direction_wordpress;
176
177
	/**
178
	 * Salesforce directions, including sync
179
	 *
180
	 * @var string
181
	 */
182
	public $direction_salesforce;
183
184
	/**
185
	 * Default record type when using a Salesforce object that has a default or Master record type
186
	 *
187
	 * @var string
188
	 */
189
	public $salesforce_default_record_type;
190
191
	/**
192
	 * Delimiter for arrays coming from Salesforce
193
	 *
194
	 * @var string
195
	 */
196
	public $array_delimiter;
197
198
	/**
199
	 * Data in Salesforce that is stored as an array
200
	 *
201
	 * @var string
202
	 */
203
	public $array_types_from_salesforce;
204
205
	/**
206
	 * Data in Salesforce that is stored as a date
207
	 *
208
	 * @var string
209
	 */
210
	public $date_types_from_salesforce;
211
212
	/**
213
	 * Data in Salesforce that is stored as an integer
214
	 *
215
	 * @var string
216
	 */
217
	public $int_types_from_salesforce;
218
219
	/**
220
	 * How long can a mapping field be
221
	 *
222
	 * @var int
223
	 */
224
	public $name_length;
225
226
	/**
227
	 * Status flag for success
228
	 *
229
	 * @var int
230
	 */
231
	public $status_success;
232
233
	/**
234
	 * Status flag for error
235
	 *
236
	 * @var int
237
	 */
238
	public $status_error;
239
240
	/**
241
	 * Option value for whether the plugin is in debug mode
242
	 *
243
	 * @var string
244
	 */
245
	public $debug;
246
247
	/**
248
	 * Constructor for mapping class
249
	 */
250
	public function __construct() {
251
		$this->version       = object_sync_for_salesforce()->version;
252
		$this->file          = object_sync_for_salesforce()->file;
253
		$this->wpdb          = object_sync_for_salesforce()->wpdb;
254
		$this->slug          = object_sync_for_salesforce()->slug;
255
		$this->option_prefix = object_sync_for_salesforce()->option_prefix;
256
257
		$this->logging = object_sync_for_salesforce()->logging;
258
259
		$this->fieldmap_table   = $this->wpdb->prefix . 'object_sync_sf_field_map';
260
		$this->object_map_table = $this->wpdb->prefix . 'object_sync_sf_object_map';
261
262
		$this->fieldmap_statuses          = array( 'active', 'inactive', 'any' );
263
		$this->active_fieldmap_conditions = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('fieldmap_status' => 'active') of type array<string,string> is incompatible with the declared type string of property $active_fieldmap_conditions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
264
			'fieldmap_status' => 'active',
265
		);
266
267
		/*
268
		 * These parameters are how we define when syncing should occur on each field map.
269
		 * They get used in the admin settings, as well as the push/pull methods to see if something should happen.
270
		*/
271
		$this->sync_off              = 'off';
272
		$this->sync_wordpress_create = 'wp_create';
273
		$this->sync_wordpress_update = 'wp_update';
274
		$this->sync_wordpress_delete = 'wp_delete';
275
		$this->sync_sf_create        = 'sf_create';
276
		$this->sync_sf_update        = 'sf_update';
277
		$this->sync_sf_delete        = 'sf_delete';
278
279
		// deprecated bit flags from version 1.x. Deprecated since 2.0.0.
280
		$this->sync_off_v1              = 0x0000;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_off_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
281
		$this->sync_wordpress_create_v1 = 0x0001;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_wordpress_create_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
282
		$this->sync_wordpress_update_v1 = 0x0002;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_wordpress_update_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
283
		$this->sync_wordpress_delete_v1 = 0x0004;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_wordpress_delete_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
284
		$this->sync_sf_create_v1        = 0x0008;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_sf_create_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
285
		$this->sync_sf_update_v1        = 0x0010;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_sf_update_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
286
		$this->sync_sf_delete_v1        = 0x0020;
0 ignored issues
show
Bug Best Practice introduced by
The property sync_sf_delete_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
287
288
		// Define which events are initialized by which system.
289
		$this->wordpress_events  = array( $this->sync_wordpress_create, $this->sync_wordpress_update, $this->sync_wordpress_delete );
0 ignored issues
show
Documentation Bug introduced by
It seems like array($this->sync_wordpr...>sync_wordpress_delete) of type array<integer,string> is incompatible with the declared type string of property $wordpress_events.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
290
		$this->salesforce_events = array( $this->sync_sf_create, $this->sync_sf_update, $this->sync_sf_delete );
0 ignored issues
show
Documentation Bug introduced by
It seems like array($this->sync_sf_cre... $this->sync_sf_delete) of type array<integer,string> is incompatible with the declared type string of property $salesforce_events.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
291
292
		// deprecated bit flags from version 1.x. Deprecated since 2.0.0.
293
		$this->wordpress_events_v1  = array( $this->sync_wordpress_create_v1, $this->sync_wordpress_update_v1, $this->sync_wordpress_delete_v1 );
0 ignored issues
show
Bug Best Practice introduced by
The property wordpress_events_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
294
		$this->salesforce_events_v1 = array( $this->sync_sf_create_v1, $this->sync_sf_update_v1, $this->sync_sf_delete_v1 );
0 ignored issues
show
Bug Best Practice introduced by
The property salesforce_events_v1 does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
295
296
		// Constants for the directions to map things.
297
		$this->direction_wordpress_sf = 'wp_sf';
298
		$this->direction_sf_wordpress = 'sf_wp';
299
		$this->direction_sync         = 'sync';
300
301
		$this->direction_wordpress  = array( $this->direction_wordpress_sf, $this->direction_sync );
0 ignored issues
show
Documentation Bug introduced by
It seems like array($this->direction_w... $this->direction_sync) of type array<integer,string> is incompatible with the declared type string of property $direction_wordpress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
302
		$this->direction_salesforce = array( $this->direction_sf_wordpress, $this->direction_sync );
0 ignored issues
show
Documentation Bug introduced by
It seems like array($this->direction_s... $this->direction_sync) of type array<integer,string> is incompatible with the declared type string of property $direction_salesforce.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
303
304
		// This is used when we map a record with default or Master.
305
		$this->salesforce_default_record_type = 'default';
306
307
		// Salesforce has multipicklists and they have a delimiter.
308
		$this->array_delimiter = ';';
309
		// What data types in Salesforce should be an array?
310
		$this->array_types_from_salesforce = array( 'multipicklist' );
0 ignored issues
show
Documentation Bug introduced by
It seems like array('multipicklist') of type array<integer,string> is incompatible with the declared type string of property $array_types_from_salesforce.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
311
		// What data types in Salesforce should be a date field?
312
		$this->date_types_from_salesforce = array( 'date', 'datetime' );
0 ignored issues
show
Documentation Bug introduced by
It seems like array('date', 'datetime') of type array<integer,string> is incompatible with the declared type string of property $date_types_from_salesforce.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
313
		// What data types in Salesforce should be an integer?
314
		$this->int_types_from_salesforce = array( 'integer', 'boolean' );
0 ignored issues
show
Documentation Bug introduced by
It seems like array('integer', 'boolean') of type array<integer,string> is incompatible with the declared type string of property $int_types_from_salesforce.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
315
316
		// Max length for a mapping field.
317
		$this->name_length = 128;
318
319
		// Statuses for object sync.
320
		$this->status_success = 1;
321
		$this->status_error   = 0;
322
323
		$this->debug = get_option( $this->option_prefix . 'debug_mode', false );
0 ignored issues
show
Documentation Bug introduced by
It seems like get_option($this->option... . 'debug_mode', false) can also be of type false. However, the property $debug is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
324
		$this->debug = filter_var( $this->debug, FILTER_VALIDATE_BOOLEAN );
325
326
	}
327
328
	/**
329
	 * Create a fieldmap row between a WordPress and Salesforce object
330
	 *
331
	 * @param array $posted The results of $_POST.
332
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
333
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
334
	 * @return int  the last inserted ID.
335
	 */
336
	public function create_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
337
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
338
		if ( ! isset( $posted['version'] ) && version_compare( $this->version, '1.2.5', '>=' ) ) {
339
			$data['version'] = $this->version;
340
		}
341
		$insert = $this->wpdb->insert( $this->fieldmap_table, $data );
342
		if ( 1 === $insert ) {
343
			return $this->wpdb->insert_id;
344
		} else {
345
			return false;
346
		}
347
	}
348
349
	/**
350
	 * Get one or more fieldmap rows between a WordPress and Salesforce object
351
	 *
352
	 * @param int   $id The ID of a desired mapping.
353
	 * @param array $conditions Array of key=>value to match the mapping by.
354
	 * @param bool  $reset Unused parameter.
355
	 * @return array $map a single mapping or $mappings, an array of mappings.
356
	 */
357
	public function get_fieldmaps( $id = null, $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

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

357
	public function get_fieldmaps( $id = null, $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
358
		$table = $this->fieldmap_table;
359
		if ( null !== $id ) { // get one fieldmap.
360
			$map        = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = ' . $id, ARRAY_A );
361
			$mappings   = array();
362
			$mappings[] = $map;
363
			$mappings   = $this->prepare_fieldmap_data( $mappings );
364
			$map        = $mappings[0];
365
			return $map;
366
		} elseif ( ! empty( $conditions ) ) { // get multiple but with a limitation.
367
			$mappings    = array();
368
			$record_type = '';
369
370
			// Assemble the SQL.
371
			if ( ! empty( $conditions ) ) {
372
				$where = '';
373
				$i     = 0;
374
				foreach ( $conditions as $key => $value ) {
375
					// if 'any' is the value for fieldmap status, we keep it off the WHERE statement.
376
					if ( 'fieldmap_status' === $key && 'any' === $value ) {
377
						continue;
378
					}
379
					if ( 'salesforce_record_type' === $key ) {
380
						$record_type = sanitize_text_field( $value );
381
					} else {
382
						$i++;
383
						if ( $i > 1 ) {
384
							$where .= ' AND ';
385
						}
386
						$where .= '`' . $key . '` = "' . $value . '"';
387
					}
388
				}
389
				if ( '' !== $where ) {
0 ignored issues
show
introduced by
The condition '' !== $where is always false.
Loading history...
390
					$where = ' WHERE ' . $where;
391
				}
392
			} else {
393
				$where = '';
394
			}
395
396
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . ' ORDER BY `fieldmap_status`, `weight`', ARRAY_A );
397
398
			if ( ! empty( $mappings ) ) {
399
				$mappings = $this->prepare_fieldmap_data( $mappings, $record_type );
400
			}
401
402
			return $mappings;
403
404
		} else { // get all of the mappings. ALL THE MAPPINGS.
405
406
			// This is the default query for loading fieldmaps.
407
			$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `fieldmap_status`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `pull_to_drafts`, `weight`, `version` FROM $table ORDER BY `fieldmap_status`", ARRAY_A );
408
409
			// lower than 2.0.0 versions.
410
			// @deprecated
411
			// will be removed in version 3.0.0.
412
			if ( version_compare( $this->version, '2.0.0', '<' ) ) {
413
				// if the version is greater than or equal to 1.5.0, the fieldmap table has a pull_to_drafts column.
414
				if ( version_compare( $this->version, '1.5.0', '>=' ) ) {
415
					$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `pull_to_drafts`, `weight`, `version` FROM $table", ARRAY_A );
416
				} elseif ( version_compare( $this->version, '1.2.5', '>=' ) ) {
417
					// if the version is greater than or equal to 1.2.5, the fieldmap table has a version column.
418
					$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `weight`, `version` FROM $table", ARRAY_A );
419
				} else {
420
					$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `weight` FROM $table", ARRAY_A );
421
				}
422
			}
423
424
			if ( ! empty( $mappings ) ) {
425
				$mappings = $this->prepare_fieldmap_data( $mappings );
426
			}
427
428
			return $mappings;
429
		} // End if statement.
430
	}
431
432
	/**
433
	 * For a mapping, get the fieldmaps associated with it.
434
	 *
435
	 * @param array $mapping The mapping for which we are getting the fieldmaps.
436
	 * @param array $directions The direction of the mapping: from WP to SF or vice-versa.
437
	 * @see Object_Sync_Sf_Salesforce_Pull::get_pull_query()
438
	 * @return array of mapped fields
439
	 */
440
	public function get_mapped_fields( $mapping, $directions = array() ) {
441
		$mapped_fields = array();
442
		foreach ( $mapping['fields'] as $fields ) {
443
			if ( empty( $directions ) || in_array( $fields['direction'], $directions, true ) ) {
444
445
				// in version 1.2.0, we provided an option for API name vs label for Salesforce fields.
446
				if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fields['salesforce_field']['name'] ) ) {
447
					$array_key = 'name';
448
				} else {
449
					$array_key = 'label';
450
				}
451
452
				// Some field map types (Relation) store a collection of SF objects.
453
				if ( is_array( $fields['salesforce_field'] ) && ! isset( $fields['salesforce_field'][ $array_key ] ) ) {
454
					foreach ( $fields['salesforce_field'] as $sf_field ) {
455
						$mapped_fields[ $sf_field[ $array_key ] ] = $sf_field[ $array_key ];
456
					}
457
				} else { // The rest are just a name/value pair.
458
					$mapped_fields[ $fields['salesforce_field'][ $array_key ] ] = $fields['salesforce_field'][ $array_key ];
459
				}
460
			}
461
		}
462
463
		if ( ! empty( $this->get_mapped_record_types ) ) {
464
			$mapped_fields['RecordTypeId'] = 'RecordTypeId';
465
		}
466
467
		return $mapped_fields;
468
	}
469
470
	/**
471
	 * Get the mapped record types for a given mapping.
472
	 *
473
	 * @param array $mapping A mapping from which we wish to estract the record type.
474
	 * @return array of mappings. Empty if the mapping's record type is default, else full of the record types.
475
	 */
476
	public function get_mapped_record_types( $mapping ) {
477
		return $mapping['salesforce_record_type_default'] === $this->salesforce_default_record_type ? array() : array_filter( maybe_unserialize( $mapping['salesforce_record_types_allowed'] ) );
478
	}
479
480
	/**
481
	 * Update a fieldmap row between a WordPress and Salesforce object
482
	 *
483
	 * @param array $posted It's $_POST.
484
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
485
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
486
	 * @param int   $id The ID of the mapping.
487
	 * @return boolean whether it was updated
488
	 */
489
	public function update_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array(), $id = '' ) {
490
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
491
		if ( version_compare( $this->version, '1.2.5', '>=' ) && ! isset( $data['updated'] ) ) {
492
			$data['version'] = $this->version;
493
		}
494
		$update = $this->wpdb->update(
495
			$this->fieldmap_table,
496
			$data,
497
			array(
498
				'id' => $id,
499
			)
500
		);
501
		if ( false === $update ) {
502
			return false;
503
		} else {
504
			return true;
505
		}
506
	}
507
508
	/**
509
	 * Setup fieldmap data
510
	 * Sets up the database entry for mapping the object types between Salesforce and WordPress
511
	 *
512
	 * @param array $posted It's $_POST.
513
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
514
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
515
	 * @return array $data the fieldmap's data for the database
516
	 */
517
	private function setup_fieldmap_data( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
518
		$data = array(
519
			'label'             => $posted['label'],
520
			'name'              => sanitize_title( $posted['label'] ),
521
			'salesforce_object' => $posted['salesforce_object'],
522
			'wordpress_object'  => $posted['wordpress_object'],
523
		);
524
		// when importing a fieldmap, there might already be a saved version. if there is, keep it.
525
		$data['version'] = isset( $posted['version'] ) ? $posted['version'] : $this->version;
526
		if ( isset( $posted['wordpress_field'] ) && is_array( $posted['wordpress_field'] ) && isset( $posted['salesforce_field'] ) && is_array( $posted['salesforce_field'] ) ) {
527
			$setup['fields'] = array();
528
			foreach ( $posted['wordpress_field'] as $key => $value ) {
529
				$method_key = array_search( $value, array_column( $wordpress_fields, 'key' ), true );
530
				if ( ! isset( $posted['direction'][ $key ] ) ) {
531
					$posted['direction'][ $key ] = 'sync';
532
				}
533
				if ( ! isset( $posted['is_prematch'][ $key ] ) ) {
534
					$posted['is_prematch'][ $key ] = false;
535
				}
536
				if ( ! isset( $posted['is_key'][ $key ] ) ) {
537
					$posted['is_key'][ $key ] = false;
538
				}
539
				if ( ! isset( $posted['is_delete'][ $key ] ) ) {
540
					$posted['is_delete'][ $key ] = false;
541
				}
542
				if ( false === $posted['is_delete'][ $key ] ) {
543
					// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
544
					$updateable_key = array_search( $posted['salesforce_field'][ $key ], array_column( $salesforce_fields, 'name' ), true );
545
546
					$salesforce_field_attributes = array();
547
					foreach ( $salesforce_fields[ $updateable_key ] as $sf_key => $sf_value ) {
548
						if ( isset( $sf_value ) && ! is_array( $sf_value ) ) {
549
							$salesforce_field_attributes[ $sf_key ] = esc_attr( $sf_value );
550
						} elseif ( ! empty( $sf_value ) && is_array( $sf_value ) ) {
551
							$salesforce_field_attributes[ $sf_key ] = maybe_unserialize( $sf_value );
0 ignored issues
show
Bug introduced by
$sf_value of type array is incompatible with the type string expected by parameter $data of maybe_unserialize(). ( Ignorable by Annotation )

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

551
							$salesforce_field_attributes[ $sf_key ] = maybe_unserialize( /** @scrutinizer ignore-type */ $sf_value );
Loading history...
552
						} else {
553
							$salesforce_field_attributes[ $sf_key ] = '';
554
						}
555
					}
556
557
					$setup['fields'][ $key ] = array(
558
						'wordpress_field'  => array(
559
							'label'   => sanitize_text_field( $posted['wordpress_field'][ $key ] ),
560
							'methods' => maybe_unserialize( $wordpress_fields[ $method_key ]['methods'] ),
561
							'type'    => isset( $wordpress_fields[ $method_key ]['type'] ) ? sanitize_text_field( $wordpress_fields[ $method_key ]['type'] ) : 'text',
562
						),
563
						'salesforce_field' => $salesforce_field_attributes,
564
						'is_prematch'      => sanitize_text_field( $posted['is_prematch'][ $key ] ),
565
						'is_key'           => sanitize_text_field( $posted['is_key'][ $key ] ),
566
						'direction'        => sanitize_text_field( $posted['direction'][ $key ] ),
567
						'is_delete'        => sanitize_text_field( $posted['is_delete'][ $key ] ),
568
					);
569
570
					// If the WordPress key or the Salesforce key are blank, remove this incomplete mapping.
571
					// This prevents https://github.com/MinnPost/object-sync-for-salesforce/issues/82 .
572
					if (
573
						empty( $setup['fields'][ $key ]['wordpress_field']['label'] )
574
						||
575
						empty( $setup['fields'][ $key ]['salesforce_field']['name'] )
576
					) {
577
						unset( $setup['fields'][ $key ] );
578
					}
579
				}
580
			} // End foreach() on WordPress fields.
581
			$data['fields'] = maybe_serialize( $setup['fields'] );
582
		} elseif ( isset( $posted['fields'] ) && is_array( $posted['fields'] ) ) {
583
			// if $posted['fields'] is already set, use that.
584
			$data['fields'] = maybe_serialize( $posted['fields'] );
585
		} // End if() WordPress fields are present.
586
587
		if ( isset( $posted['salesforce_record_types_allowed'] ) ) {
588
			$data['salesforce_record_types_allowed'] = maybe_serialize( $posted['salesforce_record_types_allowed'] );
589
		} else {
590
			$data['salesforce_record_types_allowed'] = maybe_serialize(
591
				array(
592
					$this->salesforce_default_record_type => $this->salesforce_default_record_type,
593
				)
594
			);
595
		}
596
		if ( isset( $posted['salesforce_record_type_default'] ) ) {
597
			$data['salesforce_record_type_default'] = $posted['salesforce_record_type_default'];
598
		} else {
599
			$data['salesforce_record_type_default'] = maybe_serialize( $this->salesforce_default_record_type );
600
		}
601
		if ( isset( $posted['pull_trigger_field'] ) ) {
602
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
603
		}
604
		if ( isset( $posted['sync_triggers'] ) && is_array( $posted['sync_triggers'] ) ) {
605
			$setup['sync_triggers'] = array();
606
			foreach ( $posted['sync_triggers'] as $key => $value ) {
607
				$setup['sync_triggers'][ $key ] = esc_html( $posted['sync_triggers'][ $key ] );
608
			}
609
			// format the sync triggers. if necessary, update the database.
610
			$sync_triggers          = $this->maybe_upgrade_sync_triggers( $setup['sync_triggers'], $data['version'] );
611
			$setup['sync_triggers'] = $sync_triggers;
612
		} else {
613
			$setup['sync_triggers'] = array();
614
		}
615
		$data['sync_triggers'] = maybe_serialize( $setup['sync_triggers'] );
616
		if ( isset( $posted['pull_trigger_field'] ) ) {
617
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
618
		}
619
		$data['push_async']     = isset( $posted['push_async'] ) ? $posted['push_async'] : '';
620
		$data['push_drafts']    = isset( $posted['push_drafts'] ) ? $posted['push_drafts'] : '';
621
		$data['pull_to_drafts'] = isset( $posted['pull_to_drafts'] ) ? $posted['pull_to_drafts'] : '';
622
		$data['weight']         = isset( $posted['weight'] ) ? $posted['weight'] : '';
623
		return $data;
624
	}
625
626
	/**
627
	 * Delete a fieldmap row between a WordPress and Salesforce object
628
	 *
629
	 * @param int $id The ID of a field mapping.
630
	 * @return bool whether it was deleted
631
	 */
632
	public function delete_fieldmap( $id = '' ) {
633
		$data   = array(
634
			'id' => $id,
635
		);
636
		$delete = $this->wpdb->delete( $this->fieldmap_table, $data );
637
		if ( 1 === $delete ) {
638
			return true;
639
		} else {
640
			return false;
641
		}
642
	}
643
644
	/**
645
	 * Create an object map row between a WordPress and Salesforce object
646
	 *
647
	 * @param array $posted It's $_POST.
648
	 * @return false|int of field mapping between WordPress and Salesforce objects
649
	 */
650
	public function create_object_map( $posted = array() ) {
651
		$data            = $this->setup_object_map_data( $posted );
652
		$data['created'] = current_time( 'mysql' );
653
		// Check to see if we don't know the salesforce id and it is not a temporary id, or if this is pending.
654
		// If it is using a temporary id, the map will get updated after it finishes running; it won't call this method unless there's an error, which we should log.
655
		if ( substr( $data['salesforce_id'], 0, 7 ) !== 'tmp_sf_' || ( isset( $data['action'] ) && 'pending' === $data['action'] ) ) {
656
			unset( $data['action'] );
657
			$insert = $this->wpdb->insert( $this->object_map_table, $data );
658
		} else {
659
			$status = 'error';
660
			if ( isset( $this->logging ) ) {
661
				$logging = $this->logging;
662
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
663
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
0 ignored issues
show
Unused Code introduced by
The call to Object_Sync_Sf_Logging::__construct() has too many arguments starting with $this->wpdb. ( Ignorable by Annotation )

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

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

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

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

Loading history...
664
			}
665
			$logging->setup(
666
				sprintf(
667
					// translators: %1$s is the log status, %2$s is the name of a WordPress object. %3$s is the id of that object.
668
					esc_html__( '%1$s Mapping: error caused by trying to map the WordPress %2$s with ID of %3$s to Salesforce ID starting with "tmp_sf_", which is invalid.', 'object-sync-for-salesforce' ),
669
					ucfirst( esc_attr( $status ) ),
670
					esc_attr( $data['wordpress_object'] ),
671
					absint( $data['wordpress_id'] )
672
				),
673
				'',
674
				0,
675
				0,
676
				$status
677
			);
678
			return false;
679
		}
680
		if ( 1 === $insert ) {
681
			return $this->wpdb->insert_id;
682
		} elseif ( false !== strpos( $this->wpdb->last_error, 'Duplicate entry' ) ) {
683
			// this error should never happen now, I think. But let's watch and see.
684
			$mapping = $this->load_all_by_salesforce( $data['salesforce_id'] )[0];
685
			$id      = $mapping['id'];
686
			$status  = 'error';
687
			if ( isset( $this->logging ) ) {
688
				$logging = $this->logging;
689
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
690
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
691
			}
692
			$logging->setup(
693
				sprintf(
694
					// translators: %1$s is the status word "Error". %2$s is the Id of a Salesforce object. %3$s is the ID of a mapping object.
695
					esc_html__( '%1$s: Mapping: there is already a WordPress object mapped to the Salesforce object %2$s and the mapping object ID is %3$s', 'object-sync-for-salesforce' ),
696
					ucfirst( esc_attr( $status ) ),
697
					esc_attr( $data['salesforce_id'] ),
698
					absint( $id )
699
				),
700
				print_r( $mapping, true ), // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
701
				0,
702
				0,
703
				$status
704
			);
705
			return $id;
706
		} else {
707
			return false;
708
		}
709
	}
710
711
	/**
712
	 * Get all object map rows between WordPress and Salesforce objects.
713
	 *
714
	 * This replaces previous functionality that would return a single object map if there was only one, rather than a multi-dimensional array.
715
	 *
716
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
717
	 * @param bool  $reset Unused parameter.
718
	 * @return $mappings
0 ignored issues
show
Documentation Bug introduced by
The doc comment $mappings at position 0 could not be parsed: Unknown type name '$mappings' at position 0 in $mappings.
Loading history...
719
	 */
720
	public function get_all_object_maps( $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

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

720
	public function get_all_object_maps( $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
721
		$table = $this->object_map_table;
722
		$order = ' ORDER BY object_updated, created';
723
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
724
			$mappings = array();
725
726
			if ( ! empty( $conditions ) ) {
727
				$where = ' WHERE ';
728
				$i     = 0;
729
				foreach ( $conditions as $key => $value ) {
730
					$i++;
731
					if ( $i > 1 ) {
732
						$where .= ' AND ';
733
					}
734
					$where .= '`' . $key . '` = "' . $value . '"';
735
				}
736
			} else {
737
				$where = '';
738
			}
739
740
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
741
		} else { // get all of the mappings. ALL THE MAPPINGS.
742
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
743
		}
744
745
		return $mappings;
746
747
	}
748
749
	/**
750
	 * Get one or more object map rows between WordPress and Salesforce objects
751
	 *
752
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
753
	 * @param bool  $reset Unused parameter.
754
	 * @return array $map or $mappings
755
	 * @deprecated since 1.8.0
756
	 */
757
	public function get_object_maps( $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

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

757
	public function get_object_maps( $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
758
		$table = $this->object_map_table;
759
		$order = ' ORDER BY object_updated, created';
760
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
761
			$mappings = array();
762
763
			if ( ! empty( $conditions ) ) {
764
				$where = ' WHERE ';
765
				$i     = 0;
766
				foreach ( $conditions as $key => $value ) {
767
					$i++;
768
					if ( $i > 1 ) {
769
						$where .= ' AND ';
770
					}
771
					$where .= '`' . $key . '` = "' . $value . '"';
772
				}
773
			} else {
774
				$where = '';
775
			}
776
777
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
778
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
779
				$mappings = $mappings[0];
780
			}
781
		} else { // get all of the mappings. ALL THE MAPPINGS.
782
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
783
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
784
				$mappings = $mappings[0];
785
			}
786
		}
787
788
		return $mappings;
789
790
	}
791
792
	/**
793
	 * Update an object map row between a WordPress and Salesforce object
794
	 *
795
	 * @param array $posted It's $_POST.
796
	 * @param array $id The ID of the object map row.
797
	 * @return boolean whether it was updated
798
	 */
799
	public function update_object_map( $posted = array(), $id = '' ) {
800
		$data = $this->setup_object_map_data( $posted );
801
		if ( ! isset( $data['object_updated'] ) ) {
802
			$data['object_updated'] = current_time( 'mysql' );
803
		}
804
		$update = $this->wpdb->update(
805
			$this->object_map_table,
806
			$data,
807
			array(
808
				'id' => $id,
809
			)
810
		);
811
		if ( false === $update ) {
812
			return false;
813
		} else {
814
			return true;
815
		}
816
	}
817
818
	/**
819
	 * Setup the data for the object map
820
	 *
821
	 * @param array $posted It's $_POST.
822
	 * @return array $data Filtered array with only the keys that are in the object map database table. Strips out things from WordPress form if they're present.
823
	 */
824
	private function setup_object_map_data( $posted = array() ) {
825
		$allowed_fields   = $this->wpdb->get_col( "DESC {$this->object_map_table}", 0 );
826
		$allowed_fields[] = 'action'; // we use this in both directions even though it isn't in the database; we remove it from the array later if it is present.
827
828
		$data = array_intersect_key( $posted, array_flip( $allowed_fields ) );
829
		return $data;
830
	}
831
832
	/**
833
	 * Delete an object map row between a WordPress and Salesforce object
834
	 *
835
	 * @param int|array $id The ID or IDs of the object map row(s).
836
	 * @return bool whether it was deleted
837
	 */
838
	public function delete_object_map( $id = '' ) {
839
		if ( is_string( $id ) || is_int( $id ) ) {
840
			$data   = array(
841
				'id' => $id,
842
			);
843
			$delete = $this->wpdb->delete( $this->object_map_table, $data );
844
			if ( 1 === $delete ) {
845
				return true;
846
			} else {
847
				return false;
848
			}
849
		} elseif ( is_array( $id ) ) {
0 ignored issues
show
introduced by
The condition is_array($id) is always true.
Loading history...
850
			$ids    = implode( ',', array_map( 'absint', $id ) );
851
			$delete = $this->wpdb->query( "DELETE FROM $this->object_map_table WHERE ID IN ($ids)" );
852
			if ( false !== $delete ) {
853
				return true;
854
			} else {
855
				return false;
856
			}
857
		}
858
	}
859
860
	/**
861
	 * Generate a temporary ID to store while waiting for a push or pull to complete, before the record has been assigned a new ID
862
	 *
863
	 * @param string $direction Whether this is part of a push or pull action.
864
	 * @return string $id is a temporary string that will be replaced if the modification is successful.
865
	 */
866
	public function generate_temporary_id( $direction ) {
867
		if ( 'push' === $direction ) {
868
			$prefix = 'tmp_sf_';
869
		} elseif ( 'pull' === $direction ) {
870
			$prefix = 'tmp_wp_';
871
		}
872
		$id = uniqid( $prefix, true );
873
		return $id;
874
	}
875
876
	/**
877
	 * Returns Salesforce object mappings for a given WordPress object.
878
	 *
879
	 * @param string $object_type Type of object to load.
880
	 * @param int    $object_id Unique identifier of the target object to load.
881
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
882
	 *
883
	 * @return array of object maps
884
	 */
885
	public function load_all_by_wordpress( $object_type, $object_id, $reset = false ) {
886
		$conditions = array(
887
			'wordpress_id'     => $object_id,
888
			'wordpress_object' => $object_type,
889
		);
890
		return $this->get_all_object_maps( $conditions, $reset );
891
	}
892
893
	/**
894
	 * Returns Salesforce object mappings for a given Salesforce object.
895
	 *
896
	 * @param string $salesforce_id Type of object to load.
897
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
898
	 *
899
	 * @return array $maps all the object maps that match the Salesforce Id
900
	 */
901
	public function load_all_by_salesforce( $salesforce_id, $reset = false ) {
902
		$conditions = array(
903
			'salesforce_id' => $salesforce_id,
904
		);
905
906
		$maps = $this->get_all_object_maps( $conditions, $reset );
907
908
		return $maps;
909
	}
910
911
	/**
912
	 * Map values between WordPress and Salesforce objects.
913
	 *
914
	 * @param array  $mapping Mapping object.
915
	 * @param array  $object WordPress or Salesforce object data.
916
	 * @param array  $trigger The thing that triggered this mapping.
917
	 * @param bool   $use_soap Flag to enforce use of the SOAP API.
918
	 * @param bool   $is_new Indicates whether a mapping object for this entity already exists.
919
	 * @param string $object_id_field optionally pass the object id field name.
920
	 * @return array Associative array of key value pairs.
921
	 */
922
	public function map_params( $mapping, $object, $trigger, $use_soap = false, $is_new = true, $object_id_field = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $is_new is not used and could be removed. ( Ignorable by Annotation )

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

922
	public function map_params( $mapping, $object, $trigger, $use_soap = false, /** @scrutinizer ignore-unused */ $is_new = true, $object_id_field = '' ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
923
924
		$params = array();
925
926
		$has_missing_required_salesforce_field = false;
927
		foreach ( $mapping['fields'] as $fieldmap ) {
928
929
			$wordpress_haystack  = array_values( $this->wordpress_events );
0 ignored issues
show
Bug introduced by
$this->wordpress_events of type string is incompatible with the type array expected by parameter $array of array_values(). ( Ignorable by Annotation )

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

929
			$wordpress_haystack  = array_values( /** @scrutinizer ignore-type */ $this->wordpress_events );
Loading history...
930
			$salesforce_haystack = array_values( $this->salesforce_events );
931
932
			$fieldmap['wordpress_field']['methods'] = maybe_unserialize( $fieldmap['wordpress_field']['methods'] );
933
934
			$wordpress_field = $fieldmap['wordpress_field']['label'];
935
936
			if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fieldmap['salesforce_field']['name'] ) ) {
937
				$salesforce_field = $fieldmap['salesforce_field']['name'];
938
				// Load the type of the Salesforce field. We can use this to handle Salesforce field value issues that come up based on what the field sends into WordPress or expects from WordPress.
939
				$salesforce_field_type = $fieldmap['salesforce_field']['type'];
940
			} else {
941
				$salesforce_field = $fieldmap['salesforce_field']['label'];
942
			}
943
944
			// A WordPress event caused this.
945
			if ( in_array( $trigger, array_values( $wordpress_haystack ), true ) ) {
946
947
				// Is the field in WordPress an array, if we unserialize it? Salesforce wants it to be an imploded string.
948
				if ( is_array( maybe_unserialize( $object[ $wordpress_field ] ) ) ) {
949
					// if the WordPress field is a list of capabilities (the source field is wp_capabilities), we need to get the array keys from WordPress to send them to Salesforce.
950
					if ( 'wp_capabilities' === $wordpress_field ) {
951
						$object[ $wordpress_field ] = implode( $this->array_delimiter, array_keys( $object[ $wordpress_field ] ) );
952
					} else {
953
						$object[ $wordpress_field ] = implode( $this->array_delimiter, $object[ $wordpress_field ] );
954
					}
955
				}
956
957
				if ( isset( $salesforce_field_type ) ) {
958
					// Is the Salesforce field a date, and is the WordPress value a valid date?
959
					// According to https://salesforce.stackexchange.com/questions/57032/date-format-with-salesforce-rest-api.
960
					if ( in_array( $salesforce_field_type, $this->date_types_from_salesforce, true ) ) {
0 ignored issues
show
Bug introduced by
$this->date_types_from_salesforce of type string is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

960
					if ( in_array( $salesforce_field_type, /** @scrutinizer ignore-type */ $this->date_types_from_salesforce, true ) ) {
Loading history...
961
						if ( '' === $object[ $wordpress_field ] ) {
962
							$object[ $wordpress_field ] = null;
963
						} else {
964
							if ( false !== strtotime( $object[ $wordpress_field ] ) ) {
965
								$timestamp = strtotime( $object[ $wordpress_field ] );
966
							} else {
967
								$timestamp = $object[ $wordpress_field ];
968
							}
969
							if ( 'datetime' === $salesforce_field_type ) {
970
								$object[ $wordpress_field ] = date_i18n( 'c', $timestamp );
971
							} else {
972
								$object[ $wordpress_field ] = date_i18n( 'Y-m-d', $timestamp );
973
							}
974
						}
975
					}
976
977
					// Boolean SF fields only want real boolean values. NULL is also not allowed.
978
					if ( 'boolean' === $salesforce_field_type ) {
979
						$object[ $wordpress_field ] = (bool) $object[ $wordpress_field ];
980
					}
981
				}
982
983
				$params[ $salesforce_field ] = $object[ $wordpress_field ];
984
985
				// If the field is a key in Salesforce, remove it from $params to avoid upsert errors from Salesforce,
986
				// but still put its name in the params array so we can check for it later.
987
				if ( '1' === $fieldmap['is_key'] ) {
988
					if ( ! $use_soap ) {
989
						unset( $params[ $salesforce_field ] );
990
					}
991
					$params['key'] = array(
992
						'salesforce_field' => $salesforce_field,
993
						'wordpress_field'  => $wordpress_field,
994
						'value'            => $object[ $wordpress_field ],
995
					);
996
				}
997
998
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
999
				if ( '1' === $fieldmap['is_prematch'] ) {
1000
					$params['prematch'] = array(
1001
						'salesforce_field' => $salesforce_field,
1002
						'wordpress_field'  => $wordpress_field,
1003
						'value'            => $object[ $wordpress_field ],
1004
					);
1005
				}
1006
1007
				// Skip fields that aren't being pushed to Salesforce.
1008
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_wordpress ), true ) ) {
1009
					// The trigger is a WordPress trigger, but the fieldmap direction is not a WordPress direction.
1010
					unset( $params[ $salesforce_field ] );
1011
				}
1012
1013
				// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
1014
				// Skip fields that aren't updateable when mapping params because Salesforce will error otherwise.
1015
				// This happens after dealing with the field types because key and prematch should still be available to the plugin, even if the values are not updateable in Salesforce.
1016
				if ( 1 !== (int) $fieldmap['salesforce_field']['updateable'] ) {
1017
					unset( $params[ $salesforce_field ] );
1018
				}
1019
1020
				// This case means the following:
1021
				// this field is expected by the fieldmap
1022
				// Salesforce's api reports that this field is required
1023
				// we do not have a WordPress value for this field, or it's empty
1024
				// it also means the field has not been unset by prematch, updateable, key, or directional flags prior to this check.
1025
				// When this happens, we should flag that we're missing a required Salesforce field.
1026
				if ( in_array( $salesforce_field, $params, true ) && false === filter_var( $fieldmap['salesforce_field']['nillable'], FILTER_VALIDATE_BOOLEAN ) && ( ! isset( $object[ $wordpress_field ] ) || '' === $object[ $wordpress_field ] ) ) {
1027
					$has_missing_required_salesforce_field = true;
1028
				}
1029
1030
				// we don't need a continue with the unset methods because there's no array being created down here.
1031
			} elseif ( in_array( $trigger, $salesforce_haystack, true ) ) {
1032
1033
				// A Salesforce event caused this.
1034
1035
				if ( isset( $salesforce_field_type ) && isset( $object[ $salesforce_field ] ) && ! is_null( $object[ $salesforce_field ] ) ) {
1036
					// Salesforce provides multipicklist values as a delimited string. If the
1037
					// destination field in WordPress accepts multiple values, explode the string into an array and then serialize it.
1038
					if ( in_array( $salesforce_field_type, $this->array_types_from_salesforce, true ) ) {
1039
						$object[ $salesforce_field ] = explode( $this->array_delimiter, $object[ $salesforce_field ] );
1040
						// if the WordPress field is a list of capabilities (the destination field is wp_capabilities), we need to set the array for WordPress to save it.
1041
						if ( 'wp_capabilities' === $wordpress_field ) {
1042
							$capabilities = array();
1043
							foreach ( $object[ $salesforce_field ] as $capability ) {
1044
								$capabilities[ $capability ] = true;
1045
							}
1046
							$object[ $salesforce_field ] = $capabilities;
1047
						}
1048
					}
1049
1050
					// Handle specific data types from Salesforce.
1051
					switch ( $salesforce_field_type ) {
1052
						case ( in_array( $salesforce_field_type, $this->date_types_from_salesforce, true ) ):
1053
							$format = get_option( 'date_format', 'U' );
1054
							if ( isset( $fieldmap['wordpress_field']['type'] ) && 'datetime' === $fieldmap['wordpress_field']['type'] ) {
1055
								$format = 'Y-m-d H:i:s';
1056
							}
1057
							if ( 'tribe_events' === $mapping['wordpress_object'] && class_exists( 'Tribe__Events__Main' ) ) {
1058
								$format = 'Y-m-d H:i:s';
1059
							}
1060
							if ( 'datetime' === $salesforce_field_type ) {
1061
								// Note: the Salesforce REST API appears to always return datetimes as GMT values. We should retrieve them that way, then format them to deal with them in WordPress appropriately.
1062
								// We should not do any converting unless it's a datetime, because if it's a date, Salesforce stores it as midnight. We don't want to convert that.
1063
								$object[ $salesforce_field ] = get_date_from_gmt( $object[ $salesforce_field ], 'Y-m-d\TH:i:s\Z' ); // convert from GMT to local date/time based on WordPress time zone setting.
1064
							}
1065
							$object[ $salesforce_field ] = date_i18n( $format, strtotime( $object[ $salesforce_field ] ) );
1066
							break;
1067
						case ( in_array( $salesforce_field_type, $this->int_types_from_salesforce, true ) ):
1068
							$object[ $salesforce_field ] = isset( $object[ $salesforce_field ] ) ? (int) $object[ $salesforce_field ] : 0;
1069
							break;
1070
						case 'text':
1071
							$object[ $salesforce_field ] = (string) $object[ $salesforce_field ];
1072
							break;
1073
						case 'url':
1074
							$object[ $salesforce_field ] = esc_url_raw( $object[ $salesforce_field ] );
1075
							break;
1076
					}
1077
				}
1078
1079
				// Make an array because we need to store the methods for each field as well.
1080
				if ( isset( $object[ $salesforce_field ] ) ) {
1081
					$params[ $wordpress_field ]          = array();
1082
					$params[ $wordpress_field ]['value'] = $object[ $salesforce_field ];
1083
				} elseif ( is_null( $object[ $salesforce_field ] ) ) {
1084
					// Salesforce returns blank fields as null fields; set them to blank.
1085
					$params[ $wordpress_field ]          = array();
1086
					$params[ $wordpress_field ]['value'] = '';
1087
				} else {
1088
					// prevent fields that don't exist from being passed.
1089
					continue;
1090
				}
1091
1092
				// If the field is a key in Salesforce, disregard since this is caused by a Salesforce event. We're setting up data to be stored in WordPress here, and WordPress is not concerned with external key designations in Salesforce.
1093
1094
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
1095
				if ( '1' === $fieldmap['is_prematch'] ) {
1096
					$params['prematch'] = array(
1097
						'salesforce_field' => $salesforce_field,
1098
						'wordpress_field'  => $wordpress_field,
1099
						'value'            => $object[ $salesforce_field ],
1100
						'method_match'     => isset( $fieldmap['wordpress_field']['methods']['match'] ) ? $fieldmap['wordpress_field']['methods']['match'] : $fieldmap['wordpress_field']['methods']['read'],
1101
						'method_read'      => $fieldmap['wordpress_field']['methods']['read'],
1102
						'method_create'    => $fieldmap['wordpress_field']['methods']['create'],
1103
						'method_update'    => $fieldmap['wordpress_field']['methods']['update'],
1104
					);
1105
				}
1106
1107
				// Skip fields that aren't being pulled from Salesforce.
1108
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_salesforce ), true ) ) {
1109
					// The trigger is a Salesforce trigger, but the fieldmap direction is not a Salesforce direction.
1110
					unset( $params[ $wordpress_field ] );
1111
					// we also need to continue here, so it doesn't create an empty array below for fields that are WordPress -> Salesforce only.
1112
					continue;
1113
				}
1114
1115
				switch ( $trigger ) {
1116
					case $this->sync_sf_create:
1117
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['create'];
1118
						break;
1119
					case $this->sync_sf_update:
1120
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['update'];
1121
						break;
1122
					case $this->sync_sf_delete:
1123
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['delete'];
1124
						break;
1125
				}
1126
1127
				// always allow for the delete and read methods.
1128
				$params[ $wordpress_field ]['method_delete'] = $fieldmap['wordpress_field']['methods']['delete'];
1129
				$params[ $wordpress_field ]['method_read']   = $fieldmap['wordpress_field']['methods']['read'];
1130
1131
			} // End if() statement.
1132
		} // End foreach() loop.
1133
1134
		if ( true === $has_missing_required_salesforce_field ) {
1135
			update_option( $this->option_prefix . 'missing_required_data_id_' . $object[ $object_id_field ], true, false );
1136
			return array();
1137
		}
1138
1139
		return $params;
1140
1141
	}
1142
1143
	/**
1144
	 * Prepare field map data for use
1145
	 *
1146
	 * @param array  $mappings Array of fieldmaps.
1147
	 * @param string $record_type Optional Salesforce record type to see if it is allowed or not.
1148
	 *
1149
	 * @return array $mappings Associative array of field maps ready to use
1150
	 */
1151
	private function prepare_fieldmap_data( $mappings, $record_type = '' ) {
1152
		foreach ( $mappings as $id => $mapping ) {
1153
			$mappings[ $id ]['salesforce_record_types_allowed'] = isset( $mapping['salesforce_record_types_allowed'] ) ? maybe_unserialize( $mapping['salesforce_record_types_allowed'] ) : array();
1154
			$mappings[ $id ]['fields']                          = isset( $mapping['fields'] ) ? maybe_unserialize( $mapping['fields'] ) : array();
1155
			$mappings[ $id ]['sync_triggers']                   = isset( $mapping['sync_triggers'] ) ? maybe_unserialize( $mapping['sync_triggers'] ) : array();
1156
			// format the sync triggers.
1157
			$sync_triggers                    = $this->maybe_upgrade_sync_triggers( $mappings[ $id ]['sync_triggers'], $mapping['version'], $mapping['id'] );
1158
			$mappings[ $id ]['sync_triggers'] = $sync_triggers;
1159
			if ( '' !== $record_type && ! in_array( $record_type, $mappings[ $id ]['salesforce_record_types_allowed'], true ) ) {
1160
				unset( $mappings[ $id ] );
1161
			}
1162
		}
1163
		return $mappings;
1164
	}
1165
1166
	/**
1167
	 * Format the sync trigger values for storage in the database.
1168
	 *
1169
	 * @param array  $sync_triggers Array of sync triggers.
1170
	 * @param string $mapping_version the database version when the fieldmmap was saved.
1171
	 * @param int    $mapping_id if the fieldmap already exists, this is the ID.
1172
	 *
1173
	 * @return array $sync_triggers possibly updated array of sync triggers.
1174
	 */
1175
	private function maybe_upgrade_sync_triggers( $sync_triggers = array(), $mapping_version, $mapping_id = '' ) {
1176
		// in v2 of this plugin, we replaced the bit flags with strings to make them more legible.
1177
		if ( version_compare( $mapping_version, '2.0.0', '<' ) ) {
1178
			// check if the triggers stored in the database are up to date. if not, update them.
1179
			$intersect = array_intersect( $sync_triggers, array_merge( $this->wordpress_events, $this->salesforce_events ) );
0 ignored issues
show
Bug introduced by
$this->wordpress_events of type string is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

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

1179
			$intersect = array_intersect( $sync_triggers, array_merge( /** @scrutinizer ignore-type */ $this->wordpress_events, $this->salesforce_events ) );
Loading history...
1180
			if ( empty( $intersect ) ) {
1181
				$updated_sync_triggers = array();
1182
				foreach ( $sync_triggers as $key => $value ) {
1183
					if ( $value === (string) $this->sync_off_v1 ) {
1184
						$updated_sync_triggers[] = $this->sync_off;
1185
					}
1186
					if ( $value === (string) $this->sync_wordpress_create_v1 ) {
1187
						$updated_sync_triggers[] = $this->sync_wordpress_create;
1188
					}
1189
					if ( $value === (string) $this->sync_wordpress_update_v1 ) {
1190
						$updated_sync_triggers[] = $this->sync_wordpress_update;
1191
					}
1192
					if ( $value === (string) $this->sync_wordpress_delete_v1 ) {
1193
						$updated_sync_triggers[] = $this->sync_wordpress_delete;
1194
					}
1195
					if ( $value === (string) $this->sync_sf_create_v1 ) {
1196
						$updated_sync_triggers[] = $this->sync_sf_create;
1197
					}
1198
					if ( $value === (string) $this->sync_sf_update_v1 ) {
1199
						$updated_sync_triggers[] = $this->sync_sf_update;
1200
					}
1201
					if ( $value === (string) $this->sync_sf_delete_v1 ) {
1202
						$updated_sync_triggers[] = $this->sync_sf_delete;
1203
					}
1204
				}
1205
1206
				if ( '' !== $mapping_id ) {
1207
					// format the fieldmap update query for the database.
1208
					$data = array();
1209
					if ( ! empty( $updated_sync_triggers ) ) {
1210
						$data['sync_triggers'] = array();
1211
						foreach ( $updated_sync_triggers as $key => $value ) {
1212
							$updated_sync_triggers[ $key ] = esc_html( $updated_sync_triggers[ $key ] );
1213
						}
1214
						$data['sync_triggers'] = maybe_serialize( $updated_sync_triggers );
1215
						$data['version']       = get_option( $this->option_prefix . 'db_version', $this->version );
1216
						// update the sync triggers and version fieldmap in the database.
1217
						$update = $this->wpdb->update(
1218
							$this->fieldmap_table,
1219
							$data,
1220
							array(
1221
								'id' => $mapping_id,
1222
							)
1223
						);
1224
					}
1225
				}
1226
			}
1227
		}
1228
		// whether it was updated or not, this is the array of sync triggers.
1229
		return $sync_triggers;
1230
	}
1231
1232
	/**
1233
	 * Check object map table to see if there have been any failed object map create attempts
1234
	 *
1235
	 * @return array $errors Associative array of rows that failed to finish from either system
1236
	 */
1237
	public function get_failed_object_maps() {
1238
		$table                 = $this->object_map_table;
1239
		$errors                = array();
1240
		$items_per_page        = (int) get_option( $this->option_prefix . 'errors_per_page', 50 );
1241
		$current_error_page    = isset( $_GET['error_page'] ) ? (int) $_GET['error_page'] : 1;
1242
		$offset                = ( $current_error_page * $items_per_page ) - $items_per_page;
1243
		$all_errors            = $this->wpdb->get_results( "SELECT * FROM ${table} WHERE salesforce_id LIKE 'tmp_sf_%' OR wordpress_id LIKE 'tmp_wp_%' LIMIT ${offset}, ${items_per_page}", ARRAY_A );
1244
		$errors_total          = $this->wpdb->get_var( "SELECT COUNT(`id`) FROM ${table} WHERE salesforce_id LIKE 'tmp_sf_%' OR wordpress_id LIKE 'tmp_wp_%'" );
1245
		$errors['total_pages'] = ceil( $errors_total / $items_per_page );
1246
		$errors['pagination']  = paginate_links(
1247
			array(
1248
				'base'      => add_query_arg( 'error_page', '%#%' ),
1249
				'format'    => '',
1250
				'total'     => $errors['total_pages'],
1251
				'prev_text' => __( '&laquo;', 'object-sync-for-salesforce' ),
1252
				'next_text' => __( '&raquo;', 'object-sync-for-salesforce' ),
1253
				'current'   => $current_error_page,
1254
			)
1255
		);
1256
		$errors['error_page']  = $current_error_page;
1257
		$errors['all_errors']  = $all_errors;
1258
		$errors['total']       = $errors_total;
1259
		return $errors;
1260
	}
1261
1262
	/**
1263
	 * Check object map table to see if there have been any failed object map create attempts
1264
	 *
1265
	 * @param int $id The ID of a desired mapping.
1266
	 * @return array $error Associative array of single row that failed to finish based on id
1267
	 */
1268
	public function get_failed_object_map( $id ) {
1269
		$table     = $this->object_map_table;
1270
		$error     = array();
1271
		$error_row = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = "' . $id . '"', ARRAY_A );
1272
		if ( ! empty( $error_row ) ) {
1273
			$error = $error_row;
1274
		}
1275
		return $error;
1276
	}
1277
1278
}
1279