Passed
Push — 319-publish-post-status ( 8a001d...42ed5a )
by Jonathan
09:01 queued 05:28
created

Object_Sync_Sf_Mapping::delete_fieldmap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * Class file for the Object_Sync_Sf_Mapping class.
4
 *
5
 * @file
6
 */
7
8
if ( ! class_exists( 'Object_Sync_Salesforce' ) ) {
9
	die();
10
}
11
12
/**
13
 * Map objects and records between WordPress and Salesforce
14
 */
15
class Object_Sync_Sf_Mapping {
16
17
	protected $wpdb;
18
	protected $version;
19
	protected $slug;
20
	protected $logging;
21
	protected $option_prefix;
22
23
	protected $fieldmap_table;
24
	protected $object_map_table;
25
26
	public $sync_off;
27
	public $sync_wordpress_create;
28
	public $sync_wordpress_update;
29
	public $sync_wordpress_delete;
30
	public $sync_sf_create;
31
	public $sync_sf_update;
32
	public $sync_sf_delete;
33
	public $wordpress_events;
34
	public $salesforce_events;
35
36
	public $direction_wordpress_sf;
37
	public $direction_sf_wordpress;
38
	public $direction_sync;
39
40
	public $direction_wordpress;
41
	public $direction_salesforce;
42
43
	public $salesforce_default_record_type;
44
45
	public $array_delimiter;
46
	public $array_types_from_salesforce;
47
	public $date_types_from_salesforce;
48
	public $int_types_from_salesforce;
49
50
	public $name_length;
51
52
	public $status_success;
53
	public $status_error;
54
55
	public $debug;
56
57
	/**
58
	 * Constructor which sets up links between the systems
59
	 *
60
	 * @param object $wpdb A WPDB object.
61
	 * @param string $version The plugin version.
62
	 * @param string $slug The plugin slug.
63
	 * @param object $logging Object_Sync_Sf_Logging.
64
	 * @param string $option_prefix The plugin option prefix
65
	 * @throws \Exception
66
	 */
67
	public function __construct( $wpdb, $version, $slug, $logging, $option_prefix = '' ) {
68
		$this->wpdb          = $wpdb;
69
		$this->version       = $version;
70
		$this->slug          = $slug;
71
		$this->option_prefix = isset( $option_prefix ) ? $option_prefix : 'object_sync_for_salesforce_';
72
		$this->logging       = $logging;
73
74
		$this->fieldmap_table   = $this->wpdb->prefix . 'object_sync_sf_field_map';
75
		$this->object_map_table = $this->wpdb->prefix . 'object_sync_sf_object_map';
76
77
		/*
78
		 * These parameters are how we define when syncing should occur on each field map.
79
		 * They get used in the admin settings, as well as the push/pull methods to see if something should happen.
80
		 * It is unclear why the Drupal module used bit flags, but it seems reasonable to keep the convention.
81
		*/
82
		$this->sync_off              = 0x0000;
83
		$this->sync_wordpress_create = 0x0001;
84
		$this->sync_wordpress_update = 0x0002;
85
		$this->sync_wordpress_delete = 0x0004;
86
		$this->sync_sf_create        = 0x0008;
87
		$this->sync_sf_update        = 0x0010;
88
		$this->sync_sf_delete        = 0x0020;
89
90
		// Define which events are initialized by which system.
91
		$this->wordpress_events  = array( $this->sync_wordpress_create, $this->sync_wordpress_update, $this->sync_wordpress_delete );
92
		$this->salesforce_events = array( $this->sync_sf_create, $this->sync_sf_update, $this->sync_sf_delete );
93
94
		// Constants for the directions to map things.
95
		$this->direction_wordpress_sf = 'wp_sf';
96
		$this->direction_sf_wordpress = 'sf_wp';
97
		$this->direction_sync         = 'sync';
98
99
		$this->direction_wordpress  = array( $this->direction_wordpress_sf, $this->direction_sync );
100
		$this->direction_salesforce = array( $this->direction_sf_wordpress, $this->direction_sync );
101
102
		// This is used when we map a record with default or Master.
103
		$this->salesforce_default_record_type = 'default';
104
105
		// Salesforce has multipicklists and they have a delimiter.
106
		$this->array_delimiter = ';';
107
		// What data types in Salesforce should be an array?
108
		$this->array_types_from_salesforce = array( 'multipicklist' );
109
		// What data types in Salesforce should be a date field?
110
		$this->date_types_from_salesforce = array( 'date', 'datetime' );
111
		// What data types in Salesforce should be an integer?
112
		$this->int_types_from_salesforce = array( 'integer', 'boolean' );
113
114
		// Max length for a mapping field.
115
		$this->name_length = 128;
116
117
		// Statuses for object sync.
118
		$this->status_success = 1;
119
		$this->status_error   = 0;
120
121
		$this->debug = get_option( $this->option_prefix . 'debug_mode', false );
122
123
	}
124
125
	/**
126
	 * Create a fieldmap row between a WordPress and Salesforce object
127
	 *
128
	 * @param array $posted The results of $_POST.
129
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
130
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
131
	 * @throws \Exception
132
	 */
133
	public function create_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
134
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
135
		if ( version_compare( $this->version, '1.2.5', '>=' ) ) {
136
			$data['version'] = $this->version;
137
		}
138
		$insert = $this->wpdb->insert( $this->fieldmap_table, $data );
139
		if ( 1 === $insert ) {
140
			return $this->wpdb->insert_id;
141
		} else {
142
			return false;
143
		}
144
	}
145
146
	/**
147
	 * Get one or more fieldmap rows between a WordPress and Salesforce object
148
	 *
149
	 * @param int   $id The ID of a desired mapping.
150
	 * @param array $conditions Array of key=>value to match the mapping by.
151
	 * @param bool  $reset Unused parameter.
152
	 * @return array $map a single mapping or $mappings, an array of mappings.
153
	 * @throws \Exception
154
	 */
155
	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

155
	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...
156
		$table = $this->fieldmap_table;
157
		if ( null !== $id ) { // get one fieldmap.
158
			$map                                    = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = ' . $id, ARRAY_A );
159
			$map['salesforce_record_types_allowed'] = maybe_unserialize( $map['salesforce_record_types_allowed'] );
160
161
			$map['fields']        = maybe_unserialize( $map['fields'] );
162
			$map['sync_triggers'] = maybe_unserialize( $map['sync_triggers'] );
163
			return $map;
164
		} elseif ( ! empty( $conditions ) ) { // get multiple but with a limitation.
165
			$mappings    = array();
166
			$record_type = '';
167
			// Assemble the SQL.
168
			if ( ! empty( $conditions ) ) {
169
				$where = ' WHERE ';
170
				$i     = 0;
171
				foreach ( $conditions as $key => $value ) {
172
					if ( 'salesforce_record_type' === $key ) {
173
						$record_type = sanitize_text_field( $value );
174
					} else {
175
						$i++;
176
						if ( $i > 1 ) {
177
							$where .= ' AND ';
178
						}
179
						$where .= '`' . $key . '` = "' . $value . '"';
180
					}
181
				}
182
			} else {
183
				$where = '';
184
			}
185
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . ' ORDER BY `weight`', ARRAY_A );
186
			if ( ! empty( $mappings ) ) {
187
				$mappings = $this->prepare_fieldmap_data( $mappings, $record_type );
188
			}
189
			return $mappings;
190
		} else {
191
			// get all of the mappings. ALL THE MAPPINGS.
192
			if ( version_compare( $this->version, '1.9.0', '>=' ) ) {
193
				// if the version is greater than or equal to 1.9.0, the fieldmap table has a wordpress_object_default_status column
194
				$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `wordpress_object_default_status`, `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 ); // WPCS: unprepared SQL OK.
195
			} elseif ( version_compare( $this->version, '1.5.0', '>=' ) ) {
196
				// if the version is greater than or equal to 1.5.0, the fieldmap table has a pull_to_drafts column
197
				$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 ); // WPCS: unprepared SQL OK.
198
			} elseif ( version_compare( $this->version, '1.2.5', '>=' ) ) {
199
				// if the version is greater than or equal to 1.2.5, the fieldmap table has a version column
200
				$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 ); // WPCS: unprepared SQL OK.
201
			} else {
202
				$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 ); // WPCS: unprepared SQL OK.
203
			}
204
			if ( ! empty( $mappings ) ) {
205
				$mappings = $this->prepare_fieldmap_data( $mappings );
206
			}
207
			return $mappings;
208
		} // End if().
209
	}
210
211
	/**
212
	 * For a mapping, get the fieldmaps associated with it.
213
	 *
214
	 * @param Array $mapping The mapping for which we are getting the fieldmaps.
215
	 * @param Array $directions The direction of the mapping: from WP to SF or vice-versa.
216
	 * @see Object_Sync_Sf_Salesforce_Pull::get_pull_query()
217
	 *
218
	 * @return Array of mapped fields
219
	 */
220
	public function get_mapped_fields( $mapping, $directions = array() ) {
221
		$mapped_fields = array();
222
		foreach ( $mapping['fields'] as $fields ) {
223
			if ( empty( $directions ) || in_array( $fields['direction'], $directions, true ) ) {
224
225
				// in version 1.2.0, we provided an option for API name vs label for Salesforce fields
226
				if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fields['salesforce_field']['name'] ) ) {
227
					$array_key = 'name';
228
				} else {
229
					$array_key = 'label';
230
				}
231
232
				// Some field map types (Relation) store a collection of SF objects.
233
				if ( is_array( $fields['salesforce_field'] ) && ! isset( $fields['salesforce_field'][ $array_key ] ) ) {
234
					foreach ( $fields['salesforce_field'] as $sf_field ) {
235
						$mapped_fields[ $sf_field[ $array_key ] ] = $sf_field[ $array_key ];
236
					}
237
				} else { // The rest are just a name/value pair.
238
					$mapped_fields[ $fields['salesforce_field'][ $array_key ] ] = $fields['salesforce_field'][ $array_key ];
239
				}
240
			}
241
		}
242
243
		if ( ! empty( $this->get_mapped_record_types ) ) {
244
			$mapped_fields['RecordTypeId'] = 'RecordTypeId';
245
		}
246
247
		return $mapped_fields;
248
	}
249
250
	/**
251
	 * Get the mapped record types for a given mapping.
252
	 *
253
	 * @param Array $mapping A mapping from which we wish to estract the record type.
254
	 * @return Array of mappings. Empty if the mapping's record type is default, else full of the record types.
255
	 */
256
	public function get_mapped_record_types( $mapping ) {
257
		return $mapping['salesforce_record_type_default'] === $this->salesforce_default_record_type ? array() : array_filter( maybe_unserialize( $mapping['salesforce_record_types_allowed'] ) );
258
	}
259
260
	/**
261
	 * Update a fieldmap row between a WordPress and Salesforce object
262
	 *
263
	 * @param array $posted It's $_POST.
264
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
265
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
266
	 * @param int   $id The ID of the mapping.
267
	 * @return boolean
268
	 * @throws \Exception
269
	 */
270
	public function update_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array(), $id = '' ) {
271
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
272
		if ( version_compare( $this->version, '1.2.5', '>=' ) && ! isset( $data['updated'] ) ) {
273
			$data['version'] = $this->version;
274
		}
275
		$update = $this->wpdb->update(
276
			$this->fieldmap_table,
277
			$data,
278
			array(
279
				'id' => $id,
280
			)
281
		);
282
		if ( false === $update ) {
283
			return false;
284
		} else {
285
			return true;
286
		}
287
	}
288
289
	/**
290
	 * Setup fieldmap data
291
	 * Sets up the database entry for mapping the object types between Salesforce and WordPress
292
	 *
293
	 * @param array $posted It's $_POST.
294
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
295
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
296
	 * @return array $data the fieldmap's data for the database
297
	 */
298
	private function setup_fieldmap_data( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
299
		$data = array(
300
			'label'             => $posted['label'],
301
			'name'              => sanitize_title( $posted['label'] ),
302
			'salesforce_object' => $posted['salesforce_object'],
303
			'wordpress_object'  => $posted['wordpress_object'],
304
		);
305
		if ( isset( $posted['wordpress_object_default_status'] ) ) {
306
			// added in version 1.9.0.
307
			$data['wordpress_object_default_status'] = sanitize_text_field( $posted['wordpress_object_default_status'] );
308
		}
309
		if ( isset( $posted['wordpress_field'] ) && is_array( $posted['wordpress_field'] ) && isset( $posted['salesforce_field'] ) && is_array( $posted['salesforce_field'] ) ) {
310
			$setup['fields'] = array();
311
			foreach ( $posted['wordpress_field'] as $key => $value ) {
312
				$method_key = array_search( $value, array_column( $wordpress_fields, 'key' ), true );
313
				if ( ! isset( $posted['direction'][ $key ] ) ) {
314
					$posted['direction'][ $key ] = 'sync';
315
				}
316
				if ( ! isset( $posted['is_prematch'][ $key ] ) ) {
317
					$posted['is_prematch'][ $key ] = false;
318
				}
319
				if ( ! isset( $posted['is_key'][ $key ] ) ) {
320
					$posted['is_key'][ $key ] = false;
321
				}
322
				if ( ! isset( $posted['is_delete'][ $key ] ) ) {
323
					$posted['is_delete'][ $key ] = false;
324
				}
325
				if ( false === $posted['is_delete'][ $key ] ) {
326
					// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
327
					$updateable_key = array_search( $posted['salesforce_field'][ $key ], array_column( $salesforce_fields, 'name' ), true );
328
329
					$salesforce_field_attributes = array();
330
					foreach ( $salesforce_fields[ $updateable_key ] as $sf_key => $sf_value ) {
331
						if ( isset( $sf_value ) && ! is_array( $sf_value ) ) {
332
							$salesforce_field_attributes[ $sf_key ] = esc_attr( $sf_value );
333
						} elseif ( ! empty( $sf_value ) && is_array( $sf_value ) ) {
334
							$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 $original 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

334
							$salesforce_field_attributes[ $sf_key ] = maybe_unserialize( /** @scrutinizer ignore-type */ $sf_value );
Loading history...
335
						} else {
336
							$salesforce_field_attributes[ $sf_key ] = '';
337
						}
338
					}
339
340
					$setup['fields'][ $key ] = array(
341
						'wordpress_field'  => array(
342
							'label'   => sanitize_text_field( $posted['wordpress_field'][ $key ] ),
343
							'methods' => maybe_unserialize( $wordpress_fields[ $method_key ]['methods'] ),
344
							'type'    => isset( $wordpress_fields[ $method_key ]['type'] ) ? sanitize_text_field( $wordpress_fields[ $method_key ]['type'] ) : 'text',
345
						),
346
						'salesforce_field' => $salesforce_field_attributes,
347
						'is_prematch'      => sanitize_text_field( $posted['is_prematch'][ $key ] ),
348
						'is_key'           => sanitize_text_field( $posted['is_key'][ $key ] ),
349
						'direction'        => sanitize_text_field( $posted['direction'][ $key ] ),
350
						'is_delete'        => sanitize_text_field( $posted['is_delete'][ $key ] ),
351
					);
352
353
					// If the WordPress key or the Salesforce key are blank, remove this incomplete mapping.
354
					// This prevents https://github.com/MinnPost/object-sync-for-salesforce/issues/82 .
355
					if (
356
						empty( $setup['fields'][ $key ]['wordpress_field']['label'] )
357
						||
358
						empty( $setup['fields'][ $key ]['salesforce_field']['name'] )
359
					) {
360
						unset( $setup['fields'][ $key ] );
361
					}
362
				}
363
			} // End foreach() on WordPress fields.
364
			$data['fields'] = maybe_serialize( $setup['fields'] );
365
		} elseif ( isset( $posted['fields'] ) && is_array( $posted['fields'] ) ) {
366
			// if $posted['fields'] is already set, use that
367
			$data['fields'] = maybe_serialize( $posted['fields'] );
368
		} // End if() WordPress fields are present.
369
370
		if ( isset( $posted['salesforce_record_types_allowed'] ) ) {
371
			$data['salesforce_record_types_allowed'] = maybe_serialize( $posted['salesforce_record_types_allowed'] );
372
		} else {
373
			$data['salesforce_record_types_allowed'] = maybe_serialize(
374
				array(
375
					$this->salesforce_default_record_type => $this->salesforce_default_record_type,
376
				)
377
			);
378
		}
379
		if ( isset( $posted['salesforce_record_type_default'] ) ) {
380
			$data['salesforce_record_type_default'] = $posted['salesforce_record_type_default'];
381
		} else {
382
			$data['salesforce_record_type_default'] = maybe_serialize( $this->salesforce_default_record_type );
383
		}
384
		if ( isset( $posted['pull_trigger_field'] ) ) {
385
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
386
		}
387
		if ( isset( $posted['sync_triggers'] ) && is_array( $posted['sync_triggers'] ) ) {
388
			$setup['sync_triggers'] = array();
389
			foreach ( $posted['sync_triggers'] as $key => $value ) {
390
				$setup['sync_triggers'][ $key ] = esc_html( $posted['sync_triggers'][ $key ] );
391
			}
392
		} else {
393
			$setup['sync_triggers'] = array();
394
		}
395
		$data['sync_triggers'] = maybe_serialize( $setup['sync_triggers'] );
396
		if ( isset( $posted['pull_trigger_field'] ) ) {
397
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
398
		}
399
		$data['push_async']     = isset( $posted['push_async'] ) ? $posted['push_async'] : '';
400
		$data['push_drafts']    = isset( $posted['push_drafts'] ) ? $posted['push_drafts'] : '';
401
		$data['pull_to_drafts'] = isset( $posted['pull_to_drafts'] ) ? $posted['pull_to_drafts'] : '';
402
		$data['weight']         = isset( $posted['weight'] ) ? $posted['weight'] : '';
403
		return $data;
404
	}
405
406
	/**
407
	 * Delete a fieldmap row between a WordPress and Salesforce object
408
	 *
409
	 * @param int $id The ID of a field mapping.
410
	 * @return Boolean
411
	 * @throws \Exception
412
	 */
413
	public function delete_fieldmap( $id = '' ) {
414
		$data   = array(
415
			'id' => $id,
416
		);
417
		$delete = $this->wpdb->delete( $this->fieldmap_table, $data );
418
		if ( 1 === $delete ) {
419
			return true;
420
		} else {
421
			return false;
422
		}
423
	}
424
425
	/**
426
	 * Create an object map row between a WordPress and Salesforce object
427
	 *
428
	 * @param array $posted It's $_POST.
429
	 * @return false|Int of field mapping between WordPress and Salesforce objects
430
	 * @throws \Exception
431
	 */
432
	public function create_object_map( $posted = array() ) {
433
		$data            = $this->setup_object_map_data( $posted );
434
		$data['created'] = current_time( 'mysql' );
435
		// Check to see if we don't know the salesforce id and it is not a temporary id, or if this is pending.
436
		// 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.
437
		if ( substr( $data['salesforce_id'], 0, 7 ) !== 'tmp_sf_' || ( isset( $data['action'] ) && 'pending' === $data['action'] ) ) {
438
			unset( $data['action'] );
439
			$insert = $this->wpdb->insert( $this->object_map_table, $data );
440
		} else {
441
			$status = 'error';
442
			if ( isset( $this->logging ) ) {
443
				$logging = $this->logging;
444
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
445
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
446
			}
447
			$logging->setup(
448
				sprintf(
449
					// translators: %1$s is the log status, %2$s is the name of a WordPress object. %3$s is the id of that object.
450
					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' ),
451
					ucfirst( esc_attr( $status ) ),
452
					esc_attr( $data['wordpress_object'] ),
453
					absint( $data['wordpress_id'] )
454
				),
455
				'',
456
				0,
457
				0,
458
				$status
459
			);
460
			return false;
461
		}
462
		if ( 1 === $insert ) {
463
			return $this->wpdb->insert_id;
464
		} elseif ( false !== strpos( $this->wpdb->last_error, 'Duplicate entry' ) ) {
465
			// this error should never happen now, I think. But let's watch and see.
466
			$mapping = $this->load_all_by_salesforce( $data['salesforce_id'] )[0];
467
			$id      = $mapping['id'];
468
			$status  = 'error';
469
			if ( isset( $this->logging ) ) {
470
				$logging = $this->logging;
471
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
472
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
473
			}
474
			$logging->setup(
475
				sprintf(
476
					// 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.
477
					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' ),
478
					ucfirst( esc_attr( $status ) ),
479
					esc_attr( $data['salesforce_id'] ),
480
					absint( $id )
481
				),
482
				print_r( $mapping, true ), // log whatever we have for the mapping object, so print the array
483
				0,
484
				0,
485
				$status
486
			);
487
			return $id;
488
		} else {
489
			return false;
490
		}
491
	}
492
493
	/**
494
	 * Get all object map rows between WordPress and Salesforce objects.
495
	 *
496
	 * This replaces previous functionality that would return a single object map if there was only one, rather than a multi-dimensional array.
497
	 *
498
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
499
	 * @param bool $reset Unused parameter.
500
	 * @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...
501
	 */
502
	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

502
	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...
503
		$table = $this->object_map_table;
504
		$order = ' ORDER BY object_updated, created';
505
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
506
			$mappings = array();
507
508
			if ( ! empty( $conditions ) ) {
509
				$where = ' WHERE ';
510
				$i     = 0;
511
				foreach ( $conditions as $key => $value ) {
512
					$i++;
513
					if ( $i > 1 ) {
514
						$where .= ' AND ';
515
					}
516
					$where .= '`' . $key . '` = "' . $value . '"';
517
				}
518
			} else {
519
				$where = '';
520
			}
521
522
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
523
		} else { // get all of the mappings. ALL THE MAPPINGS.
524
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
525
		}
526
527
		return $mappings;
528
529
	}
530
531
	/**
532
	 * Get one or more object map rows between WordPress and Salesforce objects
533
	 *
534
	 * @deprecated since 1.8.0
535
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
536
	 * @param bool  $reset Unused parameter.
537
	 * @return array $map or $mappings
538
	 * @throws \Exception
539
	 */
540
	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

540
	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...
541
		$table = $this->object_map_table;
542
		$order = ' ORDER BY object_updated, created';
543
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
544
			$mappings = array();
545
546
			if ( ! empty( $conditions ) ) {
547
				$where = ' WHERE ';
548
				$i     = 0;
549
				foreach ( $conditions as $key => $value ) {
550
					$i++;
551
					if ( $i > 1 ) {
552
						$where .= ' AND ';
553
					}
554
					$where .= '`' . $key . '` = "' . $value . '"';
555
				}
556
			} else {
557
				$where = '';
558
			}
559
560
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
561
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
562
				$mappings = $mappings[0];
563
			}
564
		} else { // get all of the mappings. ALL THE MAPPINGS.
565
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
566
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
567
				$mappings = $mappings[0];
568
			}
569
		}
570
571
		return $mappings;
572
573
	}
574
575
	/**
576
	 * Update an object map row between a WordPress and Salesforce object
577
	 *
578
	 * @param array $posted It's $_POST.
579
	 * @param array $id The ID of the object map row.
580
	 * @return boolean
581
	 * @throws \Exception
582
	 */
583
	public function update_object_map( $posted = array(), $id = '' ) {
584
		$data = $this->setup_object_map_data( $posted );
585
		if ( ! isset( $data['object_updated'] ) ) {
586
			$data['object_updated'] = current_time( 'mysql' );
587
		}
588
		$update = $this->wpdb->update(
589
			$this->object_map_table,
590
			$data,
591
			array(
592
				'id' => $id,
593
			)
594
		);
595
		if ( false === $update ) {
596
			return false;
597
		} else {
598
			return true;
599
		}
600
	}
601
602
	/**
603
	 * Setup the data for the object map
604
	 *
605
	 * @param array $posted It's $_POST.
606
	 * @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.
607
	 */
608
	private function setup_object_map_data( $posted = array() ) {
609
		$allowed_fields   = $this->wpdb->get_col( "DESC {$this->object_map_table}", 0 );
610
		$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
611
612
		$data = array_intersect_key( $posted, array_flip( $allowed_fields ) );
613
		return $data;
614
	}
615
616
	/**
617
	 * Delete an object map row between a WordPress and Salesforce object
618
	 *
619
	 * @param int|array $id The ID or IDs of the object map row(s).
620
	 * @return boolean
621
	 * @throws \Exception
622
	 */
623
	public function delete_object_map( $id = '' ) {
624
		if ( is_string( $id ) || is_int( $id ) ) {
625
			$data   = array(
626
				'id' => $id,
627
			);
628
			$delete = $this->wpdb->delete( $this->object_map_table, $data );
629
			if ( 1 === $delete ) {
630
				return true;
631
			} else {
632
				return false;
633
			}
634
		} elseif ( is_array( $id ) ) {
0 ignored issues
show
introduced by
The condition is_array($id) is always true.
Loading history...
635
			$ids    = implode( ',', array_map( 'absint', $id ) );
636
			$delete = $this->wpdb->query( "DELETE FROM $this->object_map_table WHERE ID IN ($ids)" );
637
			if ( false !== $delete ) {
638
				return true;
639
			} else {
640
				return false;
641
			}
642
		}
643
	}
644
645
	/**
646
	 * Generate a temporary ID to store while waiting for a push or pull to complete, before the record has been assigned a new ID
647
	 *
648
	 * @param string $direction Whether this is part of a push or pull action
649
	 * @return string $id is a temporary string that will be replaced if the modification is successful
650
	 */
651
	public function generate_temporary_id( $direction ) {
652
		if ( 'push' === $direction ) {
653
			$prefix = 'tmp_sf_';
654
		} elseif ( 'pull' === $direction ) {
655
			$prefix = 'tmp_wp_';
656
		}
657
		$id = uniqid( $prefix, true );
658
		return $id;
659
	}
660
661
	/**
662
	 * Returns Salesforce object mappings for a given WordPress object.
663
	 *
664
	 * @param string $object_type Type of object to load.
665
	 * @param int    $object_id Unique identifier of the target object to load.
666
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
667
	 *
668
	 * @return SalesforceMappingObject
0 ignored issues
show
Bug introduced by
The type SalesforceMappingObject was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
669
	 *   The requested SalesforceMappingObject or FALSE if none was found.
670
	 */
671
	public function load_all_by_wordpress( $object_type, $object_id, $reset = false ) {
672
		$conditions = array(
673
			'wordpress_id'     => $object_id,
674
			'wordpress_object' => $object_type,
675
		);
676
		return $this->get_all_object_maps( $conditions, $reset );
677
	}
678
679
	/**
680
	 * Returns one or more Salesforce object mappings for a given WordPress object.
681
	 *
682
	 * @deprecated since 1.8.0
683
	 * @param string $object_type Type of object to load.
684
	 * @param int    $object_id Unique identifier of the target object to load.
685
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
686
	 *
687
	 * @return SalesforceMappingObject
688
	 *   The requested SalesforceMappingObject or FALSE if none was found.
689
	 */
690
	public function load_by_wordpress( $object_type, $object_id, $reset = false ) {
691
		$conditions = array(
692
			'wordpress_id'     => $object_id,
693
			'wordpress_object' => $object_type,
694
		);
695
		return $this->get_object_maps( $conditions, $reset );
0 ignored issues
show
Deprecated Code introduced by
The function Object_Sync_Sf_Mapping::get_object_maps() has been deprecated: since 1.8.0 ( Ignorable by Annotation )

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

695
		return /** @scrutinizer ignore-deprecated */ $this->get_object_maps( $conditions, $reset );

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

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

Loading history...
696
	}
697
698
	/**
699
	 * Returns Salesforce object mappings for a given Salesforce object.
700
	 *
701
	 * @param string $salesforce_id Type of object to load.
702
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
703
	 *
704
	 * @return array $maps all the object maps that match the Salesforce Id
705
	 */
706
	public function load_all_by_salesforce( $salesforce_id, $reset = false ) {
707
		$conditions = array(
708
			'salesforce_id' => $salesforce_id,
709
		);
710
711
		$maps = $this->get_all_object_maps( $conditions, $reset );
712
713
		return $maps;
714
	}
715
716
	/**
717
	 * Returns one or more Salesforce object mappings for a given Salesforce object.
718
	 *
719
	 * @deprecated since 1.8.0
720
	 * @param string $salesforce_id Type of object to load.
721
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
722
	 *
723
	 * @return array $map
724
	 *   The most recent fieldmap
725
	 */
726
	public function load_by_salesforce( $salesforce_id, $reset = false ) {
727
		$conditions = array(
728
			'salesforce_id' => $salesforce_id,
729
		);
730
731
		$map = $this->get_object_maps( $conditions, $reset );
0 ignored issues
show
Deprecated Code introduced by
The function Object_Sync_Sf_Mapping::get_object_maps() has been deprecated: since 1.8.0 ( Ignorable by Annotation )

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

731
		$map = /** @scrutinizer ignore-deprecated */ $this->get_object_maps( $conditions, $reset );

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

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

Loading history...
732
733
		if ( isset( $map[0] ) && is_array( $map[0] ) && count( $map ) > 1 ) {
734
			$status = 'notice';
735
			$log    = '';
736
			$log   .= 'Mapping: there is more than one mapped WordPress object for the Salesforce object ' . $salesforce_id . '. These WordPress IDs are: ';
737
			$i      = 0;
738
			foreach ( $map as $mapping ) {
739
				$i++;
740
				if ( isset( $mapping['wordpress_id'] ) ) {
741
					$log .= 'object type: ' . $mapping['wordpress_object'] . ', id: ' . $mapping['wordpress_id'];
742
				}
743
				if ( count( $map ) !== $i ) {
744
					$log .= '; ';
745
				} else {
746
					$log .= '.';
747
				}
748
			}
749
			$map = $map[0];
750
			// Create log entry for multiple maps.
751
			if ( isset( $this->logging ) ) {
752
				$logging = $this->logging;
753
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
754
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
755
			}
756
			$logging->setup(
757
				sprintf(
758
					// translators: %1$s is the Id of a Salesforce object.
759
					esc_html__( 'Notice: Mapping: there is more than one mapped WordPress object for the Salesforce object %2$s', 'object-sync-for-salesforce' ),
760
					esc_attr( $salesforce_id )
761
				),
762
				$log,
763
				0,
764
				0,
765
				$status
766
			);
767
		} // End if().
768
769
		return $map;
770
	}
771
772
	/**
773
	 * Map values between WordPress and Salesforce objects.
774
	 *
775
	 * @param array  $mapping Mapping object.
776
	 * @param array  $object WordPress or Salesforce object data.
777
	 * @param array  $trigger The thing that triggered this mapping.
778
	 * @param bool   $use_soap Flag to enforce use of the SOAP API.
779
	 * @param bool   $is_new Indicates whether a mapping object for this entity already exists.
780
	 * @param string $object_id_field optionally pass the object id field name
781
	 *
782
	 * @return array Associative array of key value pairs.
783
	 */
784
	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

784
	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...
785
786
		$params = array();
787
788
		$has_missing_required_salesforce_field = false;
789
		foreach ( $mapping['fields'] as $fieldmap ) {
790
791
			$wordpress_haystack  = array_values( $this->wordpress_events );
792
			$salesforce_haystack = array_values( $this->salesforce_events );
793
794
			$fieldmap['wordpress_field']['methods'] = maybe_unserialize( $fieldmap['wordpress_field']['methods'] );
795
796
			$wordpress_field = $fieldmap['wordpress_field']['label'];
797
798
			if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fieldmap['salesforce_field']['name'] ) ) {
799
				$salesforce_field = $fieldmap['salesforce_field']['name'];
800
				// 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.
801
				$salesforce_field_type = $fieldmap['salesforce_field']['type'];
802
			} else {
803
				$salesforce_field = $fieldmap['salesforce_field']['label'];
804
			}
805
806
			// A WordPress event caused this.
807
			if ( in_array( $trigger, array_values( $wordpress_haystack ), true ) ) {
808
809
				// Is the field in WordPress an array, if we unserialize it? Salesforce wants it to be an imploded string.
810
				if ( is_array( maybe_unserialize( $object[ $wordpress_field ] ) ) ) {
811
					$object[ $wordpress_field ] = implode( $this->array_delimiter, $object[ $wordpress_field ] );
812
				}
813
814
				if ( isset( $salesforce_field_type ) ) {
815
					// Is the Salesforce field a date, and is the WordPress value a valid date?
816
					// According to https://salesforce.stackexchange.com/questions/57032/date-format-with-salesforce-rest-api
817
					if ( in_array( $salesforce_field_type, $this->date_types_from_salesforce ) ) {
818
						if ( '' === $object[ $wordpress_field ] ) {
819
							$object[ $wordpress_field ] = null;
820
						} else {
821
							if ( false !== strtotime( $object[ $wordpress_field ] ) ) {
822
								$timestamp = strtotime( $object[ $wordpress_field ] );
823
							} else {
824
								$timestamp = $object[ $wordpress_field ];
825
							}
826
							if ( 'datetime' === $salesforce_field_type ) {
827
								$object[ $wordpress_field ] = date_i18n( 'c', $timestamp );
828
							} else {
829
								$object[ $wordpress_field ] = date_i18n( 'Y-m-d', $timestamp );
830
							}
831
						}
832
					}
833
834
					// Boolean SF fields only want real boolean values. NULL is also not allowed.
835
					if ( 'boolean' === $salesforce_field_type ) {
836
						$object[ $wordpress_field ] = (bool) $object[ $wordpress_field ];
837
					}
838
				}
839
840
				$params[ $salesforce_field ] = $object[ $wordpress_field ];
841
842
				// If the field is a key in Salesforce, remove it from $params to avoid upsert errors from Salesforce,
843
				// but still put its name in the params array so we can check for it later.
844
				if ( '1' === $fieldmap['is_key'] ) {
845
					if ( ! $use_soap ) {
846
						unset( $params[ $salesforce_field ] );
847
					}
848
					$params['key'] = array(
849
						'salesforce_field' => $salesforce_field,
850
						'wordpress_field'  => $wordpress_field,
851
						'value'            => $object[ $wordpress_field ],
852
					);
853
				}
854
855
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
856
				if ( '1' === $fieldmap['is_prematch'] ) {
857
					$params['prematch'] = array(
858
						'salesforce_field' => $salesforce_field,
859
						'wordpress_field'  => $wordpress_field,
860
						'value'            => $object[ $wordpress_field ],
861
					);
862
				}
863
864
				// Skip fields that aren't being pushed to Salesforce.
865
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_wordpress ), true ) ) {
866
					// The trigger is a WordPress trigger, but the fieldmap direction is not a WordPress direction.
867
					unset( $params[ $salesforce_field ] );
868
				}
869
870
				// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
871
				// Skip fields that aren't updateable when mapping params because Salesforce will error otherwise.
872
				// 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.
873
				if ( 1 !== (int) $fieldmap['salesforce_field']['updateable'] ) {
874
					unset( $params[ $salesforce_field ] );
875
				}
876
877
				// This case means the following:
878
				//    this field is expected by the fieldmap
879
				//    Salesforce's api reports that this field is required
880
				//    we do not have a WordPress value for this field, or it's empty
881
				//    it also means the field has not been unset by prematch, updateable, key, or directional flags prior to this check.
882
				// When this happens, we should flag that we're missing a required Salesforce field
883
				if ( in_array( $salesforce_field, $params ) && false === filter_var( $fieldmap['salesforce_field']['nillable'], FILTER_VALIDATE_BOOLEAN ) && ( ! isset( $object[ $wordpress_field ] ) || '' === $object[ $wordpress_field ] ) ) {
884
					$has_missing_required_salesforce_field = true;
885
				}
886
887
				// we don't need a continue with the unset methods because there's no array being created down here
888
			} elseif ( in_array( $trigger, $salesforce_haystack, true ) ) {
889
890
				// A Salesforce event caused this.
891
892
				if ( isset( $salesforce_field_type ) && isset( $object[ $salesforce_field ] ) && ! is_null( $object[ $salesforce_field ] ) ) {
893
					// Salesforce provides multipicklist values as a delimited string. If the
894
					// destination field in WordPress accepts multiple values, explode the string into an array and then serialize it.
895
					if ( in_array( $salesforce_field_type, $this->array_types_from_salesforce ) ) {
896
						$object[ $salesforce_field ] = explode( $this->array_delimiter, $object[ $salesforce_field ] );
897
					}
898
899
					// Handle specific data types from Salesforce.
900
					switch ( $salesforce_field_type ) {
901
						case ( in_array( $salesforce_field_type, $this->date_types_from_salesforce ) ):
902
							$format = get_option( 'date_format', 'U' );
903
							if ( isset( $fieldmap['wordpress_field']['type'] ) && 'datetime' === $fieldmap['wordpress_field']['type'] ) {
904
								$format = 'Y-m-d H:i:s';
905
							}
906
							if ( 'tribe_events' === $mapping['wordpress_object'] && class_exists( 'Tribe__Events__Main' ) ) {
907
								$format = 'Y-m-d H:i:s';
908
							}
909
							if ( 'datetime' === $salesforce_field_type ) {
910
								// 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.
911
								// 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.
912
								$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.
913
							}
914
							$object[ $salesforce_field ] = date_i18n( $format, strtotime( $object[ $salesforce_field ] ) );
915
							break;
916
						case ( in_array( $salesforce_field_type, $this->int_types_from_salesforce ) ):
917
							$object[ $salesforce_field ] = isset( $object[ $salesforce_field ] ) ? (int) $object[ $salesforce_field ] : 0;
918
							break;
919
						case 'text':
920
							$object[ $salesforce_field ] = (string) $object[ $salesforce_field ];
921
							break;
922
						case 'url':
923
							$object[ $salesforce_field ] = esc_url_raw( $object[ $salesforce_field ] );
924
							break;
925
					}
926
				}
927
928
				// Make an array because we need to store the methods for each field as well.
929
				if ( isset( $object[ $salesforce_field ] ) && '' !== $object[ $salesforce_field ] ) {
930
					$params[ $wordpress_field ]          = array();
931
					$params[ $wordpress_field ]['value'] = $object[ $salesforce_field ];
932
				} else {
933
					// If we try to save certain fields with empty values, WordPress will silently start skipping stuff. This keeps that from happening.
934
					continue;
935
				}
936
937
				// 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.
938
939
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
940
				if ( '1' === $fieldmap['is_prematch'] ) {
941
					$params['prematch'] = array(
942
						'salesforce_field' => $salesforce_field,
943
						'wordpress_field'  => $wordpress_field,
944
						'value'            => $object[ $salesforce_field ],
945
						'method_match'     => isset( $fieldmap['wordpress_field']['methods']['match'] ) ? $fieldmap['wordpress_field']['methods']['match'] : $fieldmap['wordpress_field']['methods']['read'],
946
						'method_read'      => $fieldmap['wordpress_field']['methods']['read'],
947
						'method_create'    => $fieldmap['wordpress_field']['methods']['create'],
948
						'method_update'    => $fieldmap['wordpress_field']['methods']['update'],
949
					);
950
				}
951
952
				// Skip fields that aren't being pulled from Salesforce.
953
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_salesforce ), true ) ) {
954
					// The trigger is a Salesforce trigger, but the fieldmap direction is not a Salesforce direction.
955
					unset( $params[ $wordpress_field ] );
956
					// we also need to continue here, so it doesn't create an empty array below for fields that are WordPress -> Salesforce only
957
					continue;
958
				}
959
960
				switch ( $trigger ) {
961
					case $this->sync_sf_create:
962
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['create'];
963
						break;
964
					case $this->sync_sf_update:
965
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['update'];
966
						break;
967
					case $this->sync_sf_delete:
968
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['delete'];
969
						break;
970
				}
971
972
				$params[ $wordpress_field ]['method_read'] = $fieldmap['wordpress_field']['methods']['read'];
973
974
			} // End if().
975
		} // End foreach().
976
977
		if ( true === $has_missing_required_salesforce_field ) {
978
			update_option( $this->option_prefix . 'missing_required_data_id_' . $object[ $object_id_field ], true, false );
979
			return array();
980
		}
981
982
		return $params;
983
984
	}
985
986
	/**
987
	 * Prepare field map data for use
988
	 *
989
	 * @param array  $mappings Array of fieldmaps.
990
	 * @param string $record_type Optional Salesforce record type to see if it is allowed or not.
991
	 *
992
	 * @return array $mappings Associative array of field maps ready to use
993
	 */
994
	private function prepare_fieldmap_data( $mappings, $record_type = '' ) {
995
996
		foreach ( $mappings as $id => $mapping ) {
997
			$mappings[ $id ]['salesforce_record_types_allowed'] = maybe_unserialize( $mapping['salesforce_record_types_allowed'] );
998
			$mappings[ $id ]['fields']                          = maybe_unserialize( $mapping['fields'] );
999
			$mappings[ $id ]['sync_triggers']                   = maybe_unserialize( $mapping['sync_triggers'] );
1000
			if ( '' !== $record_type && ! in_array( $record_type, $mappings[ $id ]['salesforce_record_types_allowed'], true ) ) {
1001
				unset( $mappings[ $id ] );
1002
			}
1003
		}
1004
1005
		return $mappings;
1006
1007
	}
1008
1009
	/**
1010
	 * Check object map table to see if there have been any failed object map create attempts
1011
	 *
1012
	 * @return array $errors Associative array of rows that failed to finish from either system
1013
	 */
1014
	public function get_failed_object_maps() {
1015
		$table       = $this->object_map_table;
1016
		$errors      = array();
1017
		$push_errors = $this->wpdb->get_results( 'SELECT * FROM ' . $table . ' WHERE salesforce_id LIKE "tmp_sf_%"', ARRAY_A );
1018
		$pull_errors = $this->wpdb->get_results( 'SELECT * FROM ' . $table . ' WHERE wordpress_id LIKE "tmp_wp_%"', ARRAY_A );
1019
		if ( ! empty( $push_errors ) ) {
1020
			$errors['push_errors'] = $push_errors;
1021
		}
1022
		if ( ! empty( $pull_errors ) ) {
1023
			$errors['pull_errors'] = $pull_errors;
1024
		}
1025
		return $errors;
1026
	}
1027
1028
	/**
1029
	 * Check object map table to see if there have been any failed object map create attempts
1030
	 *
1031
	 * @param int   $id The ID of a desired mapping.
1032
	 *
1033
	 * @return array $error Associative array of single row that failed to finish based on id
1034
	 */
1035
	public function get_failed_object_map( $id ) {
1036
		$table     = $this->object_map_table;
1037
		$error     = array();
1038
		$error_row = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = "' . $id . '"', ARRAY_A );
1039
		if ( ! empty( $error_row ) ) {
1040
			$error = $error_row;
1041
		}
1042
		return $error;
1043
	}
1044
1045
}
1046