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