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