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