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