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