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