Merge pull request #19063 from christianwach/lab-core-2213
[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);
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 $age = CRM_Utils_Date::calculateAge($birthDate);
2603 $values['age']['y'] = $age['years'] ?? NULL;
2604 $values['age']['m'] = $age['months'] ?? NULL;
2605 }
2606 }
2607
2608 $contact->contact_id = $contact->id;
2609
2610 return $contact;
2611 }
2612 return NULL;
2613 }
2614
2615 /**
2616 * Given the component name and returns the count of participation of contact.
2617 *
2618 * @param string $component
2619 * Input component name.
2620 * @param int $contactId
2621 * Input contact id.
2622 * @param string $tableName
2623 * Optional tableName if component is custom group.
2624 *
2625 * @return int
2626 * total number in database
2627 */
2628 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2629 $object = NULL;
2630 switch ($component) {
2631 case 'tag':
2632 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2633
2634 case 'rel':
2635 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2636 CRM_Contact_BAO_Relationship::CURRENT,
2637 0, 1, 0,
2638 NULL, NULL,
2639 TRUE
2640 );
2641 return $result;
2642
2643 case 'group':
2644
2645 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2646
2647 case 'log':
2648 if (CRM_Core_BAO_Log::useLoggingReport()) {
2649 return FALSE;
2650 }
2651 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2652
2653 case 'note':
2654 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2655
2656 case 'contribution':
2657 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2658
2659 case 'membership':
2660 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2661
2662 case 'participant':
2663 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2664
2665 case 'pledge':
2666 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2667
2668 case 'case':
2669 return CRM_Case_BAO_Case::caseCount($contactId);
2670
2671 case 'grant':
2672 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2673
2674 case 'activity':
2675 $input = [
2676 'contact_id' => $contactId,
2677 'admin' => FALSE,
2678 'caseId' => NULL,
2679 'context' => 'activity',
2680 ];
2681 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2682
2683 case 'mailing':
2684 $params = ['contact_id' => $contactId];
2685 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2686
2687 default:
2688 $custom = explode('_', $component);
2689 if ($custom['0'] = 'custom') {
2690 if (!$tableName) {
2691 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2692 }
2693 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2694 return CRM_Core_DAO::singleValueQuery($queryString);
2695 }
2696 }
2697 }
2698
2699 /**
2700 * Update contact greetings if an update has resulted in a custom field change.
2701 *
2702 * @param array $updatedFields
2703 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2704 * @param array $contactParams
2705 * Parameters known about the contact. At minimum array('contact_id' => x).
2706 * Fields in this array will take precedence over DB fields (so far only
2707 * in the case of greeting id fields).
2708 */
2709 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2710 $contactID = $contactParams['contact_id'];
2711 CRM_Contact_BAO_Contact::ensureGreetingParamsAreSet($contactParams);
2712 $tokens = CRM_Contact_BAO_Contact_Utils::getTokensRequiredForContactGreetings($contactParams);
2713 if (!empty($tokens['all']['contact'])) {
2714 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2715 if (!empty($affectedTokens)) {
2716 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2717 $contact = new CRM_Contact_BAO_Contact();
2718 $contact->id = $contactID;
2719 CRM_Contact_BAO_Contact::processGreetings($contact);
2720 }
2721 }
2722 }
2723
2724 /**
2725 * Process greetings and cache.
2726 *
2727 * @param object $contact
2728 * Contact object after save.
2729 */
2730 public static function processGreetings(&$contact) {
2731
2732 //@todo this function does a lot of unnecessary loading.
2733 // ensureGreetingParamsAreSet now makes sure that the contact is
2734 // loaded and using updateGreetingsOnTokenFieldChange
2735 // allows us the possibility of only doing an update if required.
2736
2737 // The contact object has not always required the
2738 // fields that are required to calculate greetings
2739 // so we need to retrieve it again.
2740 if ($contact->_query !== FALSE) {
2741 $contact->find(TRUE);
2742 }
2743
2744 // store object values to an array
2745 $contactDetails = [];
2746 CRM_Core_DAO::storeValues($contact, $contactDetails);
2747 $contactDetails = [[$contact->id => $contactDetails]];
2748
2749 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2750 $updateQueryString = [];
2751
2752 //cache email and postal greeting to greeting display
2753 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2754 $emailGreetingString = $contact->email_greeting_custom;
2755 }
2756 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2757 // the filter value for Individual contact type is set to 1
2758 $filter = [
2759 'contact_type' => $contact->contact_type,
2760 'greeting_type' => 'email_greeting',
2761 ];
2762
2763 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2764 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2765 $updateQueryString[] = " email_greeting_custom = NULL ";
2766 }
2767 else {
2768 if ($contact->email_greeting_custom) {
2769 $updateQueryString[] = " email_greeting_display = NULL ";
2770 }
2771 }
2772
2773 if ($emailGreetingString) {
2774 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2775 $contactDetails,
2776 $contact->id,
2777 'CRM_Contact_BAO_Contact'
2778 );
2779 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2780 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2781 }
2782
2783 //postal greetings
2784 if ($contact->postal_greeting_custom !== 'null' && $contact->postal_greeting_custom) {
2785 $postalGreetingString = $contact->postal_greeting_custom;
2786 }
2787 elseif ($contact->postal_greeting_id !== 'null' && $contact->postal_greeting_id) {
2788 $filter = [
2789 'contact_type' => $contact->contact_type,
2790 'greeting_type' => 'postal_greeting',
2791 ];
2792 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2793 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2794 $updateQueryString[] = " postal_greeting_custom = NULL ";
2795 }
2796 else {
2797 if ($contact->postal_greeting_custom) {
2798 $updateQueryString[] = " postal_greeting_display = NULL ";
2799 }
2800 }
2801
2802 if ($postalGreetingString) {
2803 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2804 $contactDetails,
2805 $contact->id,
2806 'CRM_Contact_BAO_Contact'
2807 );
2808 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2809 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2810 }
2811
2812 // addressee
2813 if ($contact->addressee_custom !== 'null' && $contact->addressee_custom) {
2814 $addresseeString = $contact->addressee_custom;
2815 }
2816 elseif ($contact->addressee_id !== 'null' && $contact->addressee_id) {
2817 $filter = [
2818 'contact_type' => $contact->contact_type,
2819 'greeting_type' => 'addressee',
2820 ];
2821
2822 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2823 $addresseeString = $addressee[$contact->addressee_id];
2824 $updateQueryString[] = " addressee_custom = NULL ";
2825 }
2826 else {
2827 if ($contact->addressee_custom) {
2828 $updateQueryString[] = " addressee_display = NULL ";
2829 }
2830 }
2831
2832 if ($addresseeString) {
2833 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2834 $contactDetails,
2835 $contact->id,
2836 'CRM_Contact_BAO_Contact'
2837 );
2838 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2839 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2840 }
2841
2842 if (!empty($updateQueryString)) {
2843 $updateQueryString = implode(',', $updateQueryString);
2844 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2845 CRM_Core_DAO::executeQuery($queryString);
2846 }
2847 }
2848
2849 /**
2850 * Retrieve loc block ids w/ given condition.
2851 *
2852 * @param int $contactId
2853 * Contact id.
2854 * @param array $criteria
2855 * Key => value pair which should be.
2856 * fulfill by return record ids.
2857 * @param string $condOperator
2858 * Operator use for grouping multiple conditions.
2859 *
2860 * @return array
2861 * loc block ids which fulfill condition.
2862 */
2863 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2864 $locBlockIds = [];
2865 if (!$contactId) {
2866 return $locBlockIds;
2867 }
2868
2869 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2870 $name = strtolower($block);
2871 $className = "CRM_Core_DAO_$block";
2872 $blockDAO = new $className();
2873
2874 // build the condition.
2875 if (is_array($criteria)) {
2876 $fields = $blockDAO->fields();
2877 $conditions = [];
2878 foreach ($criteria as $field => $value) {
2879 if (array_key_exists($field, $fields)) {
2880 $cond = "( $field = $value )";
2881 // value might be zero or null.
2882 if (!$value || strtolower($value) === 'null') {
2883 $cond = "( $field = 0 OR $field IS NULL )";
2884 }
2885 $conditions[] = $cond;
2886 }
2887 }
2888 if (!empty($conditions)) {
2889 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2890 }
2891 }
2892
2893 $blockDAO->contact_id = $contactId;
2894 $blockDAO->find();
2895 while ($blockDAO->fetch()) {
2896 $locBlockIds[$name][] = $blockDAO->id;
2897 }
2898 }
2899
2900 return $locBlockIds;
2901 }
2902
2903 /**
2904 * Build context menu items.
2905 *
2906 * @param int $contactId
2907 *
2908 * @return array
2909 * Array of context menu for logged in user.
2910 */
2911 public static function contextMenu($contactId = NULL) {
2912 $menu = [
2913 'view' => [
2914 'title' => ts('View Contact'),
2915 'weight' => 0,
2916 'ref' => 'view-contact',
2917 'class' => 'no-popup',
2918 'key' => 'view',
2919 'permissions' => ['view all contacts'],
2920 ],
2921 'add' => [
2922 'title' => ts('Edit Contact'),
2923 'weight' => 0,
2924 'ref' => 'edit-contact',
2925 'class' => 'no-popup',
2926 'key' => 'add',
2927 'permissions' => ['edit all contacts'],
2928 ],
2929 'delete' => [
2930 'title' => ts('Delete Contact'),
2931 'weight' => 0,
2932 'ref' => 'delete-contact',
2933 'key' => 'delete',
2934 'permissions' => ['access deleted contacts', 'delete contacts'],
2935 ],
2936 'contribution' => [
2937 'title' => ts('Add Contribution'),
2938 'weight' => 5,
2939 'ref' => 'new-contribution',
2940 'key' => 'contribution',
2941 'tab' => 'contribute',
2942 'component' => 'CiviContribute',
2943 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2944 'reset=1&action=add&context=contribution'
2945 ),
2946 'permissions' => [
2947 'access CiviContribute',
2948 'edit contributions',
2949 ],
2950 ],
2951 'participant' => [
2952 'title' => ts('Register for Event'),
2953 'weight' => 10,
2954 'ref' => 'new-participant',
2955 'key' => 'participant',
2956 'tab' => 'participant',
2957 'component' => 'CiviEvent',
2958 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2959 'permissions' => [
2960 'access CiviEvent',
2961 'edit event participants',
2962 ],
2963 ],
2964 'activity' => [
2965 'title' => ts('Record Activity'),
2966 'weight' => 35,
2967 'ref' => 'new-activity',
2968 'key' => 'activity',
2969 'permissions' => ['edit all contacts'],
2970 ],
2971 'pledge' => [
2972 'title' => ts('Add Pledge'),
2973 'weight' => 15,
2974 'ref' => 'new-pledge',
2975 'key' => 'pledge',
2976 'tab' => 'pledge',
2977 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2978 'reset=1&action=add&context=pledge'
2979 ),
2980 'component' => 'CiviPledge',
2981 'permissions' => [
2982 'access CiviPledge',
2983 'edit pledges',
2984 ],
2985 ],
2986 'membership' => [
2987 'title' => ts('Add Membership'),
2988 'weight' => 20,
2989 'ref' => 'new-membership',
2990 'key' => 'membership',
2991 'tab' => 'member',
2992 'component' => 'CiviMember',
2993 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2994 'reset=1&action=add&context=membership'
2995 ),
2996 'permissions' => [
2997 'access CiviMember',
2998 'edit memberships',
2999 ],
3000 ],
3001 'case' => [
3002 'title' => ts('Add Case'),
3003 'weight' => 25,
3004 'ref' => 'new-case',
3005 'key' => 'case',
3006 'tab' => 'case',
3007 'component' => 'CiviCase',
3008 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3009 'permissions' => ['add cases'],
3010 ],
3011 'grant' => [
3012 'title' => ts('Add Grant'),
3013 'weight' => 26,
3014 'ref' => 'new-grant',
3015 'key' => 'grant',
3016 'tab' => 'grant',
3017 'component' => 'CiviGrant',
3018 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
3019 'reset=1&action=add&context=grant'
3020 ),
3021 'permissions' => ['edit grants'],
3022 ],
3023 'rel' => [
3024 'title' => ts('Add Relationship'),
3025 'weight' => 30,
3026 'ref' => 'new-relationship',
3027 'key' => 'rel',
3028 'tab' => 'rel',
3029 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
3030 'reset=1&action=add'
3031 ),
3032 'permissions' => ['edit all contacts'],
3033 ],
3034 'note' => [
3035 'title' => ts('Add Note'),
3036 'weight' => 40,
3037 'ref' => 'new-note',
3038 'key' => 'note',
3039 'tab' => 'note',
3040 'class' => 'medium-popup',
3041 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
3042 'reset=1&action=add'
3043 ),
3044 'permissions' => ['edit all contacts'],
3045 ],
3046 'email' => [
3047 'title' => ts('Send an Email'),
3048 'weight' => 45,
3049 'ref' => 'new-email',
3050 'key' => 'email',
3051 'permissions' => ['view all contacts'],
3052 ],
3053 'group' => [
3054 'title' => ts('Add to Group'),
3055 'weight' => 50,
3056 'ref' => 'group-add-contact',
3057 'key' => 'group',
3058 'tab' => 'group',
3059 'permissions' => ['edit groups'],
3060 ],
3061 'tag' => [
3062 'title' => ts('Tag Contact'),
3063 'weight' => 55,
3064 'ref' => 'tag-contact',
3065 'key' => 'tag',
3066 'tab' => 'tag',
3067 'permissions' => ['edit all contacts'],
3068 ],
3069 ];
3070
3071 $menu['otherActions'] = [
3072 'print' => [
3073 'title' => ts('Print Summary'),
3074 'description' => ts('Printer-friendly view of this page.'),
3075 'weight' => 5,
3076 'ref' => 'crm-contact-print',
3077 'key' => 'print',
3078 'tab' => 'print',
3079 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3080 "reset=1&print=1"
3081 ),
3082 'class' => 'print',
3083 'icon' => 'crm-i fa-print',
3084 ],
3085 'vcard' => [
3086 'title' => ts('vCard'),
3087 'description' => ts('vCard record for this contact.'),
3088 'weight' => 10,
3089 'ref' => 'crm-contact-vcard',
3090 'key' => 'vcard',
3091 'tab' => 'vcard',
3092 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3093 "reset=1"
3094 ),
3095 'class' => 'vcard',
3096 'icon' => 'crm-i fa-list-alt',
3097 ],
3098 ];
3099
3100 if (CRM_Core_Permission::check('access Contact Dashboard')) {
3101 $menu['otherActions']['dashboard'] = [
3102 'title' => ts('Contact Dashboard'),
3103 'description' => ts('Contact Dashboard'),
3104 'weight' => 15,
3105 'ref' => 'crm-contact-dashboard',
3106 'key' => 'dashboard',
3107 'tab' => 'dashboard',
3108 'class' => 'dashboard',
3109 // NOTE: As an alternative you can also build url on CMS specific way
3110 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3111 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id={$contactId}"),
3112 'icon' => 'crm-i fa-tachometer',
3113 ];
3114 }
3115
3116 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3117 if ($uid) {
3118 $menu['otherActions']['user-record'] = [
3119 'title' => ts('User Record'),
3120 'description' => ts('User Record'),
3121 'weight' => 20,
3122 'ref' => 'crm-contact-user-record',
3123 'key' => 'user-record',
3124 'tab' => 'user-record',
3125 'class' => 'user-record',
3126 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
3127 'icon' => 'crm-i fa-user',
3128 ];
3129 }
3130 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
3131 $menu['otherActions']['user-add'] = [
3132 'title' => ts('Create User Record'),
3133 'description' => ts('Create User Record'),
3134 'weight' => 25,
3135 'ref' => 'crm-contact-user-add',
3136 'key' => 'user-add',
3137 'tab' => 'user-add',
3138 'class' => 'user-add',
3139 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3140 'icon' => 'crm-i fa-user-plus',
3141 ];
3142 }
3143
3144 CRM_Utils_Hook::summaryActions($menu, $contactId);
3145 //1. check for component is active.
3146 //2. check for user permissions.
3147 //3. check for acls.
3148 //3. edit and view contact are directly accessible to user.
3149
3150 $aclPermissionedTasks = [
3151 'view-contact',
3152 'edit-contact',
3153 'new-activity',
3154 'new-email',
3155 'group-add-contact',
3156 'tag-contact',
3157 'delete-contact',
3158 ];
3159 $corePermission = CRM_Core_Permission::getPermission();
3160
3161 $contextMenu = [];
3162 foreach ($menu as $key => $values) {
3163 if ($key !== 'otherActions') {
3164
3165 // user does not have necessary permissions.
3166 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3167 continue;
3168 }
3169 // build directly accessible action menu.
3170 if (in_array($values['ref'], [
3171 'view-contact',
3172 'edit-contact',
3173 ])) {
3174 $contextMenu['primaryActions'][$key] = [
3175 'title' => $values['title'],
3176 'ref' => $values['ref'],
3177 'class' => $values['class'] ?? NULL,
3178 'key' => $values['key'],
3179 ];
3180 continue;
3181 }
3182
3183 // finally get menu item for -more- action widget.
3184 $contextMenu['moreActions'][$values['weight']] = [
3185 'title' => $values['title'],
3186 'ref' => $values['ref'],
3187 'href' => $values['href'] ?? NULL,
3188 'tab' => $values['tab'] ?? NULL,
3189 'class' => $values['class'] ?? NULL,
3190 'key' => $values['key'],
3191 ];
3192 }
3193 else {
3194 foreach ($values as $value) {
3195 // user does not have necessary permissions.
3196 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3197 continue;
3198 }
3199
3200 // finally get menu item for -more- action widget.
3201 $contextMenu['otherActions'][$value['weight']] = [
3202 'title' => $value['title'],
3203 'ref' => $value['ref'],
3204 'href' => $value['href'] ?? NULL,
3205 'tab' => $value['tab'] ?? NULL,
3206 'class' => $value['class'] ?? NULL,
3207 'icon' => $value['icon'] ?? NULL,
3208 'key' => $value['key'],
3209 ];
3210 }
3211 }
3212 }
3213
3214 ksort($contextMenu['moreActions']);
3215 ksort($contextMenu['otherActions']);
3216
3217 return $contextMenu;
3218 }
3219
3220 /**
3221 * Check if user has permissions to access items in action menu.
3222 *
3223 * @param array $aclPermissionedTasks
3224 * Array containing ACL related tasks.
3225 * @param string $corePermission
3226 * The permission of the user (edit or view or null).
3227 * @param array $menuOptions
3228 * Array containing params of the menu (title, href, etc).
3229 *
3230 * @return bool
3231 * TRUE if user has all permissions, FALSE if otherwise.
3232 */
3233 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3234 $componentName = $menuOptions['component'] ?? NULL;
3235
3236 // if component action - make sure component is enable.
3237 if ($componentName && !in_array($componentName, CRM_Core_Config::singleton()->enableComponents)) {
3238 return FALSE;
3239 }
3240
3241 // make sure user has all required permissions.
3242 $hasAllPermissions = FALSE;
3243
3244 $permissions = $menuOptions['permissions'] ?? NULL;
3245 if (!is_array($permissions) || empty($permissions)) {
3246 $hasAllPermissions = TRUE;
3247 }
3248
3249 // iterate for required permissions in given permissions array.
3250 if (!$hasAllPermissions) {
3251 $hasPermissions = 0;
3252 foreach ($permissions as $permission) {
3253 if (CRM_Core_Permission::check($permission)) {
3254 $hasPermissions++;
3255 }
3256 }
3257
3258 if (count($permissions) == $hasPermissions) {
3259 $hasAllPermissions = TRUE;
3260 }
3261
3262 // if still user does not have required permissions, check acl.
3263 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3264 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3265 $corePermission == CRM_Core_Permission::EDIT
3266 ) {
3267 $hasAllPermissions = TRUE;
3268 }
3269 elseif (in_array($menuOptions['ref'], [
3270 'new-email',
3271 ])) {
3272 // grant permissions for these tasks.
3273 $hasAllPermissions = TRUE;
3274 }
3275 }
3276 }
3277
3278 return $hasAllPermissions;
3279 }
3280
3281 /**
3282 * Retrieve display name of contact that address is shared.
3283 *
3284 * This is based on $masterAddressId or $contactId .
3285 *
3286 * @param int $masterAddressId
3287 * Master id.
3288 * @param int $contactId
3289 * Contact id. (deprecated - do not use)
3290 *
3291 * @return string|null
3292 * the found display name or null.
3293 */
3294 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3295 $masterDisplayName = NULL;
3296 if (!$masterAddressId) {
3297 return $masterDisplayName;
3298 }
3299
3300 $sql = "
3301 SELECT display_name from civicrm_contact
3302 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3303 WHERE civicrm_address.id = " . $masterAddressId;
3304
3305 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3306 return $masterDisplayName;
3307 }
3308
3309 /**
3310 * Get the creation/modification times for a contact.
3311 *
3312 * @param int $contactId
3313 *
3314 * @return array
3315 * Dates - ('created_date' => $, 'modified_date' => $)
3316 */
3317 public static function getTimestamps($contactId) {
3318 $timestamps = CRM_Core_DAO::executeQuery(
3319 'SELECT created_date, modified_date
3320 FROM civicrm_contact
3321 WHERE id = %1',
3322 [
3323 1 => [$contactId, 'Integer'],
3324 ]
3325 );
3326 if ($timestamps->fetch()) {
3327 return [
3328 'created_date' => $timestamps->created_date,
3329 'modified_date' => $timestamps->modified_date,
3330 ];
3331 }
3332 else {
3333 return NULL;
3334 }
3335 }
3336
3337 /**
3338 * Get a list of triggers for the contact table.
3339 *
3340 * @param $info
3341 * @param null $tableName
3342 *
3343 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3344 *
3345 * @see hook_civicrm_triggerInfo
3346 * @see CRM_Core_DAO::triggerRebuild
3347 */
3348 public static function triggerInfo(&$info, $tableName = NULL) {
3349
3350 // Modifications to these records should update the contact timestamps.
3351 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3352 ->setRelations([
3353 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3354 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3355 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3356 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3357 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3358 ])
3359 ->alterTriggerInfo($info, $tableName);
3360
3361 // Update phone table to populate phone_numeric field
3362 if (!$tableName || $tableName == 'civicrm_phone') {
3363 // Define stored sql function needed for phones
3364 $sqlTriggers = Civi::service('sql_triggers');
3365 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3366 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3367 $info[] = [
3368 'table' => ['civicrm_phone'],
3369 'when' => 'BEFORE',
3370 'event' => ['INSERT', 'UPDATE'],
3371 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3372 ];
3373 }
3374 }
3375
3376 /**
3377 * Check if contact is being used in civicrm_domain based on $contactId.
3378 *
3379 * @param int $contactId
3380 * Contact id.
3381 *
3382 * @return bool
3383 * true if present else false.
3384 */
3385 public static function checkDomainContact($contactId) {
3386 if (!$contactId) {
3387 return FALSE;
3388 }
3389 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3390
3391 if ($domainId) {
3392 return TRUE;
3393 }
3394 else {
3395 return FALSE;
3396 }
3397 }
3398
3399 /**
3400 * Get options for a given contact field.
3401 *
3402 * @param string $fieldName
3403 * @param string $context
3404 * @param array $props
3405 * whatever is known about this dao object.
3406 *
3407 * @return array|bool
3408 * @see CRM_Core_DAO::buildOptions
3409 *
3410 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3411 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3412 *
3413 * @see CRM_Core_DAO::buildOptionsContext
3414 */
3415 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3416 $params = [];
3417 // Special logic for fields whose options depend on context or properties
3418 switch ($fieldName) {
3419 case 'contact_sub_type':
3420 if (!empty($props['contact_type'])) {
3421 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3422 }
3423 break;
3424
3425 case 'contact_type':
3426 if ($context == 'search') {
3427 // CRM-15495 - EntityRef filters and basic search forms expect this format
3428 // FIXME: Search builder does not
3429 return CRM_Contact_BAO_ContactType::getSelectElements();
3430 }
3431 break;
3432
3433 // The contact api supports some related entities so we'll honor that by fetching their options
3434 case 'group_id':
3435 case 'group':
3436 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3437
3438 case 'tag_id':
3439 case 'tag':
3440 $props['entity_table'] = 'civicrm_contact';
3441 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3442
3443 case 'state_province_id':
3444 case 'state_province':
3445 case 'state_province_name':
3446 case 'country_id':
3447 case 'country':
3448 case 'county_id':
3449 case 'worldregion':
3450 case 'worldregion_id':
3451 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3452
3453 }
3454 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3455 }
3456
3457 /**
3458 * Delete a contact-related object that has an 'is_primary' field.
3459 *
3460 * Ensures that is_primary gets assigned to another object if available
3461 * Also calls pre/post hooks
3462 *
3463 * @param string $type
3464 * @param int $id
3465 *
3466 * @return bool
3467 */
3468 public static function deleteObjectWithPrimary($type, $id) {
3469 if (!$id || !is_numeric($id)) {
3470 return FALSE;
3471 }
3472 $daoName = "CRM_Core_DAO_$type";
3473 $obj = new $daoName();
3474 $obj->id = $id;
3475 $obj->find();
3476
3477 if ($obj->fetch()) {
3478 CRM_Utils_Hook::pre('delete', $type, $id);
3479 $contactId = $obj->contact_id;
3480 $obj->delete();
3481 }
3482 else {
3483 return FALSE;
3484 }
3485 // is_primary is only relavent if this field belongs to a contact
3486 if ($contactId) {
3487 $dao = new $daoName();
3488 $dao->contact_id = $contactId;
3489 $dao->is_primary = 1;
3490 // Pick another record to be primary (if one isn't already)
3491 if (!$dao->find(TRUE)) {
3492 $dao->is_primary = 0;
3493 $dao->find();
3494 if ($dao->fetch()) {
3495 $dao->is_primary = 1;
3496 $dao->save();
3497 if ($type === 'Email') {
3498 CRM_Core_BAO_UFMatch::updateUFName($dao->contact_id);
3499 }
3500 }
3501 }
3502 }
3503 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3504 return TRUE;
3505 }
3506
3507 /**
3508 * @inheritDoc
3509 */
3510 public function addSelectWhereClause() {
3511 // We always return an array with these keys, even if they are empty,
3512 // because this tells the query builder that we have considered these fields for acls
3513 $clauses = [
3514 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3515 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? [] : ['!= 1'],
3516 ];
3517 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3518 return $clauses;
3519 }
3520
3521 /**
3522 * Get any existing duplicate contacts based on the input parameters.
3523 *
3524 * @param array $input
3525 * Input parameters to be matched.
3526 * @param string $contactType
3527 * @param string $rule
3528 * - Supervised
3529 * - Unsupervised
3530 * @param $excludedContactIDs
3531 * An array of ids not to be included in the results.
3532 * @param bool $checkPermissions
3533 * @param int $ruleGroupID
3534 * ID of the rule group to be used if an override is desirable.
3535 * @param array $contextParams
3536 * The context if relevant, eg. ['event_id' => X]
3537 *
3538 * @return array
3539 */
3540 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3541 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3542 $dedupeParams['check_permission'] = $checkPermissions;
3543 $dedupeParams['contact_type'] = $contactType;
3544 $dedupeParams['rule'] = $rule;
3545 $dedupeParams['rule_group_id'] = $ruleGroupID;
3546 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3547 $dedupeResults['ids'] = [];
3548 $dedupeResults['handled'] = FALSE;
3549 CRM_Utils_Hook::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3550 if (!$dedupeResults['handled']) {
3551 $dedupeResults['ids'] = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3552 }
3553 return $dedupeResults['ids'];
3554 }
3555
3556 /**
3557 * Get the first duplicate contacts based on the input parameters.
3558 *
3559 * @param array $input
3560 * Input parameters to be matched.
3561 * @param string $contactType
3562 * @param string $rule
3563 * - Supervised
3564 * - Unsupervised
3565 * @param $excludedContactIDs
3566 * An array of ids not to be included in the results.
3567 * @param bool $checkPermissions
3568 * @param int $ruleGroupID
3569 * ID of the rule group to be used if an override is desirable.
3570 * @param array $contextParams
3571 * The context if relevant, eg. ['event_id' => X]
3572 *
3573 * @return int|null
3574 */
3575 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3576 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3577 if (empty($ids)) {
3578 return NULL;
3579 }
3580 return $ids[0];
3581 }
3582
3583 /**
3584 * Check if a field is associated with an entity that has a location type.
3585 *
3586 * (ie. is an address, phone, email etc field).
3587 *
3588 * @param string $fieldTitle
3589 * Title of the field (not the name - create a new function for that if required).
3590 *
3591 * @return bool
3592 */
3593 public static function isFieldHasLocationType($fieldTitle) {
3594 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3595 if ($field['title'] === $fieldTitle) {
3596 return $field['hasLocationType'] ?? NULL;
3597 }
3598 }
3599 return FALSE;
3600 }
3601
3602 /**
3603 * @param array $appendProfiles
3604 * Name of profile(s) to append to each link.
3605 *
3606 * @return array
3607 */
3608 public static function getEntityRefCreateLinks($appendProfiles = []) {
3609 // You'd think that "create contacts" would be the permission to check,
3610 // But new contact popups are profile forms and those use their own permissions.
3611 if (!CRM_Core_Permission::check([['profile create', 'profile listings and forms']])) {
3612 return FALSE;
3613 }
3614 $profiles = [];
3615 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $contactType) {
3616 $profiles[] = 'new_' . strtolower($contactType);
3617 }
3618 $retrieved = civicrm_api3('uf_group', 'get', [
3619 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3620 'is_active' => 1,
3621 ]);
3622 $links = $append = [];
3623 if (!empty($retrieved['values'])) {
3624 $icons = [
3625 'individual' => 'fa-user',
3626 'organization' => 'fa-building',
3627 'household' => 'fa-home',
3628 ];
3629 foreach ($retrieved['values'] as $id => $profile) {
3630 if (in_array($profile['name'], $profiles)) {
3631 $links[] = [
3632 'label' => $profile['title'],
3633 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3634 NULL, NULL, FALSE, FALSE, TRUE),
3635 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3636 'icon' => $icons[str_replace('new_', '', $profile['name'])] ?? NULL,
3637 ];
3638 }
3639 else {
3640 $append[] = $id;
3641 }
3642 }
3643 foreach ($append as $id) {
3644 foreach ($links as &$link) {
3645 $link['url'] .= ",$id";
3646 }
3647 }
3648 }
3649 return $links;
3650 }
3651
3652 /**
3653 * @return array
3654 */
3655 public static function getEntityRefFilters() {
3656 return [
3657 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3658 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3659 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3660 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3661 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3662 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3663 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3664 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3665 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3666 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3667 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3668 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3669 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3670 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3671 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3672 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3673 ];
3674 }
3675
3676 }