Merge pull request #18360 from colemanw/fixMultiInProfile
[civicrm-core.git] / CRM / Contact / BAO / Contact.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 class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact {
18
19 /**
20 * SQL function used to format the phone_numeric field via trigger.
21 *
22 * @see self::triggerInfo()
23 *
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
26 */
27 const DROP_STRIP_FUNCTION_43 = "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
28
29 const CREATE_STRIP_FUNCTION_43 = "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255))
31 RETURNS VARCHAR(255)
32 DETERMINISTIC
33 NO SQL
34 BEGIN
35 DECLARE output VARCHAR(255) DEFAULT '';
36 DECLARE iterator INT DEFAULT 1;
37 WHILE iterator < (LENGTH(input) + 1) DO
38 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
39 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
40 END IF;
41 SET iterator = iterator + 1;
42 END WHILE;
43 RETURN output;
44 END";
45
46 /**
47 * The types of communication preferences.
48 *
49 * @var array
50 */
51 public static $_commPrefs = [
52 'do_not_phone',
53 'do_not_email',
54 'do_not_mail',
55 'do_not_sms',
56 'do_not_trade',
57 ];
58
59 /**
60 * Types of greetings.
61 *
62 * @var array
63 */
64 public static $_greetingTypes = [
65 'addressee',
66 'email_greeting',
67 'postal_greeting',
68 ];
69
70 /**
71 * Static field for all the contact information that we can potentially import.
72 *
73 * @var array
74 */
75 public static $_importableFields = [];
76
77 /**
78 * Static field for all the contact information that we can potentially export.
79 *
80 * @var array
81 */
82 public static $_exportableFields = NULL;
83
84 /**
85 * Class constructor.
86 */
87 public function __construct() {
88 parent::__construct();
89 }
90
91 /**
92 * Takes an associative array and creates a contact object.
93 *
94 * The function extracts all the params it needs to initialize the create a
95 * contact object. the params array could contain additional unused name/value
96 * pairs
97 *
98 * @param array $params
99 * (reference) an assoc array of name/value pairs.
100 *
101 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
102 * Created or updated contact object or error object.
103 * (error objects are being phased out in favour of exceptions)
104 * @throws \CRM_Core_Exception
105 */
106 public static function add(&$params) {
107 $contact = new CRM_Contact_DAO_Contact();
108 $contactID = $params['contact_id'] ?? NULL;
109 if (empty($params)) {
110 return NULL;
111 }
112
113 // Fix for validate contact sub type CRM-5143.
114 if (isset($params['contact_sub_type'])) {
115 if (empty($params['contact_sub_type'])) {
116 $params['contact_sub_type'] = 'null';
117 }
118 elseif ($params['contact_sub_type'] !== 'null') {
119 if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'],
120 $params['contact_type'], TRUE
121 )
122 ) {
123 // we'll need to fix tests to handle this
124 // CRM-7925
125 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
126 }
127 $params['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
128 }
129 }
130
131 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
132 CRM_Utils_Array::formatArrayKeys($params['preferred_communication_method']);
133 $contact->preferred_communication_method = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
134 unset($params['preferred_communication_method']);
135 }
136
137 $defaults = ['source' => $params['contact_source'] ?? NULL];
138 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
139 $defaults['display_name'] = $params['organization_name'];
140 $defaults['sort_name'] = $params['organization_name'];
141 }
142 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
143 $defaults['display_name'] = $params['household_name'];
144 $defaults['sort_name'] = $params['household_name'];
145 }
146 $params = array_merge($defaults, $params);
147
148 $allNull = $contact->copyValues($params);
149
150 $contact->id = $contactID;
151
152 if ($contact->contact_type === 'Individual') {
153 $allNull = FALSE;
154 // @todo allow the lines below to be overridden by input or hooks & add tests,
155 // as has been done for households and organizations.
156 // Format individual fields.
157 CRM_Contact_BAO_Individual::format($params, $contact);
158 }
159
160 if (strlen($contact->display_name) > 128) {
161 $contact->display_name = substr($contact->display_name, 0, 128);
162 }
163 if (strlen($contact->sort_name) > 128) {
164 $contact->sort_name = substr($contact->sort_name, 0, 128);
165 }
166
167 $privacy = $params['privacy'] ?? NULL;
168 if ($privacy && is_array($privacy)) {
169 $allNull = FALSE;
170 foreach (self::$_commPrefs as $name) {
171 $contact->$name = $privacy[$name] ?? FALSE;
172 }
173 }
174
175 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
176 // @todo - does this mean we can remove this block?
177 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
178 if ((!isset($contact->hash) || !$contact->hash) && !$contact->id) {
179 $allNull = FALSE;
180 $contact->hash = md5(uniqid(rand(), TRUE));
181 }
182
183 // Even if we don't need $employerId, it's important to call getFieldValue() before
184 // the contact is saved because we want the existing value to be cached.
185 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
186 $employerId = (!$contactID || $contact->contact_type !== 'Individual') ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
187
188 if (!$allNull) {
189 $contact->save();
190
191 CRM_Core_BAO_Log::register($contact->id,
192 'civicrm_contact',
193 $contact->id
194 );
195 }
196
197 if ($contact->contact_type === 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
198 // Create current employer.
199 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : $params['current_employer'] ?? NULL;
200
201 $newContact = empty($params['contact_id']);
202 if ($newEmployer) {
203 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
204 }
205 elseif ($employerId) {
206 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
207 }
208 }
209
210 // Update cached employer name if the name of an existing organization is being updated.
211 if ($contact->contact_type === 'Organization' && !empty($params['organization_name']) && $contactID) {
212 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
213 }
214
215 return $contact;
216 }
217
218 /**
219 * Create contact.
220 *
221 * takes an associative array and creates a contact object and all the associated
222 * derived objects (i.e. individual, location, email, phone etc)
223 *
224 * This function is invoked from within the web form layer and also from the api layer
225 *
226 * @param array $params
227 * (reference ) an assoc array of name/value pairs.
228 * @param bool $fixAddress
229 * If we need to fix address.
230 * @param bool $invokeHooks
231 * If we need to invoke hooks.
232 *
233 * @param bool $skipDelete
234 * Unclear parameter, passed to website create
235 *
236 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
237 * Created or updated contribution object. We are deprecating returning an error in
238 * favour of exceptions
239 *
240 * @throws \CRM_Core_Exception
241 * @throws \CiviCRM_API3_Exception
242 * @throws \Civi\API\Exception\UnauthorizedException
243 */
244 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
245 $contact = NULL;
246 if (empty($params['contact_type']) && empty($params['contact_id'])) {
247 return $contact;
248 }
249
250 $isEdit = !empty($params['contact_id']);
251
252 if ($isEdit && empty($params['contact_type'])) {
253 $params['contact_type'] = self::getContactType($params['contact_id']);
254 }
255
256 if (!empty($params['check_permissions']) && isset($params['api_key'])
257 && !CRM_Core_Permission::check([['edit api keys', 'administer CiviCRM']])
258 && !($isEdit && CRM_Core_Permission::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session::getLoggedInContactID())
259 ) {
260 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify api key');
261 }
262
263 if ($invokeHooks) {
264 if (!empty($params['contact_id'])) {
265 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
266 }
267 else {
268 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
269 }
270 }
271
272 self::ensureGreetingParamsAreSet($params);
273
274 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
275 if (empty($params['contact_id'])) {
276 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
277 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
278 $params['preferred_language'] = $language;
279 }
280
281 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
282 if (empty($params['communication_style_id'])) {
283 $defaultCommunicationStyleId = CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
284 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
285 }
286 }
287
288 $transaction = new CRM_Core_Transaction();
289
290 $contact = self::add($params);
291
292 $params['contact_id'] = $contact->id;
293
294 if (Civi::settings()->get('is_enabled')) {
295 // Enabling multisite causes the contact to be added to the domain group.
296 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
297 if (!empty($domainGroupID)) {
298 if (!empty($params['group']) && is_array($params['group'])) {
299 $params['group'][$domainGroupID] = 1;
300 }
301 else {
302 $params['group'] = [$domainGroupID => 1];
303 }
304 }
305 }
306
307 if (!empty($params['group'])) {
308 $contactIds = [$params['contact_id']];
309 foreach ($params['group'] as $groupId => $flag) {
310 if ($flag == 1) {
311 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
312 }
313 elseif ($flag == -1) {
314 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
315 }
316 }
317 }
318
319 // Add location Block data.
320 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
321 foreach ($blocks as $name => $value) {
322 $contact->$name = $value;
323 }
324 if (!empty($params['updateBlankLocInfo'])) {
325 $skipDelete = TRUE;
326 }
327
328 if (isset($params['website'])) {
329 CRM_Core_BAO_Website::process($params['website'], $contact->id, $skipDelete);
330 }
331
332 $userID = CRM_Core_Session::singleton()->get('userID');
333 // add notes
334 if (!empty($params['note'])) {
335 if (is_array($params['note'])) {
336 foreach ($params['note'] as $note) {
337 $contactId = $contact->id;
338 if (isset($note['contact_id'])) {
339 $contactId = $note['contact_id'];
340 }
341 //if logged in user, overwrite contactId
342 if ($userID) {
343 $contactId = $userID;
344 }
345
346 $noteParams = [
347 'entity_id' => $contact->id,
348 'entity_table' => 'civicrm_contact',
349 'note' => $note['note'],
350 'subject' => $note['subject'] ?? NULL,
351 'contact_id' => $contactId,
352 ];
353 CRM_Core_BAO_Note::add($noteParams);
354 }
355 }
356 else {
357 $contactId = $contact->id;
358 //if logged in user, overwrite contactId
359 if ($userID) {
360 $contactId = $userID;
361 }
362
363 $noteParams = [
364 'entity_id' => $contact->id,
365 'entity_table' => 'civicrm_contact',
366 'note' => $params['note'],
367 'subject' => $params['subject'] ?? NULL,
368 'contact_id' => $contactId,
369 ];
370 CRM_Core_BAO_Note::add($noteParams);
371 }
372 }
373
374 if (!empty($params['custom']) &&
375 is_array($params['custom'])
376 ) {
377 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
378 }
379
380 $transaction->commit();
381
382 // CRM-6367: fetch the right label for contact type’s display
383 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
384 'CRM_Contact_DAO_ContactType',
385 $contact->contact_type,
386 'label',
387 'name'
388 );
389
390 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
391
392 if ($invokeHooks) {
393 if ($isEdit) {
394 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
395 }
396 else {
397 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
398 }
399 }
400
401 // In order to prevent a series of expensive queries in intensive batch processing
402 // api calls may pass in skip_greeting_processing, probably doing it later via the
403 // scheduled job. CRM-21551
404 if (empty($params['skip_greeting_processing'])) {
405 self::processGreetings($contact);
406 }
407
408 if (!empty($params['check_permissions'])) {
409 $contacts = [&$contact];
410 self::unsetProtectedFields($contacts);
411 }
412
413 if (!empty($params['is_deceased'])) {
414 // Edit Membership Status
415 $deceasedParams = [
416 'contact_id' => $contact->id,
417 'is_deceased' => $params['is_deceased'],
418 'deceased_date' => $params['deceased_date'] ?? NULL,
419 ];
420 CRM_Member_BAO_Membership::updateMembershipStatus($deceasedParams, $params['contact_type']);
421 }
422
423 return $contact;
424 }
425
426 /**
427 * Format the output of the create contact function
428 *
429 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
430 */
431 public static function unsetProtectedFields(&$contacts) {
432 if (!CRM_Core_Permission::check([['edit api keys', 'administer CiviCRM']])) {
433 $currentUser = CRM_Core_Session::getLoggedInContactID();
434 $editOwn = $currentUser && CRM_Core_Permission::check('edit own api keys');
435 foreach ($contacts as &$contact) {
436 $cid = is_object($contact) ? $contact->id : $contact['id'] ?? NULL;
437 if (!($editOwn && $cid == $currentUser)) {
438 if (is_object($contact)) {
439 unset($contact->api_key);
440 }
441 else {
442 unset($contact['api_key']);
443 }
444 }
445 }
446 }
447 }
448
449 /**
450 * Ensure greeting parameters are set.
451 *
452 * By always populating greetings here we can be sure they are set if required & avoid a call later.
453 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
454 *
455 * @param array $params
456 *
457 * @throws \CiviCRM_API3_Exception
458 */
459 public static function ensureGreetingParamsAreSet(&$params) {
460 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
461 $missingGreetingParams = [];
462
463 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
464 if (empty($params[$greetingParam])) {
465 $missingGreetingParams[$greetingIndex] = $greetingParam;
466 }
467 }
468
469 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
470 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
471 'id' => $params['contact_id'],
472 'return' => array_keys($missingGreetingParams),
473 ]);
474
475 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
476 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
477 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
478 }
479 }
480 // Filter out other fields.
481 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
482 $params = array_merge($params, $savedGreetings);
483 }
484 else {
485 foreach ($missingGreetingParams as $greetingName => $greeting) {
486 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greetingName);
487 }
488 }
489
490 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
491 if ($params[$greetingParam] === 'null') {
492 // If we are setting it to null then null out the display field.
493 $params[$greetingIndex . '_display'] = 'null';
494 }
495 }
496 }
497
498 /**
499 * Get the display name and image of a contact.
500 *
501 * @param int $id
502 * The contactId.
503 *
504 * @param bool $includeTypeInReturnParameters
505 * Should type be part of the returned array?
506 *
507 * @return array
508 * the displayName and contactImage for this contact
509 */
510 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
511 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
512 $sql = "
513 SELECT civicrm_contact.*,
514 civicrm_email.email as email
515 FROM civicrm_contact
516 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
517 AND civicrm_email.is_primary = 1
518 WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
519 $dao = new CRM_Core_DAO();
520 $dao->query($sql);
521 if ($dao->fetch()) {
522 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
523 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
524 );
525 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
526 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
527 );
528
529 // use email if display_name is empty
530 if (empty($dao->display_name)) {
531 $displayName = $dao->email;
532 }
533 else {
534 $displayName = $dao->display_name;
535 }
536
537 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
538
539 return $includeTypeInReturnParameters ? [
540 $displayName,
541 $image,
542 $dao->contact_type,
543 $dao->contact_sub_type,
544 $imageUrl,
545 ] : [$displayName, $image, $imageUrl];
546 }
547 return NULL;
548 }
549
550 /**
551 * Add billing fields to the params if appropriate.
552 *
553 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
554 * don't then we should set the name fields to the billing fields AND add the preserveDBName
555 * parameter (which will tell the BAO only to set those fields if none already exist.
556 *
557 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
558 * matching is best done by hipsters.
559 *
560 * @param array $params
561 *
562 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
563 */
564 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
565 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
566 foreach ($nameFields as $field) {
567 if (!empty($params[$field])) {
568 return;
569 }
570 }
571 // There are only 3 - we can iterate through them twice :-)
572 foreach ($nameFields as $field) {
573 if (!empty($params['billing_' . $field])) {
574 $params[$field] = $params['billing_' . $field];
575 }
576 $params['preserveDBName'] = TRUE;
577 }
578
579 }
580
581 /**
582 * Resolve a state province string (UT or Utah) to an ID.
583 *
584 * If country has been passed in we should select a state belonging to that country.
585 *
586 * Alternatively we should choose from enabled countries, prioritising the default country.
587 *
588 * @param array $values
589 * @param int|null $countryID
590 *
591 * @return int|null
592 *
593 * @throws \CRM_Core_Exception
594 */
595 protected static function resolveStateProvinceID($values, $countryID) {
596
597 if ($countryID) {
598 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID);
599 if (CRM_Utils_Array::lookupValue($values,
600 'state_province',
601 $stateProvinceList,
602 TRUE
603 )) {
604 return $values['state_province_id'];
605 }
606 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID, 'abbreviation');
607 if (CRM_Utils_Array::lookupValue($values,
608 'state_province',
609 $stateProvinceList,
610 TRUE
611 )) {
612 return $values['state_province_id'];
613 }
614 return NULL;
615 }
616 else {
617 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
618 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
619 // prefer matching country..
620 $stateProvinceList = CRM_Core_BAO_Address::buildOptions('state_province_id', NULL, ['country_id' => Civi::settings()->get('defaultContactCountry')]);
621 if (CRM_Utils_Array::lookupValue($values,
622 'state_province',
623 $stateProvinceList,
624 TRUE
625 )) {
626 return $values['state_province_id'];
627 }
628
629 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
630 if (CRM_Utils_Array::lookupValue($values,
631 'state_province',
632 $stateProvinceList,
633 TRUE
634 )) {
635 return $values['state_province_id'];
636 }
637
638 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviationForDefaultCountry();
639 if (CRM_Utils_Array::lookupValue($values,
640 'state_province',
641 $stateProvinceList,
642 TRUE
643 )) {
644 return $values['state_province_id'];
645 }
646 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
647 if (CRM_Utils_Array::lookupValue($values,
648 'state_province',
649 $stateProvinceList,
650 TRUE
651 )) {
652 return $values['state_province_id'];
653 }
654 }
655
656 return NULL;
657 }
658
659 /**
660 * Get the relevant location entity for the array key.
661 *
662 * Based on the field name we determine which location entity
663 * we are dealing with. Apart from a few specific ones they
664 * are mostly 'address' (the default).
665 *
666 * @param string $fieldName
667 *
668 * @return string
669 */
670 protected static function getLocationEntityForKey($fieldName) {
671 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
672 return $fieldName;
673 }
674 if ($fieldName === 'phone_ext') {
675 return 'phone';
676 }
677 return 'address';
678 }
679
680 /**
681 * Soft delete a contact.
682 *
683 * Call this via the api, not directly.
684 *
685 * @param \CRM_Contact_BAO_Contact $contact
686 *
687 * @return bool
688 * @throws \CRM_Core_Exception
689 */
690 protected static function contactTrash($contact): bool {
691 $updateParams = [
692 'id' => $contact->id,
693 'is_deleted' => 1,
694 ];
695 CRM_Utils_Hook::pre('update', $contact->contact_type, $contact->id, $updateParams);
696
697 $params = [1 => [$contact->id, 'Integer']];
698 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
699 CRM_Core_DAO::executeQuery($query, $params);
700
701 $contact->copyValues($updateParams);
702 $contact->save();
703 CRM_Core_BAO_Log::register($contact->id, 'civicrm_contact', $contact->id);
704
705 CRM_Utils_Hook::post('update', $contact->contact_type, $contact->id, $contact);
706
707 return TRUE;
708 }
709
710 /**
711 * Create last viewed link to recently updated contact.
712 *
713 * @param array $crudLinkSpec
714 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
715 * - entity_table: string, eg "civicrm_contact"
716 * - entity_id: int
717 *
718 * @return array|NULL
719 * NULL if unavailable, or
720 * [path: string, query: string, title: string]
721 * @see CRM_Utils_System::createDefaultCrudLink
722 */
723 public function createDefaultCrudLink($crudLinkSpec) {
724 switch ($crudLinkSpec['action']) {
725 case CRM_Core_Action::VIEW:
726 $result = [
727 'title' => $this->display_name,
728 'path' => 'civicrm/contact/view',
729 'query' => [
730 'reset' => 1,
731 'cid' => $this->id,
732 ],
733 ];
734 return $result;
735
736 case CRM_Core_Action::UPDATE:
737 $result = [
738 'title' => $this->display_name,
739 'path' => 'civicrm/contact/add',
740 'query' => [
741 'reset' => 1,
742 'action' => 'update',
743 'cid' => $this->id,
744 ],
745 ];
746 return $result;
747 }
748 return NULL;
749 }
750
751 /**
752 * Get the values for pseudoconstants for name->value and reverse.
753 *
754 * @param array $defaults
755 * (reference) the default values, some of which need to be resolved.
756 * @param bool $reverse
757 * Always true as this function is only called from one place..
758 *
759 * @deprecated
760 *
761 * This is called specifically from the contact import parser & should be moved there
762 * as it is not truly a generic function.
763 *
764 */
765 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
766 // Hack for birth_date.
767 if (!empty($defaults['birth_date'])) {
768 if (is_array($defaults['birth_date'])) {
769 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
770 }
771 }
772
773 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
774 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
775 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
776 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
777
778 //lookup value of email/postal greeting, addressee, CRM-4575
779 foreach (self::$_greetingTypes as $greeting) {
780 $filterCondition = [
781 'contact_type' => $defaults['contact_type'] ?? NULL,
782 'greeting_type' => $greeting,
783 ];
784 CRM_Utils_Array::lookupValue($defaults, $greeting,
785 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
786 );
787 }
788
789 $blocks = ['address', 'im', 'phone'];
790 foreach ($blocks as $name) {
791 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
792 continue;
793 }
794 foreach ($defaults[$name] as $count => & $values) {
795
796 //get location type id.
797 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
798
799 if ($name == 'address') {
800 // FIXME: lookupValue doesn't work for vcard_name
801 if (!empty($values['location_type_id'])) {
802 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
803 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
804 }
805
806 if (!CRM_Utils_Array::lookupValue($values,
807 'country',
808 CRM_Core_PseudoConstant::country(),
809 $reverse
810 ) &&
811 $reverse
812 ) {
813 CRM_Utils_Array::lookupValue($values,
814 'country',
815 CRM_Core_PseudoConstant::countryIsoCode(),
816 $reverse
817 );
818 }
819 $stateProvinceID = self::resolveStateProvinceID($values, $values['country_id'] ?? NULL);
820 if ($stateProvinceID) {
821 $values['state_province_id'] = $stateProvinceID;
822 }
823
824 if (!empty($values['state_province_id'])) {
825 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
826 }
827 else {
828 $countyList = CRM_Core_PseudoConstant::county();
829 }
830 CRM_Utils_Array::lookupValue($values,
831 'county',
832 $countyList,
833 $reverse
834 );
835 }
836
837 if ($name == 'im') {
838 CRM_Utils_Array::lookupValue($values,
839 'provider',
840 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
841 $reverse
842 );
843 }
844
845 if ($name == 'phone') {
846 CRM_Utils_Array::lookupValue($values,
847 'phone_type',
848 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
849 $reverse
850 );
851 }
852
853 // Kill the reference.
854 unset($values);
855 }
856 }
857 }
858
859 /**
860 * Fetch object based on array of properties.
861 *
862 * @param array $params
863 * (reference ) an assoc array of name/value pairs.
864 * @param array $defaults
865 * (reference ) an assoc array to hold the name / value pairs.
866 * in a hierarchical manner
867 * @param bool $microformat
868 * For location in microformat.
869 *
870 * @return CRM_Contact_BAO_Contact
871 */
872 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
873 if (array_key_exists('contact_id', $params)) {
874 $params['id'] = $params['contact_id'];
875 }
876 elseif (array_key_exists('id', $params)) {
877 $params['contact_id'] = $params['id'];
878 }
879
880 $contact = self::getValues($params, $defaults);
881
882 unset($params['id']);
883
884 //get the block information for this contact
885 $entityBlock = ['contact_id' => $params['contact_id']];
886 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
887 $defaults = array_merge($defaults, $blocks);
888 foreach ($blocks as $block => $value) {
889 $contact->$block = $value;
890 }
891
892 if (!isset($params['noNotes'])) {
893 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
894 }
895
896 if (!isset($params['noRelationships'])) {
897 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
898 }
899
900 if (!isset($params['noGroups'])) {
901 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
902 }
903
904 if (!isset($params['noWebsite'])) {
905 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
906 }
907
908 return $contact;
909 }
910
911 /**
912 * Get the display name of a contact.
913 *
914 * @param int $id
915 * Id of the contact.
916 *
917 * @return null|string
918 * display name of the contact if found
919 */
920 public static function displayName($id) {
921 $displayName = NULL;
922 if ($id) {
923 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
924 }
925
926 return $displayName;
927 }
928
929 /**
930 * Delete a contact and all its associated records.
931 *
932 * @param int $id
933 * Id of the contact to delete.
934 * @param bool $restore
935 * Whether to actually restore, not delete.
936 * @param bool $skipUndelete
937 * Whether to force contact delete or not.
938 * @param bool $checkPermissions
939 *
940 * @return bool
941 * Was contact deleted?
942 *
943 * @throws \CRM_Core_Exception
944 * @throws \CiviCRM_API3_Exception
945 */
946 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
947
948 if (!$id || !is_numeric($id)) {
949 CRM_Core_Error::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
950 return FALSE;
951 }
952 // If trash is disabled in system settings then we always skip
953 if (!Civi::settings()->get('contact_undelete')) {
954 $skipUndelete = TRUE;
955 }
956
957 // make sure we have edit permission for this contact
958 // before we delete
959 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
960 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
961 ) {
962 return FALSE;
963 }
964
965 // CRM-12929
966 // Restrict contact to be delete if contact has financial trxns
967 $error = NULL;
968 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent([$id], $error)) {
969 return FALSE;
970 }
971
972 // make sure this contact_id does not have any membership types
973 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
974 $id,
975 'id',
976 'member_of_contact_id'
977 );
978 if ($membershipTypeID) {
979 return FALSE;
980 }
981
982 $contact = new CRM_Contact_DAO_Contact();
983 $contact->id = $id;
984 if (!$contact->find(TRUE)) {
985 return FALSE;
986 }
987
988 $contactType = $contact->contact_type;
989 if ($restore) {
990 // @todo deprecate calling contactDelete with the intention to restore.
991 $updateParams = [
992 'id' => $contact->id,
993 'is_deleted' => FALSE,
994 ];
995 self::create($updateParams);
996 return TRUE;
997 }
998
999 // start a new transaction
1000 $transaction = new CRM_Core_Transaction();
1001
1002 if ($skipUndelete) {
1003 $hookParams = ['check_permissions' => $checkPermissions];
1004 CRM_Utils_Hook::pre('delete', $contactType, $id, $hookParams);
1005
1006 //delete billing address if exists.
1007 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
1008
1009 // delete the log entries since we dont have triggers enabled as yet
1010 $logDAO = new CRM_Core_DAO_Log();
1011 $logDAO->entity_table = 'civicrm_contact';
1012 $logDAO->entity_id = $id;
1013 $logDAO->delete();
1014
1015 // delete contact participants CRM-12155
1016 CRM_Event_BAO_Participant::deleteContactParticipant($id);
1017
1018 // delete contact contributions CRM-12155
1019 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
1020
1021 // do activity cleanup, CRM-5604
1022 CRM_Activity_BAO_Activity::cleanupActivity($id);
1023
1024 // delete all notes related to contact
1025 CRM_Core_BAO_Note::cleanContactNotes($id);
1026
1027 // delete cases related to contact
1028 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
1029 if (!empty($contactCases)) {
1030 foreach ($contactCases as $caseId) {
1031 //check if case is associate with other contact or not.
1032 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
1033 if (count($caseContactId) <= 1) {
1034 CRM_Case_BAO_Case::deleteCase($caseId);
1035 }
1036 }
1037 }
1038
1039 $contact->delete();
1040 }
1041 else {
1042 self::contactTrash($contact);
1043 }
1044 // currently we only clear employer cache.
1045 // we are now deleting inherited membership if any.
1046 if ($contact->contact_type == 'Organization') {
1047 $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE;
1048 $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id);
1049 if (!empty($relationshipDtls)) {
1050 foreach ($relationshipDtls as $rId => $details) {
1051 CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action);
1052 }
1053 }
1054 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
1055 }
1056
1057 //delete the contact id from recently view
1058 CRM_Utils_Recent::delContact($id);
1059 self::updateContactCache($id, empty($restore));
1060
1061 // delete any prevnext/dupe cache entry
1062 // These two calls are redundant in default deployments, but they're
1063 // meaningful if "prevnext" is memory-backed.
1064 Civi::service('prevnext')->deleteItem($id);
1065 CRM_Core_BAO_PrevNextCache::deleteItem($id);
1066
1067 $transaction->commit();
1068
1069 if ($skipUndelete) {
1070 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
1071 }
1072
1073 return TRUE;
1074 }
1075
1076 /**
1077 * Action to update any caches relating to a recently update contact.
1078 *
1079 * I was going to call this from delete as well as from create to ensure the delete is being
1080 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1081 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1082 * where the call involved a subquery that was locking the table.
1083 *
1084 * @param int $contactID
1085 * @param bool $isTrashed
1086 */
1087 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1088
1089 if ($isTrashed) {
1090 CRM_Contact_BAO_GroupContactCache::removeContact($contactID);
1091 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1092 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1093 // but this should not cause any change as long as contacts are not being trashed outside the
1094 // main functions for that.
1095 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1096 }
1097 else {
1098 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
1099 }
1100 }
1101
1102 /**
1103 * Delete the image of a contact.
1104 *
1105 * @param int $id
1106 * Id of the contact.
1107 *
1108 * @return bool
1109 * Was contact image deleted?
1110 */
1111 public static function deleteContactImage($id) {
1112 if (!$id) {
1113 return FALSE;
1114 }
1115
1116 $contact = new self();
1117 $contact->id = $id;
1118 $contact->image_URL = 'null';
1119 $contact->save();
1120
1121 return TRUE;
1122 }
1123
1124 /**
1125 * Return proportional height and width of the image.
1126 *
1127 * @param int $imageWidth
1128 * Width of image.
1129 *
1130 * @param int $imageHeight
1131 * Height of image.
1132 *
1133 * @return array
1134 * Thumb dimension of image
1135 */
1136 public static function getThumbSize($imageWidth, $imageHeight) {
1137 $thumbWidth = 100;
1138 if ($imageWidth && $imageHeight) {
1139 $imageRatio = $imageWidth / $imageHeight;
1140 }
1141 else {
1142 $imageRatio = 1;
1143 }
1144 if ($imageRatio > 1) {
1145 $imageThumbWidth = $thumbWidth;
1146 $imageThumbHeight = round($thumbWidth / $imageRatio);
1147 }
1148 else {
1149 $imageThumbHeight = $thumbWidth;
1150 $imageThumbWidth = round($thumbWidth * $imageRatio);
1151 }
1152
1153 return [$imageThumbWidth, $imageThumbHeight];
1154 }
1155
1156 /**
1157 * Validate type of contact image.
1158 *
1159 * @param array $params
1160 * @param string $imageIndex
1161 * Index of image field.
1162 * @param string $statusMsg
1163 * Status message to be set after operation.
1164 * @param string $opType
1165 * Type of operation like fatal, bounce etc.
1166 *
1167 * @return bool
1168 * true if valid image extension
1169 */
1170 public static function processImageParams(
1171 &$params,
1172 $imageIndex = 'image_URL',
1173 $statusMsg = NULL,
1174 $opType = 'status'
1175 ) {
1176 $mimeType = [
1177 'image/jpeg',
1178 'image/jpg',
1179 'image/png',
1180 'image/bmp',
1181 'image/p-jpeg',
1182 'image/gif',
1183 'image/x-png',
1184 ];
1185
1186 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1187 $photo = basename($params[$imageIndex]['name']);
1188 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1189 return TRUE;
1190 }
1191 else {
1192 unset($params[$imageIndex]);
1193 if (!$statusMsg) {
1194 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1195 }
1196 if ($opType == 'status') {
1197 CRM_Core_Session::setStatus($statusMsg, ts('Error'), 'error');
1198 }
1199 // FIXME: additional support for fatal, bounce etc could be added.
1200 return FALSE;
1201 }
1202 }
1203
1204 /**
1205 * Extract contact id from url for deleting contact image.
1206 */
1207 public static function processImage() {
1208
1209 $action = CRM_Utils_Request::retrieve('action', 'String');
1210 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
1211 // retrieve contact id in case of Profile context
1212 $id = CRM_Utils_Request::retrieve('id', 'Positive');
1213 $cid = $cid ? $cid : $id;
1214 if ($action & CRM_Core_Action::DELETE) {
1215 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
1216 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1217 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1218 $session = CRM_Core_Session::singleton();
1219 $toUrl = $session->popUserContext();
1220 CRM_Utils_System::redirect($toUrl);
1221 }
1222 }
1223 }
1224
1225 /**
1226 * Function to set is_delete true or restore deleted contact.
1227 *
1228 * @param CRM_Contact_DAO_Contact $contact
1229 * Contact DAO object.
1230 * @param bool $restore
1231 * True to set the is_delete = 1 else false to restore deleted contact,
1232 * i.e. is_delete = 0
1233 *
1234 * @deprecated
1235 *
1236 * @return bool
1237 * @throws \CRM_Core_Exception
1238 */
1239 public static function contactTrashRestore($contact, $restore = FALSE) {
1240 CRM_Core_Error::deprecatedFunctionWarning('Use the api');
1241
1242 if ($restore) {
1243 CRM_Core_Error::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1244 // @todo deprecate calling contactDelete with the intention to restore.
1245 $updateParams = [
1246 'id' => $contact->id,
1247 'is_deleted' => FALSE,
1248 ];
1249 self::create($updateParams);
1250 return TRUE;
1251 }
1252 return self::contactTrash($contact);
1253 }
1254
1255 /**
1256 * Get contact type for a contact.
1257 *
1258 * @param int $id
1259 * Id of the contact whose contact type is needed.
1260 *
1261 * @return string
1262 * contact_type if $id found else null ""
1263 */
1264 public static function getContactType($id) {
1265 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1266 }
1267
1268 /**
1269 * Get contact sub type for a contact.
1270 *
1271 * @param int $id
1272 * Id of the contact whose contact sub type is needed.
1273 *
1274 * @param string $implodeDelimiter
1275 *
1276 * @return string
1277 * contact_sub_type if $id found else null ""
1278 */
1279 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1280 $subtype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1281 if (!$subtype) {
1282 return $implodeDelimiter ? NULL : [];
1283 }
1284
1285 $subtype = CRM_Utils_Array::explodePadded($subtype);
1286
1287 if ($implodeDelimiter) {
1288 $subtype = implode($implodeDelimiter, $subtype);
1289 }
1290 return $subtype;
1291 }
1292
1293 /**
1294 * Get pair of contact-type and sub-type for a contact.
1295 *
1296 * @param int $id
1297 * Id of the contact whose contact sub/contact type is needed.
1298 *
1299 * @return array
1300 */
1301 public static function getContactTypes($id) {
1302 $params = ['id' => $id];
1303 $details = [];
1304 $contact = CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact',
1305 $params,
1306 $details,
1307 ['contact_type', 'contact_sub_type']
1308 );
1309
1310 if ($contact) {
1311 $contactTypes = [];
1312 if ($contact->contact_sub_type) {
1313 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
1314 }
1315 array_unshift($contactTypes, $contact->contact_type);
1316
1317 return $contactTypes;
1318 }
1319 else {
1320 throw new CRM_Core_Exception();
1321 }
1322 }
1323
1324 /**
1325 * Combine all the importable fields from the lower levels object.
1326 *
1327 * The ordering is important, since currently we do not have a weight
1328 * scheme. Adding weight is super important
1329 *
1330 * @param int|string $contactType contact Type
1331 * @param bool $status
1332 * Status is used to manipulate first title.
1333 * @param bool $showAll
1334 * If true returns all fields (includes disabled fields).
1335 * @param bool $isProfile
1336 * If its profile mode.
1337 * @param bool $checkPermission
1338 * If false, do not include permissioning clause (for custom data).
1339 *
1340 * @param bool $withMultiCustomFields
1341 *
1342 * @return array
1343 * array of importable Fields
1344 */
1345 public static function importableFields(
1346 $contactType = 'Individual',
1347 $status = FALSE,
1348 $showAll = FALSE,
1349 $isProfile = FALSE,
1350 $checkPermission = TRUE,
1351 $withMultiCustomFields = FALSE
1352 ) {
1353 if (empty($contactType)) {
1354 $contactType = 'All';
1355 }
1356
1357 $cacheKeyString = "importableFields $contactType";
1358 $cacheKeyString .= $status ? '_1' : '_0';
1359 $cacheKeyString .= $showAll ? '_1' : '_0';
1360 $cacheKeyString .= $isProfile ? '_1' : '_0';
1361 $cacheKeyString .= $checkPermission ? '_1' : '_0';
1362 $cacheKeyString .= '_' . CRM_Core_Config::domainID() . '_';
1363
1364 $fields = self::$_importableFields[$cacheKeyString] ?? Civi::cache('fields')->get($cacheKeyString);
1365
1366 if (!$fields) {
1367 $fields = CRM_Contact_DAO_Contact::import();
1368
1369 // get the fields thar are meant for contact types
1370 if (in_array($contactType, [
1371 'Individual',
1372 'Household',
1373 'Organization',
1374 'All',
1375 ])) {
1376 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1377 }
1378
1379 $locationFields = array_merge(CRM_Core_DAO_Address::import(),
1380 CRM_Core_DAO_Phone::import(),
1381 CRM_Core_DAO_Email::import(),
1382 CRM_Core_DAO_IM::import(TRUE),
1383 CRM_Core_DAO_OpenID::import()
1384 );
1385
1386 $locationFields = array_merge($locationFields,
1387 CRM_Core_BAO_CustomField::getFieldsForImport('Address',
1388 FALSE,
1389 FALSE,
1390 FALSE,
1391 FALSE
1392 )
1393 );
1394
1395 foreach ($locationFields as $key => $field) {
1396 $locationFields[$key]['hasLocationType'] = TRUE;
1397 }
1398
1399 $fields = array_merge($fields, $locationFields);
1400
1401 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1402 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
1403
1404 //website fields
1405 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
1406 $fields['url']['hasWebsiteType'] = TRUE;
1407
1408 if ($contactType != 'All') {
1409 $fields = array_merge($fields,
1410 CRM_Core_BAO_CustomField::getFieldsForImport($contactType,
1411 $showAll,
1412 TRUE,
1413 FALSE,
1414 FALSE,
1415 $withMultiCustomFields
1416 )
1417 );
1418 // Unset the fields which are not related to their contact type.
1419 foreach (CRM_Contact_DAO_Contact::import() as $name => $value) {
1420 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1421 unset($fields[$name]);
1422 }
1423 }
1424 }
1425 else {
1426 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $type) {
1427 $fields = array_merge($fields,
1428 CRM_Core_BAO_CustomField::getFieldsForImport($type,
1429 $showAll,
1430 FALSE,
1431 FALSE,
1432 FALSE,
1433 $withMultiCustomFields
1434 )
1435 );
1436 }
1437 }
1438
1439 if ($isProfile) {
1440 $fields = array_merge($fields, [
1441 'group' => [
1442 'title' => ts('Group(s)'),
1443 'name' => 'group',
1444 ],
1445 'tag' => [
1446 'title' => ts('Tag(s)'),
1447 'name' => 'tag',
1448 ],
1449 'note' => [
1450 'title' => ts('Note'),
1451 'name' => 'note',
1452 ],
1453 'communication_style_id' => [
1454 'title' => ts('Communication Style'),
1455 'name' => 'communication_style_id',
1456 ],
1457 ]);
1458 }
1459
1460 //Sorting fields in alphabetical order(CRM-1507)
1461 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1462
1463 Civi::cache('fields')->set($cacheKeyString, $fields);
1464 }
1465
1466 self::$_importableFields[$cacheKeyString] = $fields;
1467
1468 if (!$isProfile) {
1469 if (!$status) {
1470 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1471 self::$_importableFields[$cacheKeyString]
1472 );
1473 }
1474 else {
1475 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1476 self::$_importableFields[$cacheKeyString]
1477 );
1478 }
1479 }
1480 return $fields;
1481 }
1482
1483 /**
1484 * Combine all the exportable fields from the lower levels object.
1485 *
1486 * Currently we are using importable fields as exportable fields
1487 *
1488 * @param int|string $contactType contact Type
1489 * @param bool $status
1490 * True while exporting primary contacts.
1491 * @param bool $export
1492 * True when used during export.
1493 * @param bool $search
1494 * True when used during search, might conflict with export param?.
1495 *
1496 * @param bool $withMultiRecord
1497 * @param bool $checkPermissions
1498 *
1499 * @return array
1500 * array of exportable Fields
1501 */
1502 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1503 if (empty($contactType)) {
1504 $contactType = 'All';
1505 }
1506
1507 $cacheKeyString = "exportableFields $contactType";
1508 $cacheKeyString .= $export ? '_1' : '_0';
1509 $cacheKeyString .= $status ? '_1' : '_0';
1510 $cacheKeyString .= $search ? '_1' : '_0';
1511 $cacheKeyString .= '_' . (bool) $checkPermissions;
1512 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1513 //calculates custom fields takes into account the logged in user & caches that for all users
1514 //as an interim fix we will cache the fields by contact
1515 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1516
1517 if (!self::$_exportableFields || empty(self::$_exportableFields[$cacheKeyString])) {
1518 if (!self::$_exportableFields) {
1519 self::$_exportableFields = [];
1520 }
1521
1522 // check if we can retrieve from database cache
1523 $fields = Civi::cache('fields')->get($cacheKeyString);
1524
1525 if (!$fields) {
1526 $fields = CRM_Contact_DAO_Contact::export();
1527
1528 // The fields are meant for contact types.
1529 if (in_array($contactType, [
1530 'Individual',
1531 'Household',
1532 'Organization',
1533 'All',
1534 ])) {
1535 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1536 }
1537 // add current employer for individuals
1538 $fields = array_merge($fields, [
1539 'current_employer' =>
1540 [
1541 'name' => 'organization_name',
1542 'title' => ts('Current Employer'),
1543 'type' => CRM_Utils_Type::T_STRING,
1544 ],
1545 ]);
1546
1547 // This probably would be added anyway by appendPseudoConstantsToFields.
1548 $locationType = [
1549 'location_type' => [
1550 'name' => 'location_type',
1551 'where' => 'civicrm_location_type.name',
1552 'title' => ts('Location Type'),
1553 'type' => CRM_Utils_Type::T_STRING,
1554 ],
1555 ];
1556
1557 $IMProvider = [
1558 'im_provider' => [
1559 'name' => 'im_provider',
1560 'where' => 'civicrm_im.provider_id',
1561 'title' => ts('IM Provider'),
1562 'type' => CRM_Utils_Type::T_STRING,
1563 ],
1564 ];
1565
1566 $phoneFields = CRM_Core_DAO_Phone::export();
1567 // This adds phone_type to the exportable fields and make it available for export.
1568 // with testing the same can be done to the other entities.
1569 CRM_Core_DAO::appendPseudoConstantsToFields($phoneFields);
1570 $locationFields = array_merge($locationType,
1571 CRM_Core_DAO_Address::export(),
1572 $phoneFields,
1573 CRM_Core_DAO_Email::export(),
1574 $IMProvider,
1575 CRM_Core_DAO_IM::export(TRUE),
1576 CRM_Core_DAO_OpenID::export()
1577 );
1578
1579 $locationFields = array_merge($locationFields,
1580 CRM_Core_BAO_CustomField::getFieldsForImport('Address')
1581 );
1582
1583 foreach ($locationFields as $key => $field) {
1584 $locationFields[$key]['hasLocationType'] = TRUE;
1585 }
1586
1587 $fields = array_merge($fields, $locationFields);
1588
1589 //add world region
1590 $fields = array_merge($fields,
1591 CRM_Core_DAO_Worldregion::export()
1592 );
1593
1594 $fields = array_merge($fields,
1595 CRM_Contact_DAO_Contact::export()
1596 );
1597
1598 //website fields
1599 $fields = array_merge($fields, CRM_Core_DAO_Website::export());
1600
1601 if ($contactType != 'All') {
1602 $fields = array_merge($fields,
1603 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1604 );
1605 }
1606 else {
1607 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $type) {
1608 $fields = array_merge($fields,
1609 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1610 );
1611 }
1612 }
1613 //fix for CRM-791
1614 if ($export) {
1615 $fields = array_merge($fields, [
1616 'groups' => [
1617 'title' => ts('Group(s)'),
1618 'name' => 'groups',
1619 ],
1620 'tags' => [
1621 'title' => ts('Tag(s)'),
1622 'name' => 'tags',
1623 ],
1624 'notes' => [
1625 'title' => ts('Note(s)'),
1626 'name' => 'notes',
1627 ],
1628 ]);
1629 }
1630 else {
1631 $fields = array_merge($fields, [
1632 'group' => [
1633 'title' => ts('Group(s)'),
1634 'name' => 'group',
1635 ],
1636 'tag' => [
1637 'title' => ts('Tag(s)'),
1638 'name' => 'tag',
1639 ],
1640 'note' => [
1641 'title' => ts('Note(s)'),
1642 'name' => 'note',
1643 ],
1644 ]);
1645 }
1646
1647 //Sorting fields in alphabetical order(CRM-1507)
1648 foreach ($fields as $k => $v) {
1649 $sortArray[$k] = $v['title'] ?? NULL;
1650 }
1651
1652 $fields = array_merge($sortArray, $fields);
1653 //unset the field which are not related to their contact type.
1654 if ($contactType != 'All') {
1655 $commonValues = [
1656 'Individual' => [
1657 'household_name',
1658 'legal_name',
1659 'sic_code',
1660 'organization_name',
1661 'email_greeting_custom',
1662 'postal_greeting_custom',
1663 'addressee_custom',
1664 ],
1665 'Household' => [
1666 'first_name',
1667 'middle_name',
1668 'last_name',
1669 'formal_title',
1670 'job_title',
1671 'gender_id',
1672 'prefix_id',
1673 'suffix_id',
1674 'birth_date',
1675 'organization_name',
1676 'legal_name',
1677 'legal_identifier',
1678 'sic_code',
1679 'home_URL',
1680 'is_deceased',
1681 'deceased_date',
1682 'current_employer',
1683 'email_greeting_custom',
1684 'postal_greeting_custom',
1685 'addressee_custom',
1686 'prefix_id',
1687 'suffix_id',
1688 ],
1689 'Organization' => [
1690 'first_name',
1691 'middle_name',
1692 'last_name',
1693 'formal_title',
1694 'job_title',
1695 'gender_id',
1696 'prefix_id',
1697 'suffix_id',
1698 'birth_date',
1699 'household_name',
1700 'email_greeting_custom',
1701 'postal_greeting_custom',
1702 'prefix_id',
1703 'suffix_id',
1704 'gender_id',
1705 'addressee_custom',
1706 'is_deceased',
1707 'deceased_date',
1708 'current_employer',
1709 ],
1710 ];
1711 foreach ($commonValues[$contactType] as $value) {
1712 unset($fields[$value]);
1713 }
1714 }
1715
1716 Civi::cache('fields')->set($cacheKeyString, $fields);
1717 }
1718 self::$_exportableFields[$cacheKeyString] = $fields;
1719 }
1720
1721 if (!$status) {
1722 $fields = self::$_exportableFields[$cacheKeyString];
1723 }
1724 else {
1725 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1726 self::$_exportableFields[$cacheKeyString]
1727 );
1728 }
1729
1730 return $fields;
1731 }
1732
1733 /**
1734 * Get the all contact details (Hierarchical).
1735 *
1736 * @param int $contactId
1737 * Contact id.
1738 * @param array $fields
1739 * Fields array.
1740 *
1741 * @return array
1742 * Contact details
1743 */
1744 public static function getHierContactDetails($contactId, $fields) {
1745 $params = [['contact_id', '=', $contactId, 0, 0]];
1746
1747 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1748
1749 // We don't know the contents of return properties, but we need the lower
1750 // level ids of the contact so add a few fields.
1751 $returnProperties['first_name'] = 1;
1752 $returnProperties['organization_name'] = 1;
1753 $returnProperties['household_name'] = 1;
1754 $returnProperties['contact_type'] = 1;
1755 $returnProperties['contact_sub_type'] = 1;
1756 list($query) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties);
1757 return $query;
1758 }
1759
1760 /**
1761 * Given a set of flat profile style field names, create a hierarchy.
1762 *
1763 * This is for the query to use, create the right sql.
1764 *
1765 * @param $fields
1766 * @param int $contactId
1767 * Contact id.
1768 *
1769 * @return array
1770 * A hierarchical property tree if appropriate
1771 */
1772 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1773 $locationTypes = CRM_Core_BAO_Address::buildOptions('location_type_id', 'validate');
1774
1775 $returnProperties = [];
1776
1777 $multipleFields = ['website' => 'url'];
1778 foreach ($fields as $name => $dontCare) {
1779 if (strpos($name, '-') !== FALSE) {
1780 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
1781
1782 if (!in_array($fieldName, $multipleFields)) {
1783 if ($id == 'Primary') {
1784 $locationTypeName = 1;
1785 }
1786 else {
1787 $locationTypeName = $locationTypes[$id] ?? NULL;
1788 if (!$locationTypeName) {
1789 continue;
1790 }
1791 }
1792
1793 if (empty($returnProperties['location'])) {
1794 $returnProperties['location'] = [];
1795 }
1796 if (empty($returnProperties['location'][$locationTypeName])) {
1797 $returnProperties['location'][$locationTypeName] = [];
1798 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1799 }
1800 if (in_array($fieldName, [
1801 'phone',
1802 'im',
1803 'email',
1804 'openid',
1805 'phone_ext',
1806 ])) {
1807 if ($type) {
1808 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1809 }
1810 else {
1811 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1812 }
1813 }
1814 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1815 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1816 }
1817 else {
1818 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1819 }
1820 }
1821 else {
1822 $returnProperties['website'][$id][$fieldName] = 1;
1823 }
1824 }
1825 else {
1826 $returnProperties[$name] = 1;
1827 }
1828 }
1829
1830 return $returnProperties;
1831 }
1832
1833 /**
1834 * Return the primary location type of a contact.
1835 *
1836 * $params int $contactId contact_id
1837 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1838 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1839 *
1840 * @param int $contactId
1841 * @param bool $skipDefaultPriamry
1842 * @param null $block
1843 *
1844 * @return int
1845 * $locationType location_type_id
1846 */
1847 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1848 if ($block) {
1849 $entityBlock = ['contact_id' => $contactId];
1850 $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
1851 foreach ($blocks[$block] as $key => $value) {
1852 if (!empty($value['is_primary'])) {
1853 $locationType = $value['location_type_id'] ?? NULL;
1854 }
1855 }
1856 }
1857 else {
1858 $query = "
1859 SELECT
1860 IF ( civicrm_email.location_type_id IS NULL,
1861 IF ( civicrm_address.location_type_id IS NULL,
1862 IF ( civicrm_phone.location_type_id IS NULL,
1863 IF ( civicrm_im.location_type_id IS NULL,
1864 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1865 ,civicrm_im.location_type_id)
1866 ,civicrm_phone.location_type_id)
1867 ,civicrm_address.location_type_id)
1868 ,civicrm_email.location_type_id) as locationType
1869 FROM civicrm_contact
1870 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1871 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1872 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1873 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1874 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1875 WHERE civicrm_contact.id = %1 ";
1876
1877 $params = [1 => [$contactId, 'Integer']];
1878
1879 $dao = CRM_Core_DAO::executeQuery($query, $params);
1880
1881 $locationType = NULL;
1882 if ($dao->fetch()) {
1883 $locationType = $dao->locationType;
1884 }
1885 }
1886 if (isset($locationType)) {
1887 return $locationType;
1888 }
1889 elseif ($skipDefaultPriamry) {
1890 // if there is no primary contact location then return null
1891 return NULL;
1892 }
1893 else {
1894 // if there is no primart contact location, then return default
1895 // location type of the system
1896 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1897 return $defaultLocationType->id;
1898 }
1899 }
1900
1901 /**
1902 * Get the display name, primary email and location type of a contact.
1903 *
1904 * @param int $id
1905 * Id of the contact.
1906 *
1907 * @return array
1908 * Array of display_name, email if found, do_not_email or (null,null,null)
1909 */
1910 public static function getContactDetails($id) {
1911 // check if the contact type
1912 $contactType = self::getContactType($id);
1913
1914 $nameFields = ($contactType == 'Individual') ? "civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1915
1916 $sql = "
1917 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1918 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1919 WHERE civicrm_contact.id = %1
1920 ORDER BY civicrm_email.is_primary DESC";
1921 $params = [1 => [$id, 'Integer']];
1922 $dao = CRM_Core_DAO::executeQuery($sql, $params);
1923
1924 if ($dao->fetch()) {
1925 if ($contactType == 'Individual') {
1926 if ($dao->first_name || $dao->last_name) {
1927 $name = "{$dao->first_name} {$dao->last_name}";
1928 }
1929 else {
1930 $name = $dao->display_name;
1931 }
1932 }
1933 else {
1934 $name = $dao->display_name;
1935 }
1936 $email = $dao->email;
1937 $doNotEmail = (bool) $dao->do_not_email;
1938 $onHold = (bool) $dao->on_hold;
1939 $isDeceased = (bool) $dao->is_deceased;
1940 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1941 }
1942 return [NULL, NULL, NULL, NULL, NULL];
1943 }
1944
1945 /**
1946 * Add/edit/register contacts through profile.
1947 *
1948 * @param array $params
1949 * Array of profile fields to be edited/added.
1950 * @param array $fields
1951 * Array of fields from UFGroup.
1952 * @param int $contactID
1953 * Id of the contact to be edited/added.
1954 * @param int $addToGroupID
1955 * Specifies the default group to which contact is added.
1956 * @param int $ufGroupId
1957 * Uf group id (profile id).
1958 * @param string $ctype
1959 * @param bool $visibility
1960 * Basically lets us know where this request is coming from.
1961 * if via a profile from web, we restrict what groups are changed
1962 *
1963 * @return int
1964 * contact id created/edited
1965 *
1966 * @throws \CRM_Core_Exception
1967 * @throws \CiviCRM_API3_Exception
1968 * @throws \Civi\API\Exception\UnauthorizedException
1969 */
1970 public static function createProfileContact(
1971 &$params,
1972 $fields = [],
1973 $contactID = NULL,
1974 $addToGroupID = NULL,
1975 $ufGroupId = NULL,
1976 $ctype = NULL,
1977 $visibility = FALSE
1978 ) {
1979 // add ufGroupID to params array ( CRM-2012 )
1980 if ($ufGroupId) {
1981 $params['uf_group_id'] = $ufGroupId;
1982 }
1983 self::addBillingNameFieldsIfOtherwiseNotSet($params);
1984
1985 // If a user has logged in, or accessed via a checksum
1986 // Then deliberately 'blanking' a value in the profile should remove it from their record
1987 $session = CRM_Core_Session::singleton();
1988 $params['updateBlankLocInfo'] = TRUE;
1989 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0) {
1990 $params['updateBlankLocInfo'] = FALSE;
1991 }
1992
1993 if ($contactID) {
1994 $editHook = TRUE;
1995 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1996 }
1997 else {
1998 $editHook = FALSE;
1999 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
2000 }
2001
2002 list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2003
2004 // manage is_opt_out
2005 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2006 $wasOptOut = $contactDetails['is_opt_out'] ?? FALSE;
2007 $isOptOut = $params['is_opt_out'];
2008 $data['is_opt_out'] = $isOptOut;
2009 // on change, create new civicrm_subscription_history entry
2010 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2011 $shParams = [
2012 'contact_id' => $contactDetails['contact_id'],
2013 'status' => $isOptOut ? 'Removed' : 'Added',
2014 'method' => 'Web',
2015 ];
2016 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
2017 }
2018 }
2019
2020 $contact = self::create($data);
2021
2022 // contact is null if the profile does not have any contact fields
2023 if ($contact) {
2024 $contactID = $contact->id;
2025 }
2026
2027 if (empty($contactID)) {
2028 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
2029 }
2030
2031 // Process group and tag
2032 if (isset($params['group'])) {
2033 $method = 'Admin';
2034 // this for sure means we are coming in via profile since i added it to fix
2035 // removing contacts from user groups -- lobo
2036 if ($visibility) {
2037 $method = 'Web';
2038 }
2039 CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
2040 }
2041
2042 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2043 // Convert comma separated form values from select2 v3
2044 $tags = is_array($params['tag']) ? $params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2045 CRM_Core_BAO_EntityTag::create($tags, 'civicrm_contact', $contactID);
2046 }
2047
2048 //to add profile in default group
2049 if (is_array($addToGroupID)) {
2050 $contactIds = [$contactID];
2051 foreach ($addToGroupID as $groupId) {
2052 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
2053 }
2054 }
2055 elseif ($addToGroupID) {
2056 $contactIds = [$contactID];
2057 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
2058 }
2059
2060 if ($editHook) {
2061 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
2062 }
2063 else {
2064 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
2065 }
2066 return $contactID;
2067 }
2068
2069 /**
2070 * Format profile contact parameters.
2071 *
2072 * @param array $params
2073 * @param $fields
2074 * @param int $contactID
2075 * @param int $ufGroupId
2076 * @param null $ctype
2077 * @param bool $skipCustom
2078 *
2079 * @return array
2080 */
2081 public static function formatProfileContactParams(
2082 &$params,
2083 $fields,
2084 $contactID = NULL,
2085 $ufGroupId = NULL,
2086 $ctype = NULL,
2087 $skipCustom = FALSE
2088 ) {
2089
2090 $data = $contactDetails = [];
2091
2092 // get the contact details (hier)
2093 if ($contactID) {
2094 $details = self::getHierContactDetails($contactID, $fields);
2095
2096 $contactDetails = $details[$contactID];
2097 $data['contact_type'] = $contactDetails['contact_type'] ?? NULL;
2098 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ?? NULL;
2099 }
2100 else {
2101 //we should get contact type only if contact
2102 if ($ufGroupId) {
2103 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
2104
2105 //special case to handle profile with only contact fields
2106 if ($data['contact_type'] == 'Contact') {
2107 $data['contact_type'] = 'Individual';
2108 }
2109 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
2110 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
2111 }
2112 }
2113 elseif ($ctype) {
2114 $data['contact_type'] = $ctype;
2115 }
2116 else {
2117 $data['contact_type'] = 'Individual';
2118 }
2119 }
2120
2121 //fix contact sub type CRM-5125
2122 if (array_key_exists('contact_sub_type', $params) &&
2123 !empty($params['contact_sub_type'])
2124 ) {
2125 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
2126 }
2127 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2128 !empty($params['contact_sub_type_hidden'])
2129 ) {
2130 // if profile was used, and had any subtype, we obtain it from there
2131 //CRM-13596 - add to existing contact types, rather than overwriting
2132 if (empty($data['contact_sub_type'])) {
2133 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2134 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2135 }
2136 else {
2137 $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2138 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2139 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2140 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR);
2141 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2142 }
2143 }
2144 }
2145
2146 if ($ctype == 'Organization') {
2147 $data['organization_name'] = $contactDetails['organization_name'] ?? NULL;
2148 }
2149 elseif ($ctype == 'Household') {
2150 $data['household_name'] = $contactDetails['household_name'] ?? NULL;
2151 }
2152
2153 $locationType = [];
2154 $count = 1;
2155
2156 if ($contactID) {
2157 //add contact id
2158 $data['contact_id'] = $contactID;
2159 $primaryLocationType = self::getPrimaryLocationType($contactID);
2160 }
2161 else {
2162 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2163 $defaultLocationId = $defaultLocation->id;
2164 }
2165
2166 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
2167
2168 $blocks = ['email', 'phone', 'im', 'openid'];
2169
2170 $multiplFields = ['url'];
2171 // prevent overwritten of formatted array, reset all block from
2172 // params if it is not in valid format (since import pass valid format)
2173 foreach ($blocks as $blk) {
2174 if (array_key_exists($blk, $params) &&
2175 !is_array($params[$blk])
2176 ) {
2177 unset($params[$blk]);
2178 }
2179 }
2180
2181 $primaryPhoneLoc = NULL;
2182 $session = CRM_Core_Session::singleton();
2183 foreach ($params as $key => $value) {
2184 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2185
2186 if ($locTypeId == 'Primary') {
2187 if ($contactID) {
2188 if (in_array($fieldName, $blocks)) {
2189 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2190 }
2191 else {
2192 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2193 }
2194 $primaryLocationType = $locTypeId;
2195 }
2196 else {
2197 $locTypeId = $defaultLocationId;
2198 }
2199 }
2200
2201 if (is_numeric($locTypeId) &&
2202 !in_array($fieldName, $multiplFields) &&
2203 substr($fieldName, 0, 7) != 'custom_'
2204 ) {
2205 $index = $locTypeId;
2206
2207 if (is_numeric($typeId)) {
2208 $index .= '-' . $typeId;
2209 }
2210 if (!in_array($index, $locationType)) {
2211 $locationType[$count] = $index;
2212 $count++;
2213 }
2214
2215 $loc = CRM_Utils_Array::key($index, $locationType);
2216
2217 $blockName = self::getLocationEntityForKey($fieldName);
2218
2219 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2220
2221 //set is_billing true, for location type "Billing"
2222 if ($locTypeId == $billingLocationTypeId) {
2223 $data[$blockName][$loc]['is_billing'] = 1;
2224 }
2225
2226 if ($contactID) {
2227 //get the primary location type
2228 if ($locTypeId == $primaryLocationType) {
2229 $data[$blockName][$loc]['is_primary'] = 1;
2230 }
2231 }
2232 elseif ($locTypeId == $defaultLocationId) {
2233 $data[$blockName][$loc]['is_primary'] = 1;
2234 }
2235
2236 if (in_array($fieldName, ['phone'])) {
2237 if ($typeId) {
2238 $data['phone'][$loc]['phone_type_id'] = $typeId;
2239 }
2240 else {
2241 $data['phone'][$loc]['phone_type_id'] = '';
2242 }
2243 $data['phone'][$loc]['phone'] = $value;
2244
2245 //special case to handle primary phone with different phone types
2246 // in this case we make first phone type as primary
2247 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2248 $primaryPhoneLoc = $loc;
2249 }
2250
2251 if ($loc != $primaryPhoneLoc) {
2252 unset($data['phone'][$loc]['is_primary']);
2253 }
2254 }
2255 elseif ($fieldName == 'email') {
2256 $data['email'][$loc]['email'] = $value;
2257 if (empty($contactID)) {
2258 $data['email'][$loc]['is_primary'] = 1;
2259 }
2260 }
2261 elseif ($fieldName == 'im') {
2262 if (isset($params[$key . '-provider_id'])) {
2263 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2264 }
2265 if (strpos($key, '-provider_id') !== FALSE) {
2266 $data['im'][$loc]['provider_id'] = $params[$key];
2267 }
2268 else {
2269 $data['im'][$loc]['name'] = $value;
2270 }
2271 }
2272 elseif ($fieldName == 'openid') {
2273 $data['openid'][$loc]['openid'] = $value;
2274 }
2275 else {
2276 if ($fieldName === 'state_province') {
2277 // CRM-3393
2278 if (is_numeric($value) && ((int ) $value) >= 1000) {
2279 $data['address'][$loc]['state_province_id'] = $value;
2280 }
2281 elseif (empty($value)) {
2282 $data['address'][$loc]['state_province_id'] = '';
2283 }
2284 else {
2285 $data['address'][$loc]['state_province'] = $value;
2286 }
2287 }
2288 elseif ($fieldName === 'country') {
2289 // CRM-3393
2290 if (is_numeric($value) && ((int ) $value) >= 1000
2291 ) {
2292 $data['address'][$loc]['country_id'] = $value;
2293 }
2294 elseif (empty($value)) {
2295 $data['address'][$loc]['country_id'] = '';
2296 }
2297 else {
2298 $data['address'][$loc]['country'] = $value;
2299 }
2300 }
2301 elseif ($fieldName === 'county') {
2302 $data['address'][$loc]['county_id'] = $value;
2303 }
2304 elseif ($fieldName == 'address_name') {
2305 $data['address'][$loc]['name'] = $value;
2306 }
2307 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2308 $data['address'][$loc][substr($fieldName, 8)] = $value;
2309 }
2310 else {
2311 $data[$blockName][$loc][$fieldName] = $value;
2312 }
2313 }
2314 }
2315 else {
2316 if (substr($key, 0, 4) === 'url-') {
2317 $websiteField = explode('-', $key);
2318 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2319 $data['website'][$websiteField[1]]['url'] = $value;
2320 }
2321 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
2322 //save email/postal greeting and addressee values if any, CRM-4575
2323 $data[$key . '_id'] = $value;
2324 }
2325 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2326 // for autocomplete transfer hidden value instead of label
2327 if ($params[$key] && isset($params[$key . '_id'])) {
2328 $value = $params[$key . '_id'];
2329 }
2330
2331 // we need to append time with date
2332 if ($params[$key] && isset($params[$key . '_time'])) {
2333 $value .= ' ' . $params[$key . '_time'];
2334 }
2335
2336 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2337 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
2338 ($value == '' || !isset($value))
2339 ) {
2340 continue;
2341 }
2342
2343 $valueId = NULL;
2344 if (!empty($params['customRecordValues'])) {
2345 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2346 foreach ($params['customRecordValues'] as $recId => $customFields) {
2347 if (is_array($customFields) && !empty($customFields)) {
2348 foreach ($customFields as $customFieldName) {
2349 if ($customFieldName == $key) {
2350 $valueId = $recId;
2351 break;
2352 }
2353 }
2354 }
2355 }
2356 }
2357 }
2358
2359 //CRM-13596 - check for contact_sub_type_hidden first
2360 if (array_key_exists('contact_sub_type_hidden', $params)) {
2361 $type = $params['contact_sub_type_hidden'];
2362 }
2363 else {
2364 $type = $data['contact_type'];
2365 if (!empty($data['contact_sub_type'])) {
2366 $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2367 }
2368 }
2369
2370 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2371 $data['custom'],
2372 $value,
2373 $type,
2374 $valueId,
2375 $contactID,
2376 FALSE,
2377 FALSE
2378 );
2379 }
2380 elseif ($key === 'edit') {
2381 continue;
2382 }
2383 else {
2384 if ($key === 'location') {
2385 foreach ($value as $locationTypeId => $field) {
2386 foreach ($field as $block => $val) {
2387 if ($block === 'address' && array_key_exists('address_name', $val)) {
2388 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2389 }
2390 }
2391 }
2392 }
2393 if ($key === 'phone' && isset($params['phone_ext'])) {
2394 $data[$key] = $value;
2395 foreach ($value as $cnt => $phoneBlock) {
2396 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2397 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2398 }
2399 }
2400 }
2401 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2402 && ($value == '' || !isset($value)) &&
2403 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2404 ($key === 'current_employer' && empty($params['current_employer']))) {
2405 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2406 // to avoid update with empty values
2407 continue;
2408 }
2409 else {
2410 $data[$key] = $value;
2411 }
2412 }
2413 }
2414 }
2415
2416 if (!isset($data['contact_type'])) {
2417 $data['contact_type'] = 'Individual';
2418 }
2419
2420 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2421 $privacy = CRM_Core_SelectValues::privacy();
2422 foreach ($privacy as $key => $value) {
2423 if (array_key_exists($key, $fields)) {
2424 // do not reset values for existing contacts, if fields are added to a profile
2425 if (array_key_exists($key, $params)) {
2426 $data[$key] = $params[$key];
2427 if (empty($params[$key])) {
2428 $data[$key] = 0;
2429 }
2430 }
2431 elseif (!$contactID) {
2432 $data[$key] = 0;
2433 }
2434 }
2435 }
2436
2437 return [$data, $contactDetails];
2438 }
2439
2440 /**
2441 * Find the get contact details.
2442 *
2443 * This function does not respect ACLs for now, which might need to be rectified at some
2444 * stage based on how its used.
2445 *
2446 * @param string $mail
2447 * Primary email address of the contact.
2448 * @param string $ctype
2449 * Contact type.
2450 *
2451 * @return object|null
2452 * $dao contact details
2453 */
2454 public static function matchContactOnEmail($mail, $ctype = NULL) {
2455 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2456 $mail = $strtolower(trim($mail));
2457 $query = "
2458 SELECT civicrm_contact.id as contact_id,
2459 civicrm_contact.hash as hash,
2460 civicrm_contact.contact_type as contact_type,
2461 civicrm_contact.contact_sub_type as contact_sub_type
2462 FROM civicrm_contact
2463 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2464
2465 if (Civi::settings()->get('uniq_email_per_site')) {
2466 // try to find a match within a site (multisite).
2467 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2468 if (!empty($groups)) {
2469 $query .= "
2470 INNER JOIN civicrm_group_contact gc ON
2471 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2472 }
2473 }
2474
2475 $query .= "
2476 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2477 $p = [1 => [$mail, 'String']];
2478
2479 if ($ctype) {
2480 $query .= " AND civicrm_contact.contact_type = %3";
2481 $p[3] = [$ctype, 'String'];
2482 }
2483
2484 $query .= " ORDER BY civicrm_email.is_primary DESC";
2485
2486 $dao = CRM_Core_DAO::executeQuery($query, $p);
2487
2488 if ($dao->fetch()) {
2489 return $dao;
2490 }
2491 return NULL;
2492 }
2493
2494 /**
2495 * Find the contact details associated with an OpenID.
2496 *
2497 * @param string $openId
2498 * OpenId of the contact.
2499 * @param string $ctype
2500 * Contact type.
2501 *
2502 * @return object|null
2503 * $dao contact details
2504 */
2505 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2506 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2507 $openId = $strtolower(trim($openId));
2508 $query = "
2509 SELECT civicrm_contact.id as contact_id,
2510 civicrm_contact.hash as hash,
2511 civicrm_contact.contact_type as contact_type,
2512 civicrm_contact.contact_sub_type as contact_sub_type
2513 FROM civicrm_contact
2514 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2515 WHERE civicrm_openid.openid = %1";
2516 $p = [1 => [$openId, 'String']];
2517
2518 if ($ctype) {
2519 $query .= " AND civicrm_contact.contact_type = %3";
2520 $p[3] = [$ctype, 'String'];
2521 }
2522
2523 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2524
2525 $dao = CRM_Core_DAO::executeQuery($query, $p);
2526
2527 if ($dao->fetch()) {
2528 return $dao;
2529 }
2530 return NULL;
2531 }
2532
2533 /**
2534 * Get primary email of the contact.
2535 *
2536 * @param int $contactID
2537 * Contact id.
2538 * @param bool $polite
2539 * Whether to only pull an email if it's okay to send to it--that is, if it
2540 * is not on_hold and the contact is not do_not_email.
2541 *
2542 * @return string
2543 * Email address if present else null
2544 */
2545 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2546 // fetch the primary email
2547 $query = "
2548 SELECT civicrm_email.email as email
2549 FROM civicrm_contact
2550 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2551 WHERE civicrm_email.is_primary = 1
2552 AND civicrm_contact.id = %1";
2553 if ($polite) {
2554 $query .= '
2555 AND civicrm_contact.do_not_email = 0
2556 AND civicrm_email.on_hold = 0';
2557 }
2558 $p = [1 => [$contactID, 'Integer']];
2559 $dao = CRM_Core_DAO::executeQuery($query, $p);
2560
2561 $email = NULL;
2562 if ($dao->fetch()) {
2563 $email = $dao->email;
2564 }
2565 return $email;
2566 }
2567
2568 /**
2569 * Fetch the object and store the values in the values array.
2570 *
2571 * @param array $params
2572 * Input parameters to find object.
2573 * @param array $values
2574 * Output values of the object.
2575 *
2576 * @return CRM_Contact_BAO_Contact|null
2577 * The found object or null
2578 */
2579 public static function getValues(&$params, &$values) {
2580 $contact = new CRM_Contact_BAO_Contact();
2581
2582 $contact->copyValues($params);
2583
2584 if ($contact->find(TRUE)) {
2585
2586 CRM_Core_DAO::storeValues($contact, $values);
2587
2588 $privacy = [];
2589 foreach (self::$_commPrefs as $name) {
2590 if (isset($contact->$name)) {
2591 $privacy[$name] = $contact->$name;
2592 }
2593 }
2594
2595 if (!empty($privacy)) {
2596 $values['privacy'] = $privacy;
2597 }
2598
2599 // communication Prefferance
2600 $preffComm = $comm = [];
2601 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2602 $contact->preferred_communication_method
2603 );
2604 foreach ($comm as $value) {
2605 $preffComm[$value] = 1;
2606 }
2607 $temp = ['preferred_communication_method' => $contact->preferred_communication_method];
2608
2609 $names = [
2610 'preferred_communication_method' => [
2611 'newName' => 'preferred_communication_method_display',
2612 'groupName' => 'preferred_communication_method',
2613 ],
2614 ];
2615
2616 // @todo This can be figured out from metadata & we can avoid the uncached query.
2617 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2618
2619 $values['preferred_communication_method'] = $preffComm;
2620 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ?? NULL;
2621
2622 if ($contact->preferred_mail_format) {
2623 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2624 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2625 }
2626
2627 // get preferred languages
2628 if (!empty($contact->preferred_language)) {
2629 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2630 }
2631
2632 // Calculating Year difference
2633 if ($contact->birth_date) {
2634 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2635 if ($birthDate < date('Ymd')) {
2636 $age = CRM_Utils_Date::calculateAge($birthDate);
2637 $values['age']['y'] = $age['years'] ?? NULL;
2638 $values['age']['m'] = $age['months'] ?? NULL;
2639 }
2640 }
2641
2642 $contact->contact_id = $contact->id;
2643
2644 return $contact;
2645 }
2646 return NULL;
2647 }
2648
2649 /**
2650 * Given the component name and returns the count of participation of contact.
2651 *
2652 * @param string $component
2653 * Input component name.
2654 * @param int $contactId
2655 * Input contact id.
2656 * @param string $tableName
2657 * Optional tableName if component is custom group.
2658 *
2659 * @return int
2660 * total number in database
2661 */
2662 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2663 $object = NULL;
2664 switch ($component) {
2665 case 'tag':
2666 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2667
2668 case 'rel':
2669 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2670 CRM_Contact_BAO_Relationship::CURRENT,
2671 0, 1, 0,
2672 NULL, NULL,
2673 TRUE
2674 );
2675 return $result;
2676
2677 case 'group':
2678
2679 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2680
2681 case 'log':
2682 if (CRM_Core_BAO_Log::useLoggingReport()) {
2683 return FALSE;
2684 }
2685 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2686
2687 case 'note':
2688 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2689
2690 case 'contribution':
2691 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2692
2693 case 'membership':
2694 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2695
2696 case 'participant':
2697 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2698
2699 case 'pledge':
2700 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2701
2702 case 'case':
2703 return CRM_Case_BAO_Case::caseCount($contactId);
2704
2705 case 'grant':
2706 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2707
2708 case 'activity':
2709 $input = [
2710 'contact_id' => $contactId,
2711 'admin' => FALSE,
2712 'caseId' => NULL,
2713 'context' => 'activity',
2714 ];
2715 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2716
2717 case 'mailing':
2718 $params = ['contact_id' => $contactId];
2719 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2720
2721 default:
2722 $custom = explode('_', $component);
2723 if ($custom['0'] = 'custom') {
2724 if (!$tableName) {
2725 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2726 }
2727 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2728 return CRM_Core_DAO::singleValueQuery($queryString);
2729 }
2730 }
2731 }
2732
2733 /**
2734 * Update contact greetings if an update has resulted in a custom field change.
2735 *
2736 * @param array $updatedFields
2737 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2738 * @param array $contactParams
2739 * Parameters known about the contact. At minimum array('contact_id' => x).
2740 * Fields in this array will take precedence over DB fields (so far only
2741 * in the case of greeting id fields).
2742 */
2743 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2744 $contactID = $contactParams['contact_id'];
2745 CRM_Contact_BAO_Contact::ensureGreetingParamsAreSet($contactParams);
2746 $tokens = CRM_Contact_BAO_Contact_Utils::getTokensRequiredForContactGreetings($contactParams);
2747 if (!empty($tokens['all']['contact'])) {
2748 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2749 if (!empty($affectedTokens)) {
2750 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2751 $contact = new CRM_Contact_BAO_Contact();
2752 $contact->id = $contactID;
2753 CRM_Contact_BAO_Contact::processGreetings($contact);
2754 }
2755 }
2756 }
2757
2758 /**
2759 * Process greetings and cache.
2760 *
2761 * @param object $contact
2762 * Contact object after save.
2763 */
2764 public static function processGreetings(&$contact) {
2765
2766 //@todo this function does a lot of unnecessary loading.
2767 // ensureGreetingParamsAreSet now makes sure that the contact is
2768 // loaded and using updateGreetingsOnTokenFieldChange
2769 // allows us the possibility of only doing an update if required.
2770
2771 // The contact object has not always required the
2772 // fields that are required to calculate greetings
2773 // so we need to retrieve it again.
2774 if ($contact->_query !== FALSE) {
2775 $contact->find(TRUE);
2776 }
2777
2778 // store object values to an array
2779 $contactDetails = [];
2780 CRM_Core_DAO::storeValues($contact, $contactDetails);
2781 $contactDetails = [[$contact->id => $contactDetails]];
2782
2783 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2784 $updateQueryString = [];
2785
2786 //cache email and postal greeting to greeting display
2787 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2788 $emailGreetingString = $contact->email_greeting_custom;
2789 }
2790 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2791 // the filter value for Individual contact type is set to 1
2792 $filter = [
2793 'contact_type' => $contact->contact_type,
2794 'greeting_type' => 'email_greeting',
2795 ];
2796
2797 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2798 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2799 $updateQueryString[] = " email_greeting_custom = NULL ";
2800 }
2801 else {
2802 if ($contact->email_greeting_custom) {
2803 $updateQueryString[] = " email_greeting_display = NULL ";
2804 }
2805 }
2806
2807 if ($emailGreetingString) {
2808 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2809 $contactDetails,
2810 $contact->id,
2811 'CRM_Contact_BAO_Contact'
2812 );
2813 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2814 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2815 }
2816
2817 //postal greetings
2818 if ($contact->postal_greeting_custom !== 'null' && $contact->postal_greeting_custom) {
2819 $postalGreetingString = $contact->postal_greeting_custom;
2820 }
2821 elseif ($contact->postal_greeting_id !== 'null' && $contact->postal_greeting_id) {
2822 $filter = [
2823 'contact_type' => $contact->contact_type,
2824 'greeting_type' => 'postal_greeting',
2825 ];
2826 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2827 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2828 $updateQueryString[] = " postal_greeting_custom = NULL ";
2829 }
2830 else {
2831 if ($contact->postal_greeting_custom) {
2832 $updateQueryString[] = " postal_greeting_display = NULL ";
2833 }
2834 }
2835
2836 if ($postalGreetingString) {
2837 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2838 $contactDetails,
2839 $contact->id,
2840 'CRM_Contact_BAO_Contact'
2841 );
2842 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2843 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2844 }
2845
2846 // addressee
2847 if ($contact->addressee_custom !== 'null' && $contact->addressee_custom) {
2848 $addresseeString = $contact->addressee_custom;
2849 }
2850 elseif ($contact->addressee_id !== 'null' && $contact->addressee_id) {
2851 $filter = [
2852 'contact_type' => $contact->contact_type,
2853 'greeting_type' => 'addressee',
2854 ];
2855
2856 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2857 $addresseeString = $addressee[$contact->addressee_id];
2858 $updateQueryString[] = " addressee_custom = NULL ";
2859 }
2860 else {
2861 if ($contact->addressee_custom) {
2862 $updateQueryString[] = " addressee_display = NULL ";
2863 }
2864 }
2865
2866 if ($addresseeString) {
2867 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2868 $contactDetails,
2869 $contact->id,
2870 'CRM_Contact_BAO_Contact'
2871 );
2872 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2873 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2874 }
2875
2876 if (!empty($updateQueryString)) {
2877 $updateQueryString = implode(',', $updateQueryString);
2878 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2879 CRM_Core_DAO::executeQuery($queryString);
2880 }
2881 }
2882
2883 /**
2884 * Retrieve loc block ids w/ given condition.
2885 *
2886 * @param int $contactId
2887 * Contact id.
2888 * @param array $criteria
2889 * Key => value pair which should be.
2890 * fulfill by return record ids.
2891 * @param string $condOperator
2892 * Operator use for grouping multiple conditions.
2893 *
2894 * @return array
2895 * loc block ids which fulfill condition.
2896 */
2897 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2898 $locBlockIds = [];
2899 if (!$contactId) {
2900 return $locBlockIds;
2901 }
2902
2903 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2904 $name = strtolower($block);
2905 $className = "CRM_Core_DAO_$block";
2906 $blockDAO = new $className();
2907
2908 // build the condition.
2909 if (is_array($criteria)) {
2910 $fields = $blockDAO->fields();
2911 $conditions = [];
2912 foreach ($criteria as $field => $value) {
2913 if (array_key_exists($field, $fields)) {
2914 $cond = "( $field = $value )";
2915 // value might be zero or null.
2916 if (!$value || strtolower($value) === 'null') {
2917 $cond = "( $field = 0 OR $field IS NULL )";
2918 }
2919 $conditions[] = $cond;
2920 }
2921 }
2922 if (!empty($conditions)) {
2923 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2924 }
2925 }
2926
2927 $blockDAO->contact_id = $contactId;
2928 $blockDAO->find();
2929 while ($blockDAO->fetch()) {
2930 $locBlockIds[$name][] = $blockDAO->id;
2931 }
2932 }
2933
2934 return $locBlockIds;
2935 }
2936
2937 /**
2938 * Build context menu items.
2939 *
2940 * @param int $contactId
2941 *
2942 * @return array
2943 * Array of context menu for logged in user.
2944 */
2945 public static function contextMenu($contactId = NULL) {
2946 $menu = [
2947 'view' => [
2948 'title' => ts('View Contact'),
2949 'weight' => 0,
2950 'ref' => 'view-contact',
2951 'class' => 'no-popup',
2952 'key' => 'view',
2953 'permissions' => ['view all contacts'],
2954 ],
2955 'add' => [
2956 'title' => ts('Edit Contact'),
2957 'weight' => 0,
2958 'ref' => 'edit-contact',
2959 'class' => 'no-popup',
2960 'key' => 'add',
2961 'permissions' => ['edit all contacts'],
2962 ],
2963 'delete' => [
2964 'title' => ts('Delete Contact'),
2965 'weight' => 0,
2966 'ref' => 'delete-contact',
2967 'key' => 'delete',
2968 'permissions' => ['access deleted contacts', 'delete contacts'],
2969 ],
2970 'contribution' => [
2971 'title' => ts('Add Contribution'),
2972 'weight' => 5,
2973 'ref' => 'new-contribution',
2974 'key' => 'contribution',
2975 'tab' => 'contribute',
2976 'component' => 'CiviContribute',
2977 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2978 'reset=1&action=add&context=contribution'
2979 ),
2980 'permissions' => [
2981 'access CiviContribute',
2982 'edit contributions',
2983 ],
2984 ],
2985 'participant' => [
2986 'title' => ts('Register for Event'),
2987 'weight' => 10,
2988 'ref' => 'new-participant',
2989 'key' => 'participant',
2990 'tab' => 'participant',
2991 'component' => 'CiviEvent',
2992 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2993 'permissions' => [
2994 'access CiviEvent',
2995 'edit event participants',
2996 ],
2997 ],
2998 'activity' => [
2999 'title' => ts('Record Activity'),
3000 'weight' => 35,
3001 'ref' => 'new-activity',
3002 'key' => 'activity',
3003 'permissions' => ['edit all contacts'],
3004 ],
3005 'pledge' => [
3006 'title' => ts('Add Pledge'),
3007 'weight' => 15,
3008 'ref' => 'new-pledge',
3009 'key' => 'pledge',
3010 'tab' => 'pledge',
3011 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
3012 'reset=1&action=add&context=pledge'
3013 ),
3014 'component' => 'CiviPledge',
3015 'permissions' => [
3016 'access CiviPledge',
3017 'edit pledges',
3018 ],
3019 ],
3020 'membership' => [
3021 'title' => ts('Add Membership'),
3022 'weight' => 20,
3023 'ref' => 'new-membership',
3024 'key' => 'membership',
3025 'tab' => 'member',
3026 'component' => 'CiviMember',
3027 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
3028 'reset=1&action=add&context=membership'
3029 ),
3030 'permissions' => [
3031 'access CiviMember',
3032 'edit memberships',
3033 ],
3034 ],
3035 'case' => [
3036 'title' => ts('Add Case'),
3037 'weight' => 25,
3038 'ref' => 'new-case',
3039 'key' => 'case',
3040 'tab' => 'case',
3041 'component' => 'CiviCase',
3042 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3043 'permissions' => ['add cases'],
3044 ],
3045 'grant' => [
3046 'title' => ts('Add Grant'),
3047 'weight' => 26,
3048 'ref' => 'new-grant',
3049 'key' => 'grant',
3050 'tab' => 'grant',
3051 'component' => 'CiviGrant',
3052 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
3053 'reset=1&action=add&context=grant'
3054 ),
3055 'permissions' => ['edit grants'],
3056 ],
3057 'rel' => [
3058 'title' => ts('Add Relationship'),
3059 'weight' => 30,
3060 'ref' => 'new-relationship',
3061 'key' => 'rel',
3062 'tab' => 'rel',
3063 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
3064 'reset=1&action=add'
3065 ),
3066 'permissions' => ['edit all contacts'],
3067 ],
3068 'note' => [
3069 'title' => ts('Add Note'),
3070 'weight' => 40,
3071 'ref' => 'new-note',
3072 'key' => 'note',
3073 'tab' => 'note',
3074 'class' => 'medium-popup',
3075 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
3076 'reset=1&action=add'
3077 ),
3078 'permissions' => ['edit all contacts'],
3079 ],
3080 'email' => [
3081 'title' => ts('Send an Email'),
3082 'weight' => 45,
3083 'ref' => 'new-email',
3084 'key' => 'email',
3085 'permissions' => ['view all contacts'],
3086 ],
3087 'group' => [
3088 'title' => ts('Add to Group'),
3089 'weight' => 50,
3090 'ref' => 'group-add-contact',
3091 'key' => 'group',
3092 'tab' => 'group',
3093 'permissions' => ['edit groups'],
3094 ],
3095 'tag' => [
3096 'title' => ts('Tag Contact'),
3097 'weight' => 55,
3098 'ref' => 'tag-contact',
3099 'key' => 'tag',
3100 'tab' => 'tag',
3101 'permissions' => ['edit all contacts'],
3102 ],
3103 ];
3104
3105 $menu['otherActions'] = [
3106 'print' => [
3107 'title' => ts('Print Summary'),
3108 'description' => ts('Printer-friendly view of this page.'),
3109 'weight' => 5,
3110 'ref' => 'crm-contact-print',
3111 'key' => 'print',
3112 'tab' => 'print',
3113 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3114 "reset=1&print=1"
3115 ),
3116 'class' => 'print',
3117 'icon' => 'crm-i fa-print',
3118 ],
3119 'vcard' => [
3120 'title' => ts('vCard'),
3121 'description' => ts('vCard record for this contact.'),
3122 'weight' => 10,
3123 'ref' => 'crm-contact-vcard',
3124 'key' => 'vcard',
3125 'tab' => 'vcard',
3126 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3127 "reset=1"
3128 ),
3129 'class' => 'vcard',
3130 'icon' => 'crm-i fa-list-alt',
3131 ],
3132 ];
3133
3134 if (CRM_Core_Permission::check('access Contact Dashboard')) {
3135 $menu['otherActions']['dashboard'] = [
3136 'title' => ts('Contact Dashboard'),
3137 'description' => ts('Contact Dashboard'),
3138 'weight' => 15,
3139 'ref' => 'crm-contact-dashboard',
3140 'key' => 'dashboard',
3141 'tab' => 'dashboard',
3142 'class' => 'dashboard',
3143 // NOTE: As an alternative you can also build url on CMS specific way
3144 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3145 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id={$contactId}"),
3146 'icon' => 'crm-i fa-tachometer',
3147 ];
3148 }
3149
3150 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3151 if ($uid) {
3152 $menu['otherActions']['user-record'] = [
3153 'title' => ts('User Record'),
3154 'description' => ts('User Record'),
3155 'weight' => 20,
3156 'ref' => 'crm-contact-user-record',
3157 'key' => 'user-record',
3158 'tab' => 'user-record',
3159 'class' => 'user-record',
3160 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
3161 'icon' => 'crm-i fa-user',
3162 ];
3163 }
3164 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
3165 $menu['otherActions']['user-add'] = [
3166 'title' => ts('Create User Record'),
3167 'description' => ts('Create User Record'),
3168 'weight' => 25,
3169 'ref' => 'crm-contact-user-add',
3170 'key' => 'user-add',
3171 'tab' => 'user-add',
3172 'class' => 'user-add',
3173 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3174 'icon' => 'crm-i fa-user-plus',
3175 ];
3176 }
3177
3178 CRM_Utils_Hook::summaryActions($menu, $contactId);
3179 //1. check for component is active.
3180 //2. check for user permissions.
3181 //3. check for acls.
3182 //3. edit and view contact are directly accessible to user.
3183
3184 $aclPermissionedTasks = [
3185 'view-contact',
3186 'edit-contact',
3187 'new-activity',
3188 'new-email',
3189 'group-add-contact',
3190 'tag-contact',
3191 'delete-contact',
3192 ];
3193 $corePermission = CRM_Core_Permission::getPermission();
3194
3195 $contextMenu = [];
3196 foreach ($menu as $key => $values) {
3197 if ($key !== 'otherActions') {
3198
3199 // user does not have necessary permissions.
3200 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3201 continue;
3202 }
3203 // build directly accessible action menu.
3204 if (in_array($values['ref'], [
3205 'view-contact',
3206 'edit-contact',
3207 ])) {
3208 $contextMenu['primaryActions'][$key] = [
3209 'title' => $values['title'],
3210 'ref' => $values['ref'],
3211 'class' => $values['class'] ?? NULL,
3212 'key' => $values['key'],
3213 ];
3214 continue;
3215 }
3216
3217 // finally get menu item for -more- action widget.
3218 $contextMenu['moreActions'][$values['weight']] = [
3219 'title' => $values['title'],
3220 'ref' => $values['ref'],
3221 'href' => $values['href'] ?? NULL,
3222 'tab' => $values['tab'] ?? NULL,
3223 'class' => $values['class'] ?? NULL,
3224 'key' => $values['key'],
3225 ];
3226 }
3227 else {
3228 foreach ($values as $value) {
3229 // user does not have necessary permissions.
3230 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3231 continue;
3232 }
3233
3234 // finally get menu item for -more- action widget.
3235 $contextMenu['otherActions'][$value['weight']] = [
3236 'title' => $value['title'],
3237 'ref' => $value['ref'],
3238 'href' => $value['href'] ?? NULL,
3239 'tab' => $value['tab'] ?? NULL,
3240 'class' => $value['class'] ?? NULL,
3241 'icon' => $value['icon'] ?? NULL,
3242 'key' => $value['key'],
3243 ];
3244 }
3245 }
3246 }
3247
3248 ksort($contextMenu['moreActions']);
3249 ksort($contextMenu['otherActions']);
3250
3251 return $contextMenu;
3252 }
3253
3254 /**
3255 * Check if user has permissions to access items in action menu.
3256 *
3257 * @param array $aclPermissionedTasks
3258 * Array containing ACL related tasks.
3259 * @param string $corePermission
3260 * The permission of the user (edit or view or null).
3261 * @param array $menuOptions
3262 * Array containing params of the menu (title, href, etc).
3263 *
3264 * @return bool
3265 * TRUE if user has all permissions, FALSE if otherwise.
3266 */
3267 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3268 $componentName = $menuOptions['component'] ?? NULL;
3269
3270 // if component action - make sure component is enable.
3271 if ($componentName && !in_array($componentName, CRM_Core_Config::singleton()->enableComponents)) {
3272 return FALSE;
3273 }
3274
3275 // make sure user has all required permissions.
3276 $hasAllPermissions = FALSE;
3277
3278 $permissions = $menuOptions['permissions'] ?? NULL;
3279 if (!is_array($permissions) || empty($permissions)) {
3280 $hasAllPermissions = TRUE;
3281 }
3282
3283 // iterate for required permissions in given permissions array.
3284 if (!$hasAllPermissions) {
3285 $hasPermissions = 0;
3286 foreach ($permissions as $permission) {
3287 if (CRM_Core_Permission::check($permission)) {
3288 $hasPermissions++;
3289 }
3290 }
3291
3292 if (count($permissions) == $hasPermissions) {
3293 $hasAllPermissions = TRUE;
3294 }
3295
3296 // if still user does not have required permissions, check acl.
3297 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3298 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3299 $corePermission == CRM_Core_Permission::EDIT
3300 ) {
3301 $hasAllPermissions = TRUE;
3302 }
3303 elseif (in_array($menuOptions['ref'], [
3304 'new-email',
3305 ])) {
3306 // grant permissions for these tasks.
3307 $hasAllPermissions = TRUE;
3308 }
3309 }
3310 }
3311
3312 return $hasAllPermissions;
3313 }
3314
3315 /**
3316 * Retrieve display name of contact that address is shared.
3317 *
3318 * This is based on $masterAddressId or $contactId .
3319 *
3320 * @param int $masterAddressId
3321 * Master id.
3322 * @param int $contactId
3323 * Contact id. (deprecated - do not use)
3324 *
3325 * @return string|null
3326 * the found display name or null.
3327 */
3328 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3329 $masterDisplayName = NULL;
3330 if (!$masterAddressId) {
3331 return $masterDisplayName;
3332 }
3333
3334 $sql = "
3335 SELECT display_name from civicrm_contact
3336 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3337 WHERE civicrm_address.id = " . $masterAddressId;
3338
3339 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3340 return $masterDisplayName;
3341 }
3342
3343 /**
3344 * Get the creation/modification times for a contact.
3345 *
3346 * @param int $contactId
3347 *
3348 * @return array
3349 * Dates - ('created_date' => $, 'modified_date' => $)
3350 */
3351 public static function getTimestamps($contactId) {
3352 $timestamps = CRM_Core_DAO::executeQuery(
3353 'SELECT created_date, modified_date
3354 FROM civicrm_contact
3355 WHERE id = %1',
3356 [
3357 1 => [$contactId, 'Integer'],
3358 ]
3359 );
3360 if ($timestamps->fetch()) {
3361 return [
3362 'created_date' => $timestamps->created_date,
3363 'modified_date' => $timestamps->modified_date,
3364 ];
3365 }
3366 else {
3367 return NULL;
3368 }
3369 }
3370
3371 /**
3372 * Get a list of triggers for the contact table.
3373 *
3374 * @param $info
3375 * @param null $tableName
3376 *
3377 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3378 *
3379 * @see hook_civicrm_triggerInfo
3380 * @see CRM_Core_DAO::triggerRebuild
3381 */
3382 public static function triggerInfo(&$info, $tableName = NULL) {
3383
3384 // Modifications to these records should update the contact timestamps.
3385 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3386 ->setRelations([
3387 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3388 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3389 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3390 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3391 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3392 ])
3393 ->alterTriggerInfo($info, $tableName);
3394
3395 // Update phone table to populate phone_numeric field
3396 if (!$tableName || $tableName == 'civicrm_phone') {
3397 // Define stored sql function needed for phones
3398 $sqlTriggers = Civi::service('sql_triggers');
3399 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3400 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3401 $info[] = [
3402 'table' => ['civicrm_phone'],
3403 'when' => 'BEFORE',
3404 'event' => ['INSERT', 'UPDATE'],
3405 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3406 ];
3407 }
3408 }
3409
3410 /**
3411 * Check if contact is being used in civicrm_domain based on $contactId.
3412 *
3413 * @param int $contactId
3414 * Contact id.
3415 *
3416 * @return bool
3417 * true if present else false.
3418 */
3419 public static function checkDomainContact($contactId) {
3420 if (!$contactId) {
3421 return FALSE;
3422 }
3423 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3424
3425 if ($domainId) {
3426 return TRUE;
3427 }
3428 else {
3429 return FALSE;
3430 }
3431 }
3432
3433 /**
3434 * Get options for a given contact field.
3435 *
3436 * @param string $fieldName
3437 * @param string $context
3438 * @param array $props
3439 * whatever is known about this dao object.
3440 *
3441 * @return array|bool
3442 * @see CRM_Core_DAO::buildOptions
3443 *
3444 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3445 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3446 *
3447 * @see CRM_Core_DAO::buildOptionsContext
3448 */
3449 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3450 $params = [];
3451 // Special logic for fields whose options depend on context or properties
3452 switch ($fieldName) {
3453 case 'contact_sub_type':
3454 if (!empty($props['contact_type'])) {
3455 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3456 }
3457 break;
3458
3459 case 'contact_type':
3460 if ($context == 'search') {
3461 // CRM-15495 - EntityRef filters and basic search forms expect this format
3462 // FIXME: Search builder does not
3463 return CRM_Contact_BAO_ContactType::getSelectElements();
3464 }
3465 break;
3466
3467 // The contact api supports some related entities so we'll honor that by fetching their options
3468 case 'group_id':
3469 case 'group':
3470 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3471
3472 case 'tag_id':
3473 case 'tag':
3474 $props['entity_table'] = 'civicrm_contact';
3475 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3476
3477 case 'state_province_id':
3478 case 'state_province':
3479 case 'state_province_name':
3480 case 'country_id':
3481 case 'country':
3482 case 'county_id':
3483 case 'worldregion':
3484 case 'worldregion_id':
3485 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3486
3487 }
3488 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3489 }
3490
3491 /**
3492 * Delete a contact-related object that has an 'is_primary' field.
3493 *
3494 * Ensures that is_primary gets assigned to another object if available
3495 * Also calls pre/post hooks
3496 *
3497 * @param string $type
3498 * @param int $id
3499 *
3500 * @return bool
3501 */
3502 public static function deleteObjectWithPrimary($type, $id) {
3503 if (!$id || !is_numeric($id)) {
3504 return FALSE;
3505 }
3506 $daoName = "CRM_Core_DAO_$type";
3507 $obj = new $daoName();
3508 $obj->id = $id;
3509 $obj->find();
3510 $hookParams = [];
3511 if ($obj->fetch()) {
3512 CRM_Utils_Hook::pre('delete', $type, $id, $hookParams);
3513 $contactId = $obj->contact_id;
3514 $obj->delete();
3515 }
3516 else {
3517 return FALSE;
3518 }
3519 // is_primary is only relavent if this field belongs to a contact
3520 if ($contactId) {
3521 $dao = new $daoName();
3522 $dao->contact_id = $contactId;
3523 $dao->is_primary = 1;
3524 // Pick another record to be primary (if one isn't already)
3525 if (!$dao->find(TRUE)) {
3526 $dao->is_primary = 0;
3527 $dao->find();
3528 if ($dao->fetch()) {
3529 $dao->is_primary = 1;
3530 $dao->save();
3531 if ($type === 'Email') {
3532 CRM_Core_BAO_UFMatch::updateUFName($dao->contact_id);
3533 }
3534 }
3535 }
3536 }
3537 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3538 return TRUE;
3539 }
3540
3541 /**
3542 * @inheritDoc
3543 */
3544 public function addSelectWhereClause() {
3545 // We always return an array with these keys, even if they are empty,
3546 // because this tells the query builder that we have considered these fields for acls
3547 $clauses = [
3548 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3549 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? [] : ['!= 1'],
3550 ];
3551 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3552 return $clauses;
3553 }
3554
3555 /**
3556 * Get any existing duplicate contacts based on the input parameters.
3557 *
3558 * @param array $input
3559 * Input parameters to be matched.
3560 * @param string $contactType
3561 * @param string $rule
3562 * - Supervised
3563 * - Unsupervised
3564 * @param $excludedContactIDs
3565 * An array of ids not to be included in the results.
3566 * @param bool $checkPermissions
3567 * @param int $ruleGroupID
3568 * ID of the rule group to be used if an override is desirable.
3569 * @param array $contextParams
3570 * The context if relevant, eg. ['event_id' => X]
3571 *
3572 * @return array
3573 */
3574 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3575 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3576 $dedupeParams['check_permission'] = $checkPermissions;
3577 $dedupeParams['contact_type'] = $contactType;
3578 $dedupeParams['rule'] = $rule;
3579 $dedupeParams['rule_group_id'] = $ruleGroupID;
3580 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3581 $dedupeResults['ids'] = [];
3582 $dedupeResults['handled'] = FALSE;
3583 CRM_Utils_Hook::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3584 if (!$dedupeResults['handled']) {
3585 $dedupeResults['ids'] = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3586 }
3587 return $dedupeResults['ids'];
3588 }
3589
3590 /**
3591 * Get the first duplicate contacts based on the input parameters.
3592 *
3593 * @param array $input
3594 * Input parameters to be matched.
3595 * @param string $contactType
3596 * @param string $rule
3597 * - Supervised
3598 * - Unsupervised
3599 * @param $excludedContactIDs
3600 * An array of ids not to be included in the results.
3601 * @param bool $checkPermissions
3602 * @param int $ruleGroupID
3603 * ID of the rule group to be used if an override is desirable.
3604 * @param array $contextParams
3605 * The context if relevant, eg. ['event_id' => X]
3606 *
3607 * @return int|null
3608 */
3609 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3610 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3611 if (empty($ids)) {
3612 return NULL;
3613 }
3614 return $ids[0];
3615 }
3616
3617 /**
3618 * Check if a field is associated with an entity that has a location type.
3619 *
3620 * (ie. is an address, phone, email etc field).
3621 *
3622 * @param string $fieldTitle
3623 * Title of the field (not the name - create a new function for that if required).
3624 *
3625 * @return bool
3626 */
3627 public static function isFieldHasLocationType($fieldTitle) {
3628 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3629 if ($field['title'] === $fieldTitle) {
3630 return $field['hasLocationType'] ?? NULL;
3631 }
3632 }
3633 return FALSE;
3634 }
3635
3636 /**
3637 * @param array $appendProfiles
3638 * Name of profile(s) to append to each link.
3639 *
3640 * @return array
3641 */
3642 public static function getEntityRefCreateLinks($appendProfiles = []) {
3643 // You'd think that "create contacts" would be the permission to check,
3644 // But new contact popups are profile forms and those use their own permissions.
3645 if (!CRM_Core_Permission::check([['profile create', 'profile listings and forms']])) {
3646 return FALSE;
3647 }
3648 $profiles = [];
3649 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $contactType) {
3650 $profiles[] = 'new_' . strtolower($contactType);
3651 }
3652 $retrieved = civicrm_api3('uf_group', 'get', [
3653 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3654 'is_active' => 1,
3655 ]);
3656 $links = $append = [];
3657 if (!empty($retrieved['values'])) {
3658 $icons = [
3659 'individual' => 'fa-user',
3660 'organization' => 'fa-building',
3661 'household' => 'fa-home',
3662 ];
3663 foreach ($retrieved['values'] as $id => $profile) {
3664 if (in_array($profile['name'], $profiles)) {
3665 $links[] = [
3666 'label' => $profile['title'],
3667 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3668 NULL, NULL, FALSE, FALSE, TRUE),
3669 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3670 'icon' => $icons[str_replace('new_', '', $profile['name'])] ?? NULL,
3671 ];
3672 }
3673 else {
3674 $append[] = $id;
3675 }
3676 }
3677 foreach ($append as $id) {
3678 foreach ($links as &$link) {
3679 $link['url'] .= ",$id";
3680 }
3681 }
3682 }
3683 return $links;
3684 }
3685
3686 /**
3687 * @return array
3688 */
3689 public static function getEntityRefFilters() {
3690 return [
3691 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3692 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3693 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3694 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3695 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3696 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3697 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3698 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3699 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3700 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3701 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3702 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3703 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3704 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3705 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3706 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3707 ];
3708 }
3709
3710 }