Issues (3627)

plugins/MauticCrmBundle/Api/SugarcrmApi.php (19 issues)

1
<?php
2
3
namespace MauticPlugin\MauticCrmBundle\Api;
4
5
use Mautic\PluginBundle\Exception\ApiErrorException;
6
7
class SugarcrmApi extends CrmApi
8
{
9
    protected $object = 'Leads';
10
11
    /**
12
     * @param        $sMethod
13
     * @param array  $data
14
     * @param string $method
15
     *
16
     * @return mixed|string
17
     *
18
     * @throws ApiErrorException
19
     */
20
    public function request($sMethod, $data = [], $method = 'GET', $object = null)
21
    {
22
        if (!$object) {
23
            $object = $this->object;
24
        }
25
        $tokenData = $this->integration->getKeys();
26
27
        if ('6' == $tokenData['version']) {
28
            $request_url = sprintf('%s/service/v4_1/rest.php', $tokenData['sugarcrm_url']);
29
30
            $sessionParams = [
31
                'session' => $tokenData['id'],
32
            ];
33
            if (!isset($data['module_names'])) {
34
                $sessionParams['module_name'] = $object;
35
            } //Making sure that module_name is the second value of the array
36
            else {
37
                $sessionParams['module_names'] = $data['module_names'];
38
            }
39
40
            $sessionParams = array_merge($sessionParams, $data);
41
            $parameters    = [
42
                'method'        => $sMethod,
43
                'input_type'    => 'JSON',
44
                'response_type' => 'JSON',
45
                'rest_data'     => json_encode($sessionParams),
46
            ];
47
48
            $response = $this->integration->makeRequest($request_url, $parameters, $method);
49
50
            if (is_array($response) && !empty($response['name']) && !empty($response['number'])) {
51
                throw new ApiErrorException($response['name'].' '.$object.' '.$sMethod.' '.$method);
52
            } else {
53
                return $response;
54
            }
55
        } else {
56
            $request_url = sprintf('%s/rest/v10/%s', $tokenData['sugarcrm_url'], $sMethod);
57
            $settings    = [
58
                'request_timeout'   => 50,
59
                'encode_parameters' => 'json',
60
            ];
61
            $response = $this->integration->makeRequest($request_url, $data, $method, $settings);
62
63
            if (isset($response['error'])) {
64
                throw new ApiErrorException(isset($response['error_message']) ? $response['error_message'] : $response['error']['message'], ('invalid_grant' == $response['error']) ? 1 : 500);
65
            }
66
67
            return $response;
68
        }
69
    }
70
71
    /**
72
     * @return mixed|string
73
     *
74
     * @throws ApiErrorException
75
     */
76
    public function getLeadFields($object = null)
77
    {
78
        if (!$object) {
79
            $object = $this->object;
80
        }
81
        if ('company' == $object) {
82
            $object = 'Accounts'; //sugarCRM object name
83
        } elseif ('lead' == $object || 'Lead' == $object) {
84
            $object = 'Leads';
85
        } elseif ('contact' == $object || 'Contact' == $object) {
86
            $object = 'Contacts';
87
        }
88
89
        $tokenData = $this->integration->getKeys();
90
91
        if ('6' == $tokenData['version']) {
92
            return $this->request('get_module_fields', [], 'GET', $object);
93
        } else {
94
            $parameters = [
95
                'module_filter' => $object,
96
                'type_filter'   => 'modules',
97
            ];
98
99
            $response = $this->request('metadata', $parameters, 'GET', $object);
100
101
            return $response['modules'][$object];
102
        }
103
    }
104
105
    /**
106
     * @return array
107
     *
108
     * @throws \Mautic\PluginBundle\Exception\ApiErrorException
109
     */
110
    public function createLead(array $fields, $lead)
111
    {
112
        $tokenData       = $this->integration->getKeys();
113
        $createdLeadData = [];
114
        //search for Sugar id in mautic records first to avoid making an API call
115
        if (is_object($lead)) {
116
            $sugarLeadRecords = $this->integration->getSugarLeadId($lead);
0 ignored issues
show
The method getSugarLeadId() does not exist on MauticPlugin\MauticCrmBu...\CrmAbstractIntegration. It seems like you code against a sub-type of MauticPlugin\MauticCrmBu...\CrmAbstractIntegration such as MauticPlugin\MauticCrmBu...ion\SugarcrmIntegration. ( Ignorable by Annotation )

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

116
            /** @scrutinizer ignore-call */ 
117
            $sugarLeadRecords = $this->integration->getSugarLeadId($lead);
Loading history...
117
        }
118
        if ('6' == $tokenData['version']) {
119
            //if not found then go ahead and make an API call to find all the records with that email
120
            if (isset($fields['email1']) && empty($sugarLeadRecords)) {
121
                $sLeads           = $this->getLeads(['email' => $fields['email1'], 'offset' => 0, 'max_results' => 1000], 'Leads');
122
                $sugarLeadRecords = isset($sLeads['entry_list']) ? $sLeads['entry_list'] : [];
123
            }
124
            $leadFields = [];
125
            foreach ($fields as $name => $value) {
126
                if ('id' != $name) {
127
                    $leadFields[] = [
128
                        'name'  => $name,
129
                        'value' => $value,
130
                    ];
131
                }
132
            }
133
            $parameters = [
134
                'name_value_list' => $leadFields,
135
            ];
136
137
            if (!empty($sugarLeadRecords)) {
138
                foreach ($sugarLeadRecords as $sLeadRecord) {
139
                    $localParam  = $parameters;
0 ignored issues
show
The assignment to $localParam is dead and can be removed.
Loading history...
140
                    $sugarLeadId = (isset($sLeadRecord['integration_entity_id']) ? $sLeadRecord['integration_entity_id'] : $sLeadRecord['id']);
141
                    $sugarObject = (isset($sLeadRecord['integration_entity']) ? $sLeadRecord['integration_entity'] : 'Leads');
142
                    //update the converted contact if found and not the Lead
143
                    if (isset($sLeadRecord['contact_id']) && null != $sLeadRecord['contact_id'] && '' != $sLeadRecord['contact_id']) {
144
                        unset($fields['Company']); //because this record is not in the Contact object.
145
                        $localParams['name_value_list'][] = ['name' => 'id', 'value' => $sLeadRecord['contact_id']];
146
                        $createdLeadData[]                = $this->request('set_entry', $localParams, 'POST', 'Contacts');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $localParams seems to be defined later in this foreach loop on line 145. Are you sure it is defined here?
Loading history...
147
                    } else {
148
                        $localParams['name_value_list'][] = ['name' => 'id', 'value' => $sugarLeadId];
149
                        $createdLeadData[]                = $this->request('set_entry', $localParams, 'POST', $sugarObject);
150
                    }
151
                }
152
            } else {
153
                $createdLeadData = $this->request('set_entry', $parameters, 'POST', 'Leads');
154
            }
155
156
            //$createdLeadData[] = $this->request('set_entry', $parameters, 'POST');
157
        } else {
158
            //if not found then go ahead and make an API call to find all the records with that email
159
            if (isset($fields['email1']) && empty($sugarLeadRecords)) {
160
                $sLeads           = $this->getLeads(['email' => $fields['email1'], 'offset' => 0, 'max_results' => 1000], 'Leads');
161
                $sugarLeadRecords = $sLeads['records'];
162
            }
163
            unset($fields['id']);
164
165
            if (!empty($sugarLeadRecords)) {
166
                foreach ($sugarLeadRecords as $sLeadRecord) {
167
                    $sugarLeadId = (isset($sLeadRecord['integration_entity_id']) ? $sLeadRecord['integration_entity_id'] : $sLeadRecord['id']);
168
                    $sugarObject = (isset($sLeadRecord['integration_entity']) ? $sLeadRecord['integration_entity'] : 'Leads');
169
                    //update the converted contact if found and not the Lead
170
                    $config                = $this->integration->mergeConfigToFeatureSettings();
171
                    $fieldsToUpdateInSugar = isset($config['update_mautic']) ? array_keys($config['update_mautic'], 1) : [];
172
173
                    if (isset($sLeadRecord['contact_id']) && null != $sLeadRecord['contact_id'] && '' != $sLeadRecord['contact_id']) {
174
                        unset($fields['Company']); //because this record is not in the Contact object
175
                        $fieldsToUpdateInContactsSugar = $this->integration->cleanSugarData($config, $fieldsToUpdateInSugar, 'Contacts');
176
                        $contactSugarFields            = array_diff_key($fields, $fieldsToUpdateInContactsSugar);
177
                        $createdLeadData[]             = $this->request("Contacts/$sugarLeadId", $contactSugarFields, 'PUT', 'Contacts');
178
                    } else {
179
                        $fieldsToUpdateInLeadsSugar = $this->integration->cleanSugarData($config, $fieldsToUpdateInSugar, 'Leads');
180
                        $leadSugarFields            = array_diff_key($fields, $fieldsToUpdateInLeadsSugar);
181
                        $createdLeadData[]          = $this->request("$sugarObject/$sugarLeadId", $leadSugarFields, 'PUT', $sugarObject);
182
                    }
183
                }
184
            } else {
185
                $createdLeadData = $this->request('Leads', $fields, 'POST', 'Leads');
186
            }
187
            //$createdLeadData[] = $this->request('set_entry', $fields, 'POST', 'Leads');
188
        }
189
190
        return $createdLeadData;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $createdLeadData also could return the type string which is incompatible with the documented return type array.
Loading history...
191
    }
192
193
    /**
194
     * @return array
195
     *
196
     * @throws \Mautic\PluginBundle\Exception\ApiErrorException
197
     */
198
    public function syncLeadsToSugar(array $data)
199
    {
200
        $tokenData = $this->integration->getKeys();
201
        $object    = $this->object;
0 ignored issues
show
The assignment to $object is dead and can be removed.
Loading history...
202
203
        if ('6' == $tokenData['version']) {
204
            $leadFieldsList = [];
0 ignored issues
show
The assignment to $leadFieldsList is dead and can be removed.
Loading history...
205
            $response       = [];
206
207
            foreach ($data as $object => $leadFieldsList) {
208
                $parameters = [
209
                    'name_value_lists' => $leadFieldsList,
210
                ];
211
                $resp = $this->request('set_entries', $parameters, 'POST', $object);
212
                if (!empty($resp)) {
213
                    foreach ($leadFieldsList as $k => $leadFields) {
214
                        $fields = [];
215
                        foreach ($leadFields as $item) {
216
                            $fields[$item['name']] = $item['value'];
217
                        }
218
                        if (isset($resp['ids'])) {
219
                            $result = ['reference_id' => $fields['reference_id'],
220
                                       'id'           => $resp['ids'][$k],
221
                                       'new'          => !isset($fields['id']),
222
                                       'ko'           => false, ];
223
                        }
224
                        if (isset($resp['error'])) {
225
                            $result['ko']    = true;
226
                            $result['error'] = $resp['error']['message'];
227
                        }
228
                        if (isset($fields['id']) && $fields['id'] != $resp['ids'][$k]) {
229
                            $result['ko']    = true;
230
                            $result['error'] = 'Returned ID does not correspond to input id';
231
                        }
232
233
                        $response[] = $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
234
                    }
235
                }
236
            }
237
238
            return $response;
239
        } else {
240
            $leadFieldsList = [];
241
            $response       = [];
242
            //body is prepared for Sugar6. Translate it to sugar 7
243
            $reference_ids = [];
0 ignored issues
show
The assignment to $reference_ids is dead and can be removed.
Loading history...
244
            foreach ($data as $object => $leadFieldsList) {
245
                $requests = [];
246
                $all_ids  = [];
247
                foreach ($leadFieldsList as $body) {
248
                    $fields = [];
249
                    $ids    = [];
250
                    foreach ($body as $field) {
251
                        $fields[$field['name']] = $field['value'];
252
                    }
253
                    $request = [];
254
                    if (isset($fields['id'])) {
255
                        $ids['id'] = $fields['id'];
256
                        //Update record
257
                        $sugarLeadId = $fields['id'];
258
                        unset($fields['id']);
259
                        $request['method'] = 'PUT';
260
                        $request['url']    = "/v10/$object/$sugarLeadId";
261
                        $request['data']   = $fields;
262
                    } else {
263
                        //Create record
264
                        $request['data']   = $fields;
265
                        $request['url']    = '/v10/'.$object;
266
                        $request['method'] = 'POST';
267
                    }
268
                    $requests[]          = $request;
269
                    $ids['reference_id'] = $fields['reference_id'];
270
                    $all_ids[]           = $ids;
271
                }
272
                $parameters = [
273
                    'requests' => $requests,
274
                ];
275
276
                $resp = $this->request('bulk', $parameters, 'POST', $object);
277
                if (!empty($resp)) {
278
                    foreach ($resp as $k => $leadFields) {
279
                        $fields = $leadFields['contents'];
280
                        if (200 != $leadFields['status']) {
281
                            $result = ['ko' => true,
282
                                'error'     => $leadFields['error'].' '.$leadFields['error_message'], ];
283
                        } else {
284
                            $result = ['reference_id' => $all_ids[$k]['reference_id'],
285
                                    'id'              => $fields['id'],
286
                                    'new'             => !isset($all_ids[$k]['id']),
287
                                    'ko'              => false, ];
288
                            if (isset($all_ids[$k]['id']) && $fields['id'] != $all_ids[$k]['id']) {
289
                                $result['ko']    = true;
290
                                $result['error'] = 'Returned ID does not correspond to input id';
291
                            }
292
                        }
293
                        $response[] = $result;
294
                    }
295
                }
296
            }
297
298
            return $response;
299
        }
300
    }
301
302
    /**
303
     * @param $object
304
     *                 TODO 7.x
305
     *
306
     * @return array|mixed|string
307
     */
308
    public function createLeadActivity(array $activity, $object)
309
    {
310
        $config    = $this->integration->getIntegrationSettings()->getFeatureSettings();
0 ignored issues
show
The assignment to $config is dead and can be removed.
Loading history...
311
        $tokenData = $this->integration->getKeys();
312
313
        //1st : set_entries to return ids module_name : "Leads" or "Contacts" and name_value_lists (array of arrays of name/value)
314
        $module_name          = $object;
0 ignored issues
show
The assignment to $module_name is dead and can be removed.
Loading history...
315
        $set_name_value_lists = [];
316
        // set relationship
317
        $module_names     = []; //Contacts or Leads
318
        $module_ids       = []; //Contacts or leads ids
319
        $link_field_names = []; //Array of mtc_webactivities_contacts or mtc_webactivities_leads
320
        $related_ids      = []; //Array of arrays of web activity array
321
        $name_value_lists = []; //array of empty arrays
322
        $delete_array     = []; //Array of 0
323
        //set_relationships
324
        $s7_records = [];
325
        //Send activities and get back sugar activities id
326
327
        if (!empty($activity)) {
328
            foreach ($activity as $sugarId => $records) {
329
                foreach ($records['records'] as $record) {
330
                    $rec   = [];
331
                    $rec[] = ['name' => 'name', 'value' => $record['name']];
332
                    $rec[] = ['name' => 'description', 'value' => $record['description']];
333
                    $rec[] = ['name' => 'url', 'value' => $records['leadUrl']];
334
                    $rec[] = ['name' => 'date_entered', 'value' => $record['dateAdded']->format('c')];
335
                    $rec[] = ['name' => 'reference_id', 'value' => $record['id'].'-'.$sugarId];
336
                    if ('Contacts' == $object) {
337
                        $rec[] = ['name' => 'contact_id_c', 'value' => $sugarId];
338
                    } else {
339
                        $rec[] = ['name' => 'lead_id_c', 'value' => $sugarId];
340
                    }
341
                    $set_name_value_lists[] = $rec; //Sugar 6
342
                    $s7_record              = [];
343
                    foreach ($rec as $r) {
344
                        $s7_record[$r['name']] = $r['value'];
345
                    }
346
                    $s7_records[] = $s7_record;
347
                }
348
            }
349
350
            $parameters = [
351
                    'name_value_lists' => $set_name_value_lists,
352
                ];
353
            if ('6' == $tokenData['version']) {
354
                $resp = $this->request('set_entries', $parameters, 'POST', 'mtc_WebActivities');
355
            } else {
356
                $requests = [];
357
                foreach ($s7_records as $fields) {
358
                    //Create record
359
                    $request['data']   = $fields;
360
                    $request['url']    = '/v10/'.'mtc_WebActivities';
361
                    $request['method'] = 'POST';
362
                    $requests[]        = $request;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request seems to be defined later in this foreach loop on line 359. Are you sure it is defined here?
Loading history...
363
                }
364
                $parameters = [
365
                    'requests' => $requests,
366
                ];
367
                $resp = $this->request('bulk', $parameters, 'POST', 'bulk');
368
            }
369
370
            if ('6' == $tokenData['version']) {
371
                //Send sugar relationsips
372
                if (!empty($resp)) {
373
                    $nbLeads = 0;
374
                    $nbAct   = 0;
375
                    $idList  = [];
376
377
                    foreach ($activity as $sugarId => $records) {
378
                        $related_ids_row = [];
379
380
                        $module_names[] = $object;
381
                        $module_ids[]   = $sugarId;
382
                        if ('Contacts' == $object) {
383
                            $link_field_names[] = 'mtc_webactivities_contacts';
384
                        } else {
385
                            $link_field_names[] = 'mtc_webactivities_leads';
386
                        }
387
                        ++$nbLeads;
388
                        foreach ($records['records'] as $record) {
389
                            $name_value_lists[] = [];
390
                            $delete_array[]     = 0;
391
                            $idList[]           = $sugarId;
392
                            $related_ids_row[]  = $resp['ids'][$nbAct];
393
                            ++$nbAct;
394
                        }
395
                        $related_ids[] = $related_ids_row;
396
                    }
397
                    $parameters = [
398
                        'module_names'     => $module_names, //Contacts or Leads
399
                        'module_ids'       => $module_ids, //Contacts or leads ids
400
                        'link_field_names' => $link_field_names, //Array of mtc_webactivities_contacts or mtc_webactivities_leads
401
                        'related_ids'      => $related_ids, //Array of arrays of web activity array
402
                        'name_value_lists' => $name_value_lists, //array of empty arrays
403
                        'delete_array'     => $delete_array, //Array of 0
404
                    ];
405
                    $resp2 = $this->request('set_relationships', $parameters, 'POST', $object);
0 ignored issues
show
The assignment to $resp2 is dead and can be removed.
Loading history...
406
                }
407
            } else {
408
                //Sugar 7 set relationship
409
                if (!empty($resp)) {
410
                    $nbAct = 0;
411
                    foreach ($activity as $sugarId => $records) {
412
                        if ('Contacts' == $object) {
413
                            $link_field_name = 'mtc_webactivities_contacts';
414
                        } else {
415
                            $link_field_name = 'mtc_webactivities_leads';
416
                        }
417
                        foreach ($records['records'] as $record) {
418
                            if (!isset($resp[$nbAct]['contents']['id'])) {
419
                                continue;
420
                            } //current Web activity was not created
421
                            $wa_id = $resp[$nbAct]['contents']['id'];
422
                            $resp2 = $this->request("mtc_WebActivities/$wa_id/link/$link_field_name/$sugarId", [], 'POST');
423
                            ++$nbAct;
424
                        }
425
                    }
426
                }
427
            }
428
429
            return [];
430
        }
431
    }
432
433
    public function getEmailBySugarUserId($query = null)
434
    {
435
        $tokenData = $this->integration->getKeys();
436
        if ('6' == $tokenData['version']) {
437
            if (isset($query['emails'])) {
438
                $q = " users.id IN (SELECT bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (eabr.email_address_id = ea.id) WHERE bean_module = 'Users' AND ea.email_address IN ('".implode("','", $query['emails'])."') AND eabr.deleted=0) ";
439
            }
440
            if (isset($query['ids'])) {
441
                $q = " users.id IN ('".implode("','", $query['ids'])."') ";
442
            }
443
444
            $data   = ['filter' => 'all'];
0 ignored issues
show
The assignment to $data is dead and can be removed.
Loading history...
445
            $fields = ['id', 'email1'];
446
447
            $parameters = [
448
                     'query'                    => $q,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $q does not seem to be defined for all execution paths leading up to this point.
Loading history...
449
                     'order_by'                 => '',
450
                     'offset'                   => 0,
451
                    'select_fields'             => $fields,
452
                    'link_name_to_fields_array' => [/* TO BE MODIFIED */
453
                    ],
454
                    'max_results' => 1000,
455
                    'deleted'     => 0,
456
                    'favorites'   => false,
457
                ];
458
            $data = $this->request('get_entry_list', $parameters, 'GET', 'Users');
459
460
            if (isset($query['type']) && 'BYEMAIL' == $query['type']) {
461
                $type = 'BYEMAIL';
462
            } else {
463
                $type = 'BYID';
464
            }
465
466
            $res = [];
467
            if (isset($data['entry_list'])) {
468
                foreach ($data['entry_list'] as $record) {
469
                    $fields       = [];
470
                    $fields['id'] = $record['id'];
471
                    foreach ($record['name_value_list'] as $item) {
472
                        $fields[$item['name']] = $item['value'];
473
                    }
474
                    if ('BYID' == $type) {
475
                        $res[$fields['id']] = $fields['email1'];
476
                    } elseif (isset($fields['email1'])) {
477
                        $res[$fields['email1']] = $fields['id'];
478
                    } elseif ('BYEMAIL' == $type && !isset($fields['email1'])) {
479
                        $res[$query['emails'][0]] = $fields['id'];
480
                    }
481
                }
482
            }
483
484
            return $res;
485
        } else {
486
            //TODO
487
488
            if (isset($query['emails'])) {
489
                $filter[] = ['email_addresses.email_address' => ['$in' => $query['emails']]];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$filter was never initialized. Although not strictly required by PHP, it is generally a good practice to add $filter = array(); before regardless.
Loading history...
490
                $filter[] = ['deleted' => '0'];
491
            }
492
            if (isset($query['ids'])) {
493
                $filter[] = ['id' => ['$in' => $query['ids']]];
494
            }
495
496
            $data   = ['filter' => 'all'];
497
            $fields = ['id', 'email1', 'email'];
498
499
            $parameters = [
500
                    'filter' => [['$and' => $filter]],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filter does not seem to be defined for all execution paths leading up to this point.
Loading history...
501
                    'offset' => 0,
502
                'fields'     => implode(',', $fields),
503
                'max_num'    => 1000,
504
                //'deleted'     => 0,
505
                //'favorites'   => false,
506
            ];
507
            $data = $this->request('Users/filter', $parameters, 'POST', 'Users');
508
509
            if (isset($query['type']) && 'BYEMAIL' == $query['type']) {
510
                $type = 'BYEMAIL';
511
            } else {
512
                $type = 'BYID';
513
            }
514
            $res = [];
515
            if (isset($data['records'])) {
516
                foreach ($data['records'] as $record) {
517
                    if (isset($record['email'][0]['email_address']) && '' != $record['email'][0]['email_address']) {
518
                        $found_email = $record['email'][0]['email_address'];
519
                        if (isset($record['name_value_list'])) {
520
                            foreach ($record['name_value_list'] as $email) {
521
                                if ('' != $email['email_address'] && 1 == $email['primary_address']) {
522
                                    $found_email = $email;
523
                                    break;
524
                                }
525
                            }
526
                        }
527
                        if ('BYID' == $type) {
528
                            $res[$record['id']] = $found_email;
529
                        } else {
530
                            $res[$found_email] = $record['id'];
531
                        }
532
                    }
533
                }
534
            }
535
536
            return $res;
537
        }
538
    }
539
540
    public function getIdBySugarEmail($query = null)
541
    {
542
        if (null == $query) {
543
            $query = ['type' => 'BYEMAIL'];
544
        } else {
545
            $query['type'] = 'BYEMAIL';
546
        }
547
548
        return $this->getEmailBySugarUserId($query);
549
    }
550
551
    /**
552
     * Get SugarCRM leads.
553
     *
554
     * @param array  $query
555
     * @param string $object
556
     *
557
     * @return mixed
558
     */
559
    public function getLeads($query, $object)
560
    {
561
        $tokenData       = $this->integration->getKeys();
562
        $data            = ['filter' => 'all'];
563
        $availableFields = $this->integration->getIntegrationSettings()->getFeatureSettings();
564
565
        switch ($object) {
566
            case 'company':
567
            case 'Account':
568
            case 'Accounts':
569
                $fields = array_keys(array_filter($availableFields['companyFields']));
570
                break;
571
            default:
572
                $mixedFields = array_filter($availableFields['leadFields']);
573
                $fields      = [];
574
                $object      = ('Contacts' == $object) ? 'Contacts' : 'Leads';
575
                foreach ($mixedFields as $sugarField => $mField) {
576
                    if (false !== strpos($sugarField, '__'.$object)) {
577
                        $fields[] = str_replace('__'.$object, '', $sugarField);
578
                    }
579
                    if (false !== strpos($sugarField, '-'.$object)) {
580
                        $fields[] = str_replace('-'.$object, '', $sugarField);
581
                    }
582
                }
583
        }
584
585
        if ('6' == $tokenData['version']) {
586
            $result = [];
0 ignored issues
show
The assignment to $result is dead and can be removed.
Loading history...
587
588
            if (!empty($fields)) {
589
                $q   = '';
0 ignored issues
show
The assignment to $q is dead and can be removed.
Loading history...
590
                $qry = [];
591
                if (isset($query['start'])) {
592
                    $qry[] = ' '.strtolower($object).".date_modified >= '".$query['start']."' ";
593
                }
594
                if (isset($query['end'])) {
595
                    $qry[] = ' '.strtolower($object).".date_modified <= '".$query['end']."' ";
596
                }
597
                if (isset($query['email'])) {
598
                    $qry[]    = " leads.id IN (SELECT bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (eabr.email_address_id = ea.id) WHERE bean_module = 'Leads' AND ea.email_address = '".$query['email']."' AND eabr.deleted=0) ";
599
                    $fields[] = 'contact_id';
600
                }
601
                if (isset($query['checkemail'])) {
602
                    $qry[]    = ' leads.deleted=0 ';
603
                    $qry[]    = " leads.id IN (SELECT bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (eabr.email_address_id = ea.id) WHERE bean_module = 'Leads' AND ea.email_address IN ('".implode("','", $query['checkemail'])."') AND eabr.deleted=0) ";
604
                    $fields[] = 'contact_id';
605
                    $fields[] = 'deleted';
606
                }
607
                if (isset($query['checkemail_contacts'])) {
608
                    $qry[]    = ' contacts.deleted=0 ';
609
                    $qry[]    = " contacts.id IN (SELECT bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (eabr.email_address_id = ea.id) WHERE bean_module = 'Contacts' AND ea.email_address IN ('".implode("','", $query['checkemail_contacts'])."') AND eabr.deleted=0) ";
610
                    $fields[] = 'deleted';
611
                }
612
613
                $q        = implode('AND', $qry);
614
                $fields[] = 'id';
615
                $fields[] = 'date_modified';
616
                $fields[] = 'date_entered';
617
                $fields[] = 'assigned_user_id';
618
                $fields[] = 'email1';
619
                if ('Accounts' != $object) {
620
                    $fields[] = 'account_id';
621
                }
622
                $parameters = [
623
                     'query'                    => $q,
624
                     'order_by'                 => '',
625
                     'offset'                   => $query['offset'],
626
                    'select_fields'             => $fields,
627
                    'link_name_to_fields_array' => [/* TO BE MODIFIED */
628
                        [
629
                            'name'  => 'email_addresses',
630
                            'value' => [
631
                                'email_address',
632
                                'opt_out',
633
                                'primary_address',
634
                            ],
635
                        ],
636
                    ],
637
                    'max_results' => $query['max_results'],
638
                    'deleted'     => 0,
639
                    'favorites'   => false,
640
                ];
641
642
                return $this->request('get_entry_list', $parameters, 'GET', $object);
643
            }
644
        } else {
645
            if (!empty($fields)) {
646
                $q      = '';
647
                $qry    = [];
0 ignored issues
show
The assignment to $qry is dead and can be removed.
Loading history...
648
                $filter = [];
649
                if (isset($query['start'])) {
650
                    $filter[] = ['date_modified' => ['$gte' => $query['start']]];
651
                    //$qry[] = ' '.strtolower($object).".date_modified >= '".$query['start']."' ";
652
                }
653
                if (isset($query['end'])) {
654
                    $filter[] = ['date_modified' => ['$lte' => $query['end']]];
655
                    //$qry[] = ' '.strtolower($object).".date_modified <= '".$query['end']."' ";
656
                }
657
                if (isset($query['email'])) {
658
                    $filter[] = ['email' => ['$equals' => $query['email']]];
659
                    //$qry[]    = " leads.id IN (SELECT bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (eabr.email_address_id = ea.id) WHERE bean_module = 'Leads' AND ea.email_address = '".$query['email']."' AND eabr.deleted=0) ";
660
                    $fields[] = 'contact_id';
661
                }
662
                if (isset($query['checkemail'])) {
663
                    $filter[] = ['email' => ['$in' => $query['checkemail']]];
664
                    $filter[] = ['deleted' => '0'];
665
                    $fields   = []; //Do not need previous fields
666
                    $fields[] = 'contact_id';
667
                    $fields[] = 'deleted';
668
                }
669
                if (isset($query['checkemail_contacts'])) {
670
                    $filter[] = ['email' => ['$in' => $query['checkemail_contacts']]];
671
                    $filter[] = ['deleted' => '0'];
672
                    $fields   = []; //Do not need previous fields
673
                    $fields[] = 'deleted';
674
                }
675
                $fields[] = 'id';
676
                $fields[] = 'date_modified';
677
                $fields[] = 'date_entered';
678
                $fields[] = 'assigned_user_id';
679
                $fields[] = 'email1';
680
                if ('Accounts' != $object) {
681
                    $fields[] = 'account_id';
682
                }
683
                //$filter_args = ['filter' => [['$and' => $filter]]];
684
                //$fields_arg  = implode(',', $fields);
685
                $parameters = [
686
//                     'order_by'                 => '',
687
                     'filter' => [['$and' => $filter]],
688
                     'offset' => $query['offset'],
689
                    'fields'  => implode(',', $fields),
690
                    'max_num' => $query['max_results'],
691
                    //'deleted'     => 0,
692
                    //'favorites'   => false,
693
                ];
694
695
                return $this->request("$object/filter", $parameters, 'POST', $object);
696
            }
697
        }
698
    }
699
}
700