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