Passed
Push — 414-pull-options-class ( cf02a2...21e578 )
by Jonathan
03:57
created

Object_Sync_Sf_Mapping::get_fieldmaps()   C

Complexity

Conditions 15
Paths 15

Size

Total Lines 72
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 44
nc 15
nop 3
dl 0
loc 72
rs 5.9166
c 0
b 0
f 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(
263
			'active'   => esc_html__( 'Active', 'object-sync-for-salesforce' ),
264
			'inactive' => esc_html__( 'Inactive', 'object-sync-for-salesforce' ),
265
			'any'      => '',
266
		);
267
		$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...
268
			'fieldmap_status' => 'active',
269
		);
270
271
		/*
272
		 * These parameters are how we define when syncing should occur on each field map.
273
		 * They get used in the admin settings, as well as the push/pull methods to see if something should happen.
274
		*/
275
		$this->sync_off              = 'off';
276
		$this->sync_wordpress_create = 'wp_create';
277
		$this->sync_wordpress_update = 'wp_update';
278
		$this->sync_wordpress_delete = 'wp_delete';
279
		$this->sync_sf_create        = 'sf_create';
280
		$this->sync_sf_update        = 'sf_update';
281
		$this->sync_sf_delete        = 'sf_delete';
282
283
		// deprecated bit flags from version 1.x. Deprecated since 2.0.0.
284
		$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...
285
		$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...
286
		$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...
287
		$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...
288
		$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...
289
		$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...
290
		$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...
291
292
		// Define which events are initialized by which system.
293
		$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...
294
		$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...
295
296
		// deprecated bit flags from version 1.x. Deprecated since 2.0.0.
297
		$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...
298
		$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...
299
300
		// Constants for the directions to map things.
301
		$this->direction_wordpress_sf = 'wp_sf';
302
		$this->direction_sf_wordpress = 'sf_wp';
303
		$this->direction_sync         = 'sync';
304
305
		$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...
306
		$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...
307
308
		// This is used when we map a record with default or Master.
309
		$this->salesforce_default_record_type = 'default';
310
311
		// Salesforce has multipicklists and they have a delimiter.
312
		$this->array_delimiter = ';';
313
		// What data types in Salesforce should be an array?
314
		$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...
315
		// What data types in Salesforce should be a date field?
316
		$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...
317
		// What data types in Salesforce should be an integer?
318
		$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...
319
320
		// Max length for a mapping field.
321
		$this->name_length = 128;
322
323
		// Statuses for object sync.
324
		$this->status_success = 1;
325
		$this->status_error   = 0;
326
327
		$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...
328
		$this->debug = filter_var( $this->debug, FILTER_VALIDATE_BOOLEAN );
329
330
	}
331
332
	/**
333
	 * Create a fieldmap row between a WordPress and Salesforce object
334
	 *
335
	 * @param array $posted The results of $_POST.
336
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
337
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
338
	 * @return int  the last inserted ID.
339
	 */
340
	public function create_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
341
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
342
		if ( ! isset( $posted['version'] ) && version_compare( $this->version, '1.2.5', '>=' ) ) {
343
			$data['version'] = $this->version;
344
		}
345
		$insert = $this->wpdb->insert( $this->fieldmap_table, $data );
346
		if ( 1 === $insert ) {
347
			return $this->wpdb->insert_id;
348
		} else {
349
			return false;
350
		}
351
	}
352
353
	/**
354
	 * Get one or more fieldmap rows between a WordPress and Salesforce object
355
	 *
356
	 * @param int   $id The ID of a desired mapping.
357
	 * @param array $conditions Array of key=>value to match the mapping by.
358
	 * @param bool  $reset Unused parameter.
359
	 * @return array $map a single mapping or $mappings, an array of mappings.
360
	 */
361
	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

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

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

668
				$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...
669
			}
670
			$logging->setup(
671
				sprintf(
672
					// translators: %1$s is the log status, %2$s is the name of a WordPress object. %3$s is the id of that object.
673
					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' ),
674
					ucfirst( esc_attr( $status ) ),
675
					esc_attr( $data['wordpress_object'] ),
676
					absint( $data['wordpress_id'] )
677
				),
678
				'',
679
				0,
680
				0,
681
				$status
682
			);
683
			return false;
684
		}
685
		if ( 1 === $insert ) {
686
			return $this->wpdb->insert_id;
687
		} elseif ( false !== strpos( $this->wpdb->last_error, 'Duplicate entry' ) ) {
688
			// this error should never happen now, I think. But let's watch and see.
689
			$mapping = $this->load_all_by_salesforce( $data['salesforce_id'] )[0];
690
			$id      = $mapping['id'];
691
			$status  = 'error';
692
			if ( isset( $this->logging ) ) {
693
				$logging = $this->logging;
694
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
695
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
696
			}
697
			$logging->setup(
698
				sprintf(
699
					// 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.
700
					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' ),
701
					ucfirst( esc_attr( $status ) ),
702
					esc_attr( $data['salesforce_id'] ),
703
					absint( $id )
704
				),
705
				print_r( $mapping, true ), // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
706
				0,
707
				0,
708
				$status
709
			);
710
			return $id;
711
		} else {
712
			return false;
713
		}
714
	}
715
716
	/**
717
	 * Get all object map rows between WordPress and Salesforce objects.
718
	 *
719
	 * This replaces previous functionality that would return a single object map if there was only one, rather than a multi-dimensional array.
720
	 *
721
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
722
	 * @param bool  $reset Unused parameter.
723
	 * @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...
724
	 */
725
	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

725
	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...
726
		$table = $this->object_map_table;
727
		$order = ' ORDER BY object_updated, created';
728
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
729
			$mappings = array();
730
731
			if ( ! empty( $conditions ) ) {
732
				$where = ' WHERE ';
733
				$i     = 0;
734
				foreach ( $conditions as $key => $value ) {
735
					$i++;
736
					if ( $i > 1 ) {
737
						$where .= ' AND ';
738
					}
739
					$where .= '`' . $key . '` = "' . $value . '"';
740
				}
741
			} else {
742
				$where = '';
743
			}
744
745
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
746
		} else { // get all of the mappings. ALL THE MAPPINGS.
747
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
748
		}
749
750
		return $mappings;
751
752
	}
753
754
	/**
755
	 * Get one or more object map rows between WordPress and Salesforce objects
756
	 *
757
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
758
	 * @param bool  $reset Unused parameter.
759
	 * @return array $map or $mappings
760
	 * @deprecated since 1.8.0
761
	 */
762
	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

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

927
	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...
928
929
		$params = array();
930
931
		$has_missing_required_salesforce_field = false;
932
		foreach ( $mapping['fields'] as $fieldmap ) {
933
934
			$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

934
			$wordpress_haystack  = array_values( /** @scrutinizer ignore-type */ $this->wordpress_events );
Loading history...
935
			$salesforce_haystack = array_values( $this->salesforce_events );
936
937
			$fieldmap['wordpress_field']['methods'] = maybe_unserialize( $fieldmap['wordpress_field']['methods'] );
938
939
			$wordpress_field = $fieldmap['wordpress_field']['label'];
940
941
			if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fieldmap['salesforce_field']['name'] ) ) {
942
				$salesforce_field = $fieldmap['salesforce_field']['name'];
943
				// 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.
944
				$salesforce_field_type = $fieldmap['salesforce_field']['type'];
945
			} else {
946
				$salesforce_field = $fieldmap['salesforce_field']['label'];
947
			}
948
949
			// A WordPress event caused this.
950
			if ( in_array( $trigger, array_values( $wordpress_haystack ), true ) ) {
951
952
				// Is the field in WordPress an array, if we unserialize it? Salesforce wants it to be an imploded string.
953
				if ( is_array( maybe_unserialize( $object[ $wordpress_field ] ) ) ) {
954
					// 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.
955
					if ( 'wp_capabilities' === $wordpress_field ) {
956
						$object[ $wordpress_field ] = implode( $this->array_delimiter, array_keys( $object[ $wordpress_field ] ) );
957
					} else {
958
						$object[ $wordpress_field ] = implode( $this->array_delimiter, $object[ $wordpress_field ] );
959
					}
960
				}
961
962
				if ( isset( $salesforce_field_type ) ) {
963
					// Is the Salesforce field a date, and is the WordPress value a valid date?
964
					// According to https://salesforce.stackexchange.com/questions/57032/date-format-with-salesforce-rest-api.
965
					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

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

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