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