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