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