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