Merge pull request #16953 from jitendrapurohit/core-1685
[civicrm-core.git] / CRM / Utils / DeprecatedUtils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /*
19 * These functions have been deprecated out of API v3 Utils folder as they are not part of the
20 * API. Calling API functions directly is not supported & these functions are not called by any
21 * part of the API so are not really part of the api
22 *
23 */
24
25 require_once 'api/v3/utils.php';
26
27 /**
28 * Check duplicate contacts based on de-dupe parameters.
29 *
30 * @param array $params
31 *
32 * @return array
33 */
34 function _civicrm_api3_deprecated_check_contact_dedupe($params) {
35 static $cIndieFields = NULL;
36 static $defaultLocationId = NULL;
37
38 $contactType = $params['contact_type'];
39 if ($cIndieFields == NULL) {
40 require_once 'CRM/Contact/BAO/Contact.php';
41 $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields($contactType);
42 $cIndieFields = $cTempIndieFields;
43
44 require_once "CRM/Core/BAO/LocationType.php";
45 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
46
47 // set the value to default location id else set to 1
48 if (!$defaultLocationId = (int) $defaultLocation->id) {
49 $defaultLocationId = 1;
50 }
51 }
52
53 require_once 'CRM/Contact/BAO/Query.php';
54 $locationFields = CRM_Contact_BAO_Query::$_locationSpecificFields;
55
56 $contactFormatted = [];
57 foreach ($params as $key => $field) {
58 if ($field == NULL || $field === '') {
59 continue;
60 }
61 // CRM-17040, Considering only primary contact when importing contributions. So contribution inserts into primary contact
62 // instead of soft credit contact.
63 if (is_array($field) && $key != "soft_credit") {
64 foreach ($field as $value) {
65 $break = FALSE;
66 if (is_array($value)) {
67 foreach ($value as $name => $testForEmpty) {
68 if ($name !== 'phone_type' &&
69 ($testForEmpty === '' || $testForEmpty == NULL)
70 ) {
71 $break = TRUE;
72 break;
73 }
74 }
75 }
76 else {
77 $break = TRUE;
78 }
79 if (!$break) {
80 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
81 }
82 }
83 continue;
84 }
85
86 $value = [$key => $field];
87
88 // check if location related field, then we need to add primary location type
89 if (in_array($key, $locationFields)) {
90 $value['location_type_id'] = $defaultLocationId;
91 }
92 elseif (array_key_exists($key, $cIndieFields)) {
93 $value['contact_type'] = $contactType;
94 }
95
96 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
97 }
98
99 $contactFormatted['contact_type'] = $contactType;
100
101 return _civicrm_api3_deprecated_duplicate_formatted_contact($contactFormatted);
102 }
103
104 /**
105 * take the input parameter list as specified in the data model and
106 * convert it into the same format that we use in QF and BAO object
107 *
108 * @param array $params
109 * Associative array of property name/value.
110 * pairs to insert in new contact.
111 * @param array $values
112 * The reformatted properties that we can use internally.
113 *
114 * @param array|bool $create Is the formatted Values array going to
115 * be used for CRM_Activity_BAO_Activity::create()
116 *
117 * @return array|CRM_Error
118 */
119 function _civicrm_api3_deprecated_activity_formatted_param(&$params, &$values, $create = FALSE) {
120 // copy all the activity fields as is
121 $fields = CRM_Activity_DAO_Activity::fields();
122 _civicrm_api3_store_values($fields, $params, $values);
123
124 require_once 'CRM/Core/OptionGroup.php';
125 $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
126
127 foreach ($params as $key => $value) {
128 // ignore empty values or empty arrays etc
129 if (CRM_Utils_System::isNull($value)) {
130 continue;
131 }
132
133 //Handling Custom Data
134 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
135 $values[$key] = $value;
136 $type = $customFields[$customFieldID]['html_type'];
137 if (CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID])) {
138 $mulValues = explode(',', $value);
139 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
140 $values[$key] = [];
141 foreach ($mulValues as $v1) {
142 foreach ($customOption as $customValueID => $customLabel) {
143 $customValue = $customLabel['value'];
144 if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
145 (strtolower(trim($customValue)) == strtolower(trim($v1)))
146 ) {
147 if ($type == 'CheckBox') {
148 $values[$key][$customValue] = 1;
149 }
150 else {
151 $values[$key][] = $customValue;
152 }
153 }
154 }
155 }
156 }
157 elseif ($type == 'Select' || $type == 'Radio') {
158 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
159 foreach ($customOption as $customFldID => $customValue) {
160 $val = $customValue['value'] ?? NULL;
161 $label = $customValue['label'] ?? NULL;
162 $label = strtolower($label);
163 $value = strtolower(trim($value));
164 if (($value == $label) || ($value == strtolower($val))) {
165 $values[$key] = $val;
166 }
167 }
168 }
169 }
170
171 if ($key == 'target_contact_id') {
172 if (!CRM_Utils_Rule::integer($value)) {
173 return civicrm_api3_create_error("contact_id not valid: $value");
174 }
175 $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
176 if (!$contactID) {
177 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
178 }
179 }
180 }
181 return NULL;
182 }
183
184 /**
185 * This function adds the contact variable in $values to the
186 * parameter list $params. For most cases, $values should have length 1. If
187 * the variable being added is a child of Location, a location_type_id must
188 * also be included. If it is a child of phone, a phone_type must be included.
189 *
190 * @param array $values
191 * The variable(s) to be added.
192 * @param array $params
193 * The structured parameter list.
194 *
195 * @return bool|CRM_Utils_Error
196 */
197 function _civicrm_api3_deprecated_add_formatted_param(&$values, &$params) {
198 // Crawl through the possible classes:
199 // Contact
200 // Individual
201 // Household
202 // Organization
203 // Location
204 // Address
205 // Email
206 // Phone
207 // IM
208 // Note
209 // Custom
210
211 // Cache the various object fields
212 static $fields = NULL;
213
214 if ($fields == NULL) {
215 $fields = [];
216 }
217
218 // first add core contact values since for other Civi modules they are not added
219 require_once 'CRM/Contact/BAO/Contact.php';
220 $contactFields = CRM_Contact_DAO_Contact::fields();
221 _civicrm_api3_store_values($contactFields, $values, $params);
222
223 if (isset($values['contact_type'])) {
224 // we're an individual/household/org property
225
226 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
227
228 _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
229 return TRUE;
230 }
231
232 if (isset($values['individual_prefix'])) {
233 if (!empty($params['prefix_id'])) {
234 $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
235 $params['prefix'] = $prefixes[$params['prefix_id']];
236 }
237 else {
238 $params['prefix'] = $values['individual_prefix'];
239 }
240 return TRUE;
241 }
242
243 if (isset($values['individual_suffix'])) {
244 if (!empty($params['suffix_id'])) {
245 $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
246 $params['suffix'] = $suffixes[$params['suffix_id']];
247 }
248 else {
249 $params['suffix'] = $values['individual_suffix'];
250 }
251 return TRUE;
252 }
253
254 // CRM-4575
255 if (isset($values['email_greeting'])) {
256 if (!empty($params['email_greeting_id'])) {
257 $emailGreetingFilter = [
258 'contact_type' => $params['contact_type'] ?? NULL,
259 'greeting_type' => 'email_greeting',
260 ];
261 $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
262 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
263 }
264 else {
265 $params['email_greeting'] = $values['email_greeting'];
266 }
267
268 return TRUE;
269 }
270
271 if (isset($values['postal_greeting'])) {
272 if (!empty($params['postal_greeting_id'])) {
273 $postalGreetingFilter = [
274 'contact_type' => $params['contact_type'] ?? NULL,
275 'greeting_type' => 'postal_greeting',
276 ];
277 $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
278 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
279 }
280 else {
281 $params['postal_greeting'] = $values['postal_greeting'];
282 }
283 return TRUE;
284 }
285
286 if (isset($values['addressee'])) {
287 if (!empty($params['addressee_id'])) {
288 $addresseeFilter = [
289 'contact_type' => $params['contact_type'] ?? NULL,
290 'greeting_type' => 'addressee',
291 ];
292 $addressee = CRM_Core_PseudoConstant::addressee($addresseeFilter);
293 $params['addressee'] = $addressee[$params['addressee_id']];
294 }
295 else {
296 $params['addressee'] = $values['addressee'];
297 }
298 return TRUE;
299 }
300
301 if (isset($values['gender'])) {
302 if (!empty($params['gender_id'])) {
303 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
304 $params['gender'] = $genders[$params['gender_id']];
305 }
306 else {
307 $params['gender'] = $values['gender'];
308 }
309 return TRUE;
310 }
311
312 if (!empty($values['preferred_communication_method'])) {
313 $comm = [];
314 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method')), CASE_LOWER);
315
316 $preffComm = explode(',', $values['preferred_communication_method']);
317 foreach ($preffComm as $v) {
318 $v = strtolower(trim($v));
319 if (array_key_exists($v, $pcm)) {
320 $comm[$pcm[$v]] = 1;
321 }
322 }
323
324 $params['preferred_communication_method'] = $comm;
325 return TRUE;
326 }
327
328 // format the website params.
329 if (!empty($values['url'])) {
330 static $websiteFields;
331 if (!is_array($websiteFields)) {
332 require_once 'CRM/Core/DAO/Website.php';
333 $websiteFields = CRM_Core_DAO_Website::fields();
334 }
335 if (!array_key_exists('website', $params) ||
336 !is_array($params['website'])
337 ) {
338 $params['website'] = [];
339 }
340
341 $websiteCount = count($params['website']);
342 _civicrm_api3_store_values($websiteFields, $values,
343 $params['website'][++$websiteCount]
344 );
345
346 return TRUE;
347 }
348
349 // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
350 if (!empty($values['location_type_id'])) {
351 static $fields = NULL;
352 if ($fields == NULL) {
353 $fields = [];
354 }
355
356 foreach ([
357 'Phone',
358 'Email',
359 'IM',
360 'OpenID',
361 'Phone_Ext',
362 ] as $block) {
363 $name = strtolower($block);
364 if (!array_key_exists($name, $values)) {
365 continue;
366 }
367
368 if ($name == 'phone_ext') {
369 $block = 'Phone';
370 }
371
372 // block present in value array.
373 if (!array_key_exists($name, $params) || !is_array($params[$name])) {
374 $params[$name] = [];
375 }
376
377 if (!array_key_exists($block, $fields)) {
378 $className = "CRM_Core_DAO_$block";
379 $fields[$block] =& $className::fields();
380 }
381
382 $blockCnt = count($params[$name]);
383
384 // copy value to dao field name.
385 if ($name == 'im') {
386 $values['name'] = $values[$name];
387 }
388
389 _civicrm_api3_store_values($fields[$block], $values,
390 $params[$name][++$blockCnt]
391 );
392
393 if (empty($params['id']) && ($blockCnt == 1)) {
394 $params[$name][$blockCnt]['is_primary'] = TRUE;
395 }
396
397 // we only process single block at a time.
398 return TRUE;
399 }
400
401 // handle address fields.
402 if (!array_key_exists('address', $params) || !is_array($params['address'])) {
403 $params['address'] = [];
404 }
405
406 $addressCnt = 1;
407 foreach ($params['address'] as $cnt => $addressBlock) {
408 if (CRM_Utils_Array::value('location_type_id', $values) ==
409 CRM_Utils_Array::value('location_type_id', $addressBlock)
410 ) {
411 $addressCnt = $cnt;
412 break;
413 }
414 $addressCnt++;
415 }
416
417 if (!array_key_exists('Address', $fields)) {
418 $fields['Address'] = CRM_Core_DAO_Address::fields();
419 }
420
421 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
422 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
423 // the address in CRM_Core_BAO_Address::create method
424 if (!empty($values['location_type_id'])) {
425 static $customFields = [];
426 if (empty($customFields)) {
427 $customFields = CRM_Core_BAO_CustomField::getFields('Address');
428 }
429 // make a copy of values, as we going to make changes
430 $newValues = $values;
431 foreach ($values as $key => $val) {
432 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
433 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
434 // mark an entry in fields array since we want the value of custom field to be copied
435 $fields['Address'][$key] = NULL;
436
437 $htmlType = $customFields[$customFieldID]['html_type'] ?? NULL;
438 if (CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID]) && $val) {
439 $mulValues = explode(',', $val);
440 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
441 $newValues[$key] = [];
442 foreach ($mulValues as $v1) {
443 foreach ($customOption as $v2) {
444 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
445 (strtolower($v2['value']) == strtolower(trim($v1)))
446 ) {
447 if ($htmlType == 'CheckBox') {
448 $newValues[$key][$v2['value']] = 1;
449 }
450 else {
451 $newValues[$key][] = $v2['value'];
452 }
453 }
454 }
455 }
456 }
457 }
458 }
459 // consider new values
460 $values = $newValues;
461 }
462
463 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
464
465 $addressFields = [
466 'county',
467 'country',
468 'state_province',
469 'supplemental_address_1',
470 'supplemental_address_2',
471 'supplemental_address_3',
472 'StateProvince.name',
473 ];
474
475 foreach ($addressFields as $field) {
476 if (array_key_exists($field, $values)) {
477 if (!array_key_exists('address', $params)) {
478 $params['address'] = [];
479 }
480 $params['address'][$addressCnt][$field] = $values[$field];
481 }
482 }
483
484 if ($addressCnt == 1) {
485
486 $params['address'][$addressCnt]['is_primary'] = TRUE;
487 }
488 return TRUE;
489 }
490
491 if (isset($values['note'])) {
492 // add a note field
493 if (!isset($params['note'])) {
494 $params['note'] = [];
495 }
496 $noteBlock = count($params['note']) + 1;
497
498 $params['note'][$noteBlock] = [];
499 if (!isset($fields['Note'])) {
500 $fields['Note'] = CRM_Core_DAO_Note::fields();
501 }
502
503 // get the current logged in civicrm user
504 $session = CRM_Core_Session::singleton();
505 $userID = $session->get('userID');
506
507 if ($userID) {
508 $values['contact_id'] = $userID;
509 }
510
511 _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
512
513 return TRUE;
514 }
515
516 // Check for custom field values
517
518 if (empty($fields['custom'])) {
519 $fields['custom'] = &CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $values),
520 FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE
521 );
522 }
523
524 foreach ($values as $key => $value) {
525 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
526 // check if it's a valid custom field id
527
528 if (!array_key_exists($customFieldID, $fields['custom'])) {
529 return civicrm_api3_create_error('Invalid custom field ID');
530 }
531 else {
532 $params[$key] = $value;
533 }
534 }
535 }
536 }
537
538 /**
539 *
540 * @param array $params
541 *
542 * @return array
543 * <type>
544 */
545 function _civicrm_api3_deprecated_duplicate_formatted_contact($params) {
546 $id = $params['id'] ?? NULL;
547 $externalId = $params['external_identifier'] ?? NULL;
548 if ($id || $externalId) {
549 $contact = new CRM_Contact_DAO_Contact();
550
551 $contact->id = $id;
552 $contact->external_identifier = $externalId;
553
554 if ($contact->find(TRUE)) {
555 if ($params['contact_type'] != $contact->contact_type) {
556 return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types");
557 }
558
559 $error = CRM_Core_Error::createError("Found matching contacts: $contact->id",
560 CRM_Core_Error::DUPLICATE_CONTACT,
561 'Fatal', $contact->id
562 );
563 return civicrm_api3_create_error($error->pop());
564 }
565 }
566 else {
567 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised');
568
569 if (!empty($ids)) {
570 $ids = implode(',', $ids);
571 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
572 CRM_Core_Error::DUPLICATE_CONTACT,
573 'Fatal', $ids
574 );
575 return civicrm_api3_create_error($error->pop());
576 }
577 }
578 return civicrm_api3_create_success(TRUE);
579 }
580
581 /**
582 * Validate a formatted contact parameter list.
583 *
584 * @param array $params
585 * Structured parameter list (as in crm_format_params).
586 *
587 * @return bool|CRM_Core_Error
588 */
589 function _civicrm_api3_deprecated_validate_formatted_contact(&$params) {
590 // Look for offending email addresses
591
592 if (array_key_exists('email', $params)) {
593 foreach ($params['email'] as $count => $values) {
594 if (!is_array($values)) {
595 continue;
596 }
597 if ($email = CRM_Utils_Array::value('email', $values)) {
598 // validate each email
599 if (!CRM_Utils_Rule::email($email)) {
600 return civicrm_api3_create_error('No valid email address');
601 }
602
603 // check for loc type id.
604 if (empty($values['location_type_id'])) {
605 return civicrm_api3_create_error('Location Type Id missing.');
606 }
607 }
608 }
609 }
610
611 // Validate custom data fields
612 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
613 foreach ($params['custom'] as $key => $custom) {
614 if (is_array($custom)) {
615 foreach ($custom as $fieldId => $value) {
616 $valid = CRM_Core_BAO_CustomValue::typecheck(CRM_Utils_Array::value('type', $value),
617 CRM_Utils_Array::value('value', $value)
618 );
619 if (!$valid && $value['is_required']) {
620 return civicrm_api3_create_error('Invalid value for custom field \'' .
621 CRM_Utils_Array::value('name', $custom) . '\''
622 );
623 }
624 if (CRM_Utils_Array::value('type', $custom) == 'Date') {
625 $params['custom'][$key][$fieldId]['value'] = str_replace('-', '', $params['custom'][$key][$fieldId]['value']);
626 }
627 }
628 }
629 }
630 }
631
632 return civicrm_api3_create_success(TRUE);
633 }
634
635 /**
636 * @deprecated - this is part of the import parser not the API & needs to be moved on out
637 *
638 * @param array $params
639 * @param $onDuplicate
640 *
641 * @return array|bool
642 * <type>
643 */
644 function _civicrm_api3_deprecated_create_participant_formatted($params, $onDuplicate) {
645 require_once 'CRM/Event/Import/Parser.php';
646 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
647 CRM_Core_Error::reset();
648 $error = _civicrm_api3_deprecated_participant_check_params($params, TRUE);
649 if (civicrm_error($error)) {
650 return $error;
651 }
652 }
653 require_once "api/v3/Participant.php";
654 return civicrm_api3_participant_create($params);
655 }
656
657 /**
658 *
659 * @param array $params
660 *
661 * @param bool $checkDuplicate
662 *
663 * @return array|bool
664 * <type>
665 */
666 function _civicrm_api3_deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
667
668 // check if participant id is valid or not
669 if (!empty($params['id'])) {
670 $participant = new CRM_Event_BAO_Participant();
671 $participant->id = $params['id'];
672 if (!$participant->find(TRUE)) {
673 return civicrm_api3_create_error(ts('Participant id is not valid'));
674 }
675 }
676 require_once 'CRM/Contact/BAO/Contact.php';
677 // check if contact id is valid or not
678 if (!empty($params['contact_id'])) {
679 $contact = new CRM_Contact_BAO_Contact();
680 $contact->id = $params['contact_id'];
681 if (!$contact->find(TRUE)) {
682 return civicrm_api3_create_error(ts('Contact id is not valid'));
683 }
684 }
685
686 // check that event id is not an template
687 if (!empty($params['event_id'])) {
688 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
689 if (!empty($isTemplate)) {
690 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
691 }
692 }
693
694 $result = [];
695 if ($checkDuplicate) {
696 if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
697 $participantID = array_pop($result);
698
699 $error = CRM_Core_Error::createError("Found matching participant record.",
700 CRM_Core_Error::DUPLICATE_PARTICIPANT,
701 'Fatal', $participantID
702 );
703
704 return civicrm_api3_create_error($error->pop(),
705 [
706 'contactID' => $params['contact_id'],
707 'participantID' => $participantID,
708 ]
709 );
710 }
711 }
712 return TRUE;
713 }
714
715 /**
716 * @param array $params
717 * @param bool $dupeCheck
718 * @param int $dedupeRuleGroupID
719 *
720 * @return array|null
721 */
722 function _civicrm_api3_deprecated_contact_check_params(
723 &$params,
724 $dupeCheck = TRUE,
725 $dedupeRuleGroupID = NULL) {
726
727 $requiredCheck = TRUE;
728
729 if (isset($params['id']) && is_numeric($params['id'])) {
730 $requiredCheck = FALSE;
731 }
732 if ($requiredCheck) {
733 if (isset($params['id'])) {
734 $required = ['Individual', 'Household', 'Organization'];
735 }
736 $required = [
737 'Individual' => [
738 ['first_name', 'last_name'],
739 'email',
740 ],
741 'Household' => [
742 'household_name',
743 ],
744 'Organization' => [
745 'organization_name',
746 ],
747 ];
748
749 // contact_type has a limited number of valid values
750 if (empty($params['contact_type'])) {
751 return civicrm_api3_create_error("No Contact Type");
752 }
753 $fields = $required[$params['contact_type']] ?? NULL;
754 if ($fields == NULL) {
755 return civicrm_api3_create_error("Invalid Contact Type: {$params['contact_type']}");
756 }
757
758 if ($csType = CRM_Utils_Array::value('contact_sub_type', $params)) {
759 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($csType, $params['contact_type']))) {
760 return civicrm_api3_create_error("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $csType));
761 }
762 }
763
764 if (empty($params['contact_id']) && !empty($params['id'])) {
765 $valid = FALSE;
766 $error = '';
767 foreach ($fields as $field) {
768 if (is_array($field)) {
769 $valid = TRUE;
770 foreach ($field as $element) {
771 if (empty($params[$element])) {
772 $valid = FALSE;
773 $error .= $element;
774 break;
775 }
776 }
777 }
778 else {
779 if (!empty($params[$field])) {
780 $valid = TRUE;
781 }
782 }
783 if ($valid) {
784 break;
785 }
786 }
787
788 if (!$valid) {
789 return civicrm_api3_create_error("Required fields not found for {$params['contact_type']} : $error");
790 }
791 }
792 }
793
794 if ($dupeCheck) {
795 // @todo switch to using api version
796 // $dupes = civicrm_api3('Contact', 'duplicatecheck', (array('match' => $params, 'dedupe_rule_id' => $dedupeRuleGroupID)));
797 // $ids = $dupes['count'] ? implode(',', array_keys($dupes['values'])) : NULL;
798 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised', [], CRM_Utils_Array::value('check_permissions', $params), $dedupeRuleGroupID);
799 if ($ids != NULL) {
800 $error = CRM_Core_Error::createError("Found matching contacts: " . implode(',', $ids),
801 CRM_Core_Error::DUPLICATE_CONTACT,
802 'Fatal', $ids
803 );
804 return civicrm_api3_create_error($error->pop());
805 }
806 }
807
808 // check for organisations with same name
809 if (!empty($params['current_employer'])) {
810 $organizationParams = ['organization_name' => $params['current_employer']];
811 $dupeIds = CRM_Contact_BAO_Contact::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', [], FALSE);
812
813 // check for mismatch employer name and id
814 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)
815 ) {
816 return civicrm_api3_create_error('Employer name and Employer id Mismatch');
817 }
818
819 // show error if multiple organisation with same name exist
820 if (empty($params['employer_id']) && (count($dupeIds) > 1)
821 ) {
822 return civicrm_api3_create_error('Found more than one Organisation with same Name.');
823 }
824 }
825
826 return NULL;
827 }
828
829 /**
830 * @param $result
831 * @param int $activityTypeID
832 *
833 * @return array
834 * <type> $params
835 */
836 function _civicrm_api3_deprecated_activity_buildmailparams($result, $activityTypeID) {
837 // get ready for collecting data about activity to be created
838 $params = [];
839
840 $params['activity_type_id'] = $activityTypeID;
841
842 $params['status_id'] = 'Completed';
843 if (!empty($result['from']['id'])) {
844 $params['source_contact_id'] = $params['assignee_contact_id'] = $result['from']['id'];
845 }
846 $params['target_contact_id'] = [];
847 $keys = ['to', 'cc', 'bcc'];
848 foreach ($keys as $key) {
849 if (is_array($result[$key])) {
850 foreach ($result[$key] as $key => $keyValue) {
851 if (!empty($keyValue['id'])) {
852 $params['target_contact_id'][] = $keyValue['id'];
853 }
854 }
855 }
856 }
857 $params['subject'] = $result['subject'];
858 $params['activity_date_time'] = $result['date'];
859 $params['details'] = $result['body'];
860
861 $numAttachments = Civi::settings()->get('max_attachments_backend') ?? CRM_Core_BAO_File::DEFAULT_MAX_ATTACHMENTS_BACKEND;
862 for ($i = 1; $i <= $numAttachments; $i++) {
863 if (isset($result["attachFile_$i"])) {
864 $params["attachFile_$i"] = $result["attachFile_$i"];
865 }
866 else {
867 // No point looping 100 times if there's only one attachment
868 break;
869 }
870 }
871
872 return $params;
873 }