3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This is class to handle address related functions.
21 class CRM_Core_BAO_Address
extends CRM_Core_DAO_Address
{
22 use CRM_Contact_AccessTrait
;
25 * Takes an associative array and creates a address.
27 * @param array $params
28 * (reference ) an assoc array of name/value pairs.
29 * @param bool $fixAddress
30 * True if you need to fix (format) address values.
31 * before inserting in db
33 * @return array|NULL|self
34 * array of created address
36 public static function create(&$params, $fixAddress = TRUE) {
37 if (!isset($params['address']) ||
!is_array($params['address'])) {
38 return self
::add($params, $fixAddress);
40 CRM_Core_Error
::deprecatedFunctionWarning('Use legacyCreate if not doing a single crud action');
41 return self
::legacyCreate($params, $fixAddress);
45 * Takes an associative array and adds address.
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param bool $fixAddress
50 * True if you need to fix (format) address values.
51 * before inserting in db
53 * @return CRM_Core_BAO_Address|null
55 public static function add(&$params, $fixAddress = FALSE) {
57 $address = new CRM_Core_DAO_Address();
58 $checkPermissions = $params['check_permissions'] ??
TRUE;
60 // fixAddress mode to be done
62 CRM_Core_BAO_Address
::fixAddress($params);
65 $hook = empty($params['id']) ?
'create' : 'edit';
66 CRM_Utils_Hook
::pre($hook, 'Address', CRM_Utils_Array
::value('id', $params), $params);
68 CRM_Core_BAO_Block
::handlePrimary($params, get_class());
69 CRM_Core_BAO_Block
::handleBilling($params, get_class());
71 // (prevent chaining 1 and 3) CRM-21214
72 if (isset($params['master_id']) && !CRM_Utils_System
::isNull($params['master_id'])) {
73 self
::fixSharedAddress($params);
76 $address->copyValues($params);
80 // first get custom field from master address if any
81 if (isset($params['master_id']) && !CRM_Utils_System
::isNull($params['master_id'])) {
82 $address->copyCustomFields($params['master_id'], $address->id
, $hook);
85 if (isset($params['custom'])) {
86 $addressCustom = $params['custom'];
89 $customFields = CRM_Core_BAO_CustomField
::getFields('Address', FALSE, TRUE, NULL, NULL,
90 FALSE, FALSE, $checkPermissions ? CRM_Core_Permission
::EDIT
: FALSE);
92 if (!empty($customFields)) {
93 $addressCustom = CRM_Core_BAO_CustomField
::postProcess($params,
101 if (!empty($addressCustom)) {
102 CRM_Core_BAO_CustomValueTable
::store($addressCustom, 'civicrm_address', $address->id
, $hook);
105 // call the function to sync shared address and create relationships
106 // if address is already shared, share master_id with all children and update relationships accordingly
107 // (prevent chaining 2) CRM-21214
108 self
::processSharedAddress($address->id
, $params, $hook);
110 // lets call the post hook only after we've done all the follow on processing
111 CRM_Utils_Hook
::post($hook, 'Address', $address->id
, $address);
118 * Format the address params to have reasonable values.
120 * @param array $params
121 * (reference ) an assoc array of name/value pairs.
123 public static function fixAddress(&$params) {
124 if (!empty($params['billing_street_address'])) {
125 //Check address is coming from online contribution / registration page
128 'street_address' => 'billing_street_address',
129 'city' => 'billing_city',
130 'postal_code' => 'billing_postal_code',
131 'state_province' => 'billing_state_province',
132 'state_province_id' => 'billing_state_province_id',
133 'country' => 'billing_country',
134 'country_id' => 'billing_country_id',
137 foreach ($billing as $key => $val) {
138 if ($value = CRM_Utils_Array
::value($val, $params)) {
139 if (!empty($params[$key])) {
140 unset($params[$val]);
143 //add new key and removed old
144 $params[$key] = $value;
145 unset($params[$val]);
151 /* Split the zip and +4, if it's in US format */
152 if (!empty($params['postal_code']) &&
153 preg_match('/^(\d{4,5})[+-](\d{4})$/',
154 $params['postal_code'],
158 $params['postal_code'] = $match[1];
159 $params['postal_code_suffix'] = $match[2];
162 // add country id if not set
163 if ((!isset($params['country_id']) ||
!is_numeric($params['country_id'])) &&
164 isset($params['country'])
166 $country = new CRM_Core_DAO_Country();
167 $country->name
= $params['country'];
168 if (!$country->find(TRUE)) {
169 $country->name
= NULL;
170 $country->iso_code
= $params['country'];
171 $country->find(TRUE);
173 $params['country_id'] = $country->id
;
176 // add state_id if state is set
177 if ((!isset($params['state_province_id']) ||
!is_numeric($params['state_province_id']))
178 && isset($params['state_province'])
180 if (!empty($params['state_province'])) {
181 $state_province = new CRM_Core_DAO_StateProvince();
182 $state_province->name
= $params['state_province'];
184 // add country id if present
185 if (!empty($params['country_id'])) {
186 $state_province->country_id
= $params['country_id'];
189 if (!$state_province->find(TRUE)) {
190 unset($state_province->name
);
191 $state_province->abbreviation
= $params['state_province'];
192 $state_province->find(TRUE);
194 $params['state_province_id'] = $state_province->id
;
195 if (empty($params['country_id'])) {
196 // set this here since we have it
197 $params['country_id'] = $state_province->country_id
;
201 $params['state_province_id'] = 'null';
205 // add county id if county is set
207 if ((!isset($params['county_id']) ||
!is_numeric($params['county_id']))
208 && isset($params['county']) && !empty($params['county'])
210 $county = new CRM_Core_DAO_County();
211 $county->name
= $params['county'];
213 if (isset($params['state_province_id'])) {
214 $county->state_province_id
= $params['state_province_id'];
217 if ($county->find(TRUE)) {
218 $params['county_id'] = $county->id
;
222 // currently copy values populates empty fields with the string "null"
223 // and hence need to check for the string null
224 if (isset($params['state_province_id']) &&
225 is_numeric($params['state_province_id']) &&
226 (!isset($params['country_id']) ||
empty($params['country_id']))
228 // since state id present and country id not present, hence lets populate it
229 // jira issue http://issues.civicrm.org/jira/browse/CRM-56
230 $params['country_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_StateProvince',
231 $params['state_province_id'],
236 //special check to ignore non numeric values if they are not
237 //detected by formRule(sometimes happens due to internet latency), also allow user to unselect state/country
238 if (isset($params['state_province_id'])) {
239 if (empty($params['state_province_id'])) {
240 $params['state_province_id'] = 'null';
242 elseif (!is_numeric($params['state_province_id']) ||
243 ((int ) $params['state_province_id'] < 1000)
245 // CRM-3393 ( the hacky 1000 check)
246 $params['state_province_id'] = 'null';
250 if (isset($params['country_id'])) {
251 if (empty($params['country_id'])) {
252 $params['country_id'] = 'null';
254 elseif (!is_numeric($params['country_id']) ||
255 ((int ) $params['country_id'] < 1000)
257 // CRM-3393 ( the hacky 1000 check)
258 $params['country_id'] = 'null';
262 // add state and country names from the ids
263 if (isset($params['state_province_id']) && is_numeric($params['state_province_id'])) {
264 $params['state_province'] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($params['state_province_id']);
267 if (isset($params['country_id']) && is_numeric($params['country_id'])) {
268 $params['country'] = CRM_Core_PseudoConstant
::country($params['country_id']);
271 $asp = Civi
::settings()->get('address_standardization_provider');
272 // clean up the address via USPS web services if enabled
273 if ($asp === 'USPS' &&
274 $params['country_id'] == 1228
276 CRM_Utils_Address_USPS
::checkAddress($params);
278 // do street parsing again if enabled, since street address might have changed
279 $parseStreetAddress = CRM_Utils_Array
::value(
280 'street_address_parsing',
281 CRM_Core_BAO_Setting
::valueOptions(
282 CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
288 if ($parseStreetAddress && !empty($params['street_address'])) {
289 foreach (['street_number', 'street_name', 'street_unit', 'street_number_suffix'] as $fld) {
290 unset($params[$fld]);
292 // main parse string.
293 $parseString = $params['street_address'] ??
NULL;
294 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
296 // merge parse address in to main address block.
297 $params = array_merge($params, $parsedFields);
300 // skip_geocode is an optional parameter through the api.
301 // manual_geo_code is on the contact edit form. They do the same thing....
302 if (empty($params['skip_geocode']) && empty($params['manual_geo_code'])) {
303 self
::addGeocoderData($params);
309 * Check if there is data to create the object.
311 * @param array $params
312 * (reference ) an assoc array of name/value pairs.
316 public static function dataExists(&$params) {
317 //check if location type is set if not return false
318 if (!isset($params['location_type_id'])) {
322 $config = CRM_Core_Config
::singleton();
323 foreach ($params as $name => $value) {
324 if (in_array($name, [
335 elseif (!CRM_Utils_System
::isNull($value)) {
336 // name could be country or country id
337 if (substr($name, 0, 7) == 'country') {
338 // make sure its different from the default country
340 $defaultCountry = CRM_Core_BAO_Country
::defaultContactCountry();
342 $defaultCountryName = CRM_Core_BAO_Country
::defaultContactCountryName();
344 if ($defaultCountry) {
345 if ($value == $defaultCountry ||
346 $value == $defaultCountryName ||
347 $value == $config->defaultContactCountry
356 // return if null default
370 * Given the list of params in the params array, fetch the object
371 * and store the values in the values array
373 * @param array $entityBlock
374 * Associated array of fields.
375 * @param bool $microformat
376 * If microformat output is required.
377 * @param int|string $fieldName conditional field name
380 * array with address fields
382 public static function &getValues($entityBlock, $microformat = FALSE, $fieldName = 'contact_id') {
383 if (empty($entityBlock)) {
387 $address = new CRM_Core_BAO_Address();
389 if (empty($entityBlock['entity_table'])) {
390 $address->$fieldName = $entityBlock[$fieldName] ??
NULL;
394 $addressIds = self
::allEntityAddress($entityBlock);
396 if (!empty($addressIds[1])) {
397 $address->id
= $addressIds[1];
403 if (isset($entityBlock['is_billing']) && $entityBlock['is_billing'] == 1) {
404 $address->orderBy('is_billing desc, id');
407 //get primary address as a first block.
408 $address->orderBy('is_primary desc, id');
413 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
415 while ($address->fetch()) {
416 // deprecate reference.
418 foreach (['state', 'state_name', 'country', 'world_region'] as $fld) {
419 if (isset($address->$fld)) {
420 unset($address->$fld);
424 $stree = $address->street_address
;
426 CRM_Core_DAO
::storeValues($address, $values);
428 // add state and country information: CRM-369
429 if (!empty($address->location_type_id
)) {
430 $values['location_type'] = $locationTypes[$address->location_type_id
] ??
NULL;
432 if (!empty($address->state_province_id
)) {
433 $address->state
= CRM_Core_PseudoConstant
::stateProvinceAbbreviation($address->state_province_id
, FALSE);
434 $address->state_name
= CRM_Core_PseudoConstant
::stateProvince($address->state_province_id
, FALSE);
435 $values['state_province_abbreviation'] = $address->state
;
436 $values['state_province'] = $address->state_name
;
439 if (!empty($address->country_id
)) {
440 $address->country
= CRM_Core_PseudoConstant
::country($address->country_id
);
441 $values['country'] = $address->country
;
444 $regionId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Country', $address->country_id
, 'region_id');
445 $values['world_region'] = CRM_Core_PseudoConstant
::worldregion($regionId);
448 $address->addDisplay($microformat);
450 $values['display'] = $address->display
;
451 $values['display_text'] = $address->display_text
;
453 if (isset($address->master_id
) && !CRM_Utils_System
::isNull($address->master_id
)) {
454 $values['use_shared_address'] = 1;
457 $addresses[$count] = $values;
459 //There should never be more than one primary blocks, hence set is_primary = 0 other than first
460 // Calling functions expect the key is_primary to be set, so do not unset it here!
462 $addresses[$count]['is_primary'] = 0;
472 * Add the formatted address to $this-> display.
474 * @param bool $microformat
475 * Unexplained parameter that I've always wondered about.
477 public function addDisplay($microformat = FALSE) {
479 // added this for CRM 1200
480 'address_id' => $this->id
,
482 'address_name' => str_replace('\ 1', ' ', ($this->name ??
'')),
483 'street_address' => $this->street_address
,
484 'supplemental_address_1' => $this->supplemental_address_1
,
485 'supplemental_address_2' => $this->supplemental_address_2
,
486 'supplemental_address_3' => $this->supplemental_address_3
,
487 'city' => $this->city
,
488 'state_province_name' => $this->state_name ??
"",
489 'state_province' => $this->state ??
"",
490 'postal_code' => $this->postal_code ??
"",
491 'postal_code_suffix' => $this->postal_code_suffix ??
"",
492 'country' => $this->country ??
"",
493 'world_region' => $this->world_region ??
"",
496 if (isset($this->county_id
) && $this->county_id
) {
497 $fields['county'] = CRM_Core_PseudoConstant
::county($this->county_id
);
500 $fields['county'] = NULL;
503 $this->display
= CRM_Utils_Address
::format($fields, NULL, $microformat);
504 $this->display_text
= CRM_Utils_Address
::format($fields);
508 * Get all the addresses for a specified contact_id, with the primary address being first
513 * @param bool $updateBlankLocInfo
516 * the array of adrress data
518 public static function allAddress($id, $updateBlankLocInfo = FALSE) {
524 SELECT civicrm_address.id as address_id, civicrm_address.location_type_id as location_type_id
525 FROM civicrm_contact, civicrm_address
526 WHERE civicrm_address.contact_id = civicrm_contact.id AND civicrm_contact.id = %1
527 ORDER BY civicrm_address.is_primary DESC, address_id ASC";
528 $params = [1 => [$id, 'Integer']];
531 $dao = CRM_Core_DAO
::executeQuery($query, $params);
533 while ($dao->fetch()) {
534 if ($updateBlankLocInfo) {
535 $addresses[$count++
] = $dao->address_id
;
538 $addresses[$dao->location_type_id
] = $dao->address_id
;
545 * Get all the addresses for a specified location_block id, with the primary address being first
547 * @param array $entityElements
548 * The array containing entity_id and.
552 * the array of adrress data
554 public static function allEntityAddress(&$entityElements) {
556 if (empty($entityElements)) {
560 $entityId = $entityElements['entity_id'];
561 $entityTable = $entityElements['entity_table'];
564 SELECT civicrm_address.id as address_id
565 FROM civicrm_loc_block loc, civicrm_location_type ltype, civicrm_address, {$entityTable} ev
567 AND loc.id = ev.loc_block_id
568 AND civicrm_address.id IN (loc.address_id, loc.address_2_id)
569 AND ltype.id = civicrm_address.location_type_id
570 ORDER BY civicrm_address.is_primary DESC, civicrm_address.location_type_id DESC, address_id ASC ";
572 $params = [1 => [$entityId, 'Integer']];
573 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
575 while ($dao->fetch()) {
576 $addresses[$locationCount] = $dao->address_id
;
583 * Get address sequence.
586 * Array of address sequence.
588 public static function addressSequence() {
589 $addressSequence = CRM_Utils_Address
::sequence(\Civi
::settings()->get('address_format'));
591 $countryState = $cityPostal = FALSE;
592 foreach ($addressSequence as $key => $field) {
594 in_array($field, ['country', 'state_province']) &&
597 $countryState = TRUE;
598 $addressSequence[$key] = 'country_state_province';
601 in_array($field, ['city', 'postal_code']) &&
605 $addressSequence[$key] = 'city_postal_code';
608 in_array($field, ['country', 'state_province', 'city', 'postal_code'])
610 unset($addressSequence[$key]);
614 return $addressSequence;
618 * Parse given street address string in to street_name,
619 * street_unit, street_number and street_number_suffix
620 * eg "54A Excelsior Ave. Apt 1C", or "917 1/2 Elm Street"
622 * NB: civic street formats for en_CA and fr_CA used by default if those locales are active
623 * otherwise en_US format is default action
625 * @param string $streetAddress
626 * Street address including number and apt.
627 * @param string $locale
628 * Locale used to parse address.
631 * parsed fields values.
633 public static function parseStreetAddress($streetAddress, $locale = NULL) {
634 // use 'en_US' for address parsing if the requested locale is not supported.
635 if (!self
::isSupportedParsingLocale($locale)) {
639 $emptyParseFields = $parseFields = [
642 'street_number' => '',
643 'street_number_suffix' => '',
646 if (empty($streetAddress)) {
650 $streetAddress = trim($streetAddress);
653 if (in_array($locale, ['en_CA', 'fr_CA'])
654 && preg_match('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', $streetAddress, $matches)
656 $parseFields['street_unit'] = $matches[1];
657 // unset from rest of street address
658 $streetAddress = preg_replace('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', '', $streetAddress);
661 // get street number and suffix.
663 //alter street number/suffix handling so that we accept -digit
664 if (preg_match('/^[A-Za-z0-9]+([\S]+)/', $streetAddress, $matches)) {
665 // check that $matches[0] is numeric, else assume no street number
666 if (preg_match('/^(\d+)/', $matches[0])) {
667 $streetNumAndSuffix = $matches[0];
669 // get street number.
671 if (preg_match('/^(\d+)/', $streetNumAndSuffix, $matches)) {
672 $parseFields['street_number'] = $matches[0];
673 $suffix = preg_replace('/^(\d+)/', '', $streetNumAndSuffix);
674 $parseFields['street_number_suffix'] = trim($suffix);
677 // unset from main street address.
678 $streetAddress = preg_replace('/^[A-Za-z0-9]+([\S]+)/', '', $streetAddress);
679 $streetAddress = trim($streetAddress);
682 elseif (preg_match('/^(\d+)/', $streetAddress, $matches)) {
683 $parseFields['street_number'] = $matches[0];
684 // unset from main street address.
685 $streetAddress = preg_replace('/^(\d+)/', '', $streetAddress);
686 $streetAddress = trim($streetAddress);
689 // If street number is too large, we cannot store it.
690 if ($parseFields['street_number'] > CRM_Utils_Type
::INT_MAX
) {
691 return $emptyParseFields;
694 // suffix might be like 1/2
696 if (preg_match('/^\d\/\d/', $streetAddress, $matches)) {
697 $parseFields['street_number_suffix'] .= $matches[0];
699 // unset from main street address.
700 $streetAddress = preg_replace('/^\d+\/\d+/', '', $streetAddress);
701 $streetAddress = trim($streetAddress);
704 // now get the street unit.
705 // supportable street unit formats.
706 $streetUnitFormats = [
749 // overwriting $streetUnitFormats for 'en_CA' and 'fr_CA' locale
750 if (in_array($locale, [
754 $streetUnitFormats = ['APT', 'APP', 'SUITE', 'BUREAU', 'UNIT'];
756 //@todo per CRM-14459 this regex picks up words with the string in them - e.g APT picks up
757 //Captain - presuming fixing regex (& adding test) to ensure a-z does not preced string will fix
758 $streetUnitPreg = '/(' . implode('|\s', $streetUnitFormats) . ')(.+)?/i';
760 if (preg_match($streetUnitPreg, $streetAddress, $matches)) {
761 $parseFields['street_unit'] = trim($matches[0]);
762 $streetAddress = str_replace($matches[0], '', $streetAddress);
763 $streetAddress = trim($streetAddress);
766 // consider remaining string as street name.
767 $parseFields['street_name'] = $streetAddress;
769 //run parsed fields through stripSpaces to clean
770 foreach ($parseFields as $parseField => $value) {
771 $parseFields[$parseField] = CRM_Utils_String
::stripSpaces($value);
773 //CRM-14459 if the field is too long we should assume it didn't get it right & skip rather than allow
775 $fields = CRM_Core_BAO_Address
::fields();
776 foreach ($fields as $fieldname => $field) {
777 if (!empty($field['maxlength']) && strlen(($parseFields[$fieldname] ??
'')) > $field['maxlength']) {
778 return $emptyParseFields;
786 * Determines if the specified locale is
787 * supported by address parsing.
788 * If no locale is specified then it
789 * will check the default configured locale.
791 * locales supported include:
792 * en_US - http://pe.usps.com/cpim/ftp/pubs/pub28/pub28.pdf
793 * en_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp
794 * fr_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-f.asp
795 * NB: common use of comma after street number also supported
797 * @param string $locale
798 * The locale to be checked
802 public static function isSupportedParsingLocale($locale = NULL) {
804 $config = CRM_Core_Config
::singleton();
805 $locale = $config->lcMessages
;
808 $parsingSupportedLocales = ['en_US', 'en_CA', 'fr_CA'];
810 if (in_array($locale, $parsingSupportedLocales)) {
818 * Validate the address fields based on the address options enabled.
819 * in the Address Settings
821 * @param array $fields
822 * An array of importable/exportable contact fields.
825 * an array of contact fields and only the enabled address options
827 public static function validateAddressOptions($fields) {
828 static $addressOptions = NULL;
829 if (!$addressOptions) {
830 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(
831 CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
836 if (is_array($fields) && !empty($fields)) {
837 foreach ($addressOptions as $key => $value) {
838 if (!$value && isset($fields[$key])) {
839 unset($fields[$key]);
847 * Check if current address is used by any other contacts.
849 * @param int $addressId
853 * count of contacts that use this shared address
855 public static function checkContactSharedAddress($addressId) {
856 $query = 'SELECT count(id) FROM civicrm_address WHERE master_id = %1';
857 return CRM_Core_DAO
::singleValueQuery($query, [1 => [$addressId, 'Integer']]);
861 * Check if current address fields are shared with any other address.
863 * @param array $fields
864 * Address fields in profile.
865 * @param int $contactId
869 public static function checkContactSharedAddressFields(&$fields, $contactId) {
870 if (!$contactId ||
!is_array($fields) ||
empty($fields)) {
874 $sharedLocations = [];
880 WHERE contact_id = %1
881 AND master_id IS NOT NULL";
883 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$contactId, 'Positive']]);
884 while ($dao->fetch()) {
885 $sharedLocations[$dao->location_type_id
] = $dao->location_type_id
;
886 if ($dao->is_primary
) {
887 $sharedLocations['Primary'] = 'Primary';
891 //no need to process further.
892 if (empty($sharedLocations)) {
906 'postal_code_suffix',
907 'supplemental_address_1',
908 'supplemental_address_2',
909 'supplemental_address_3',
912 foreach ($fields as $name => & $values) {
913 if (!is_array($values) ||
empty($values)) {
917 $nameVal = explode('-', $values['name']);
918 $fldName = $nameVal[0] ??
NULL;
919 $locType = $nameVal[1] ??
NULL;
920 if (!empty($values['location_type_id'])) {
921 $locType = $values['location_type_id'];
924 if (in_array($fldName, $addressFields) &&
925 in_array($locType, $sharedLocations)
927 $values['is_shared'] = TRUE;
933 * Fix the shared address if address is already shared
934 * or if address will be shared with itself.
936 * @param array $params
937 * Associated array of address params.
939 public static function fixSharedAddress(&$params) {
940 // if address master address is shared, use its master (prevent chaining 1) CRM-21214
941 $masterMasterId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Address', $params['master_id'], 'master_id');
942 if ($masterMasterId > 0) {
943 $params['master_id'] = $masterMasterId;
946 // prevent an endless chain between two shared addresses (prevent chaining 3) CRM-21214
947 if (CRM_Utils_Array
::value('id', $params) == $params['master_id']) {
948 $params['master_id'] = NULL;
949 CRM_Core_Session
::setStatus(ts("You can't connect an address to itself"), '', 'warning');
954 * Update the shared addresses if master address is modified.
956 * @param int $addressId
958 * @param array $params
959 * Associated array of address params.
960 * @param string $parentOperation Operation being taken on the parent entity.
962 public static function processSharedAddress($addressId, $params, $parentOperation = NULL) {
963 $query = 'SELECT id, contact_id FROM civicrm_address WHERE master_id = %1';
964 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$addressId, 'Integer']]);
966 // Default to TRUE if not set to maintain api backward compatibility.
967 $createRelationship = $params['add_relationship'] ??
TRUE;
970 $skipFields = ['is_primary', 'location_type_id', 'is_billing', 'contact_id'];
971 if (isset($params['master_id']) && !CRM_Utils_System
::isNull($params['master_id'])) {
972 if ($createRelationship) {
973 // call the function to create a relationship for the new shared address
974 self
::processSharedAddressRelationship($params['master_id'], $params['contact_id']);
978 // else no new shares will be created, only update shared addresses
979 $skipFields[] = 'master_id';
981 foreach ($skipFields as $value) {
982 unset($params[$value]);
985 $addressDAO = new CRM_Core_DAO_Address();
986 while ($dao->fetch()) {
987 // call the function to update the relationship
988 if ($createRelationship && isset($params['master_id']) && !CRM_Utils_System
::isNull($params['master_id'])) {
989 self
::processSharedAddressRelationship($params['master_id'], $dao->contact_id
);
991 $addressDAO->copyValues($params);
992 $addressDAO->id
= $dao->id
;
994 $addressDAO->copyCustomFields($addressId, $addressDAO->id
, $parentOperation);
999 * Merge contacts with the Same address to get one shared label.
1000 * @param array $rows
1001 * Array[contact_id][contactDetails].
1003 public static function mergeSameAddress(&$rows) {
1004 $uniqueAddress = [];
1005 foreach (array_keys($rows) as $rowID) {
1006 // load complete address as array key
1007 $address = trim($rows[$rowID]['street_address'])
1008 . trim($rows[$rowID]['city'])
1009 . trim($rows[$rowID]['state_province'])
1010 . trim($rows[$rowID]['postal_code'])
1011 . trim($rows[$rowID]['country']);
1012 if (isset($rows[$rowID]['last_name'])) {
1013 $name = $rows[$rowID]['last_name'];
1016 $name = $rows[$rowID]['display_name'];
1021 'first_name' => $rows[$rowID]['first_name'],
1022 'individual_prefix' => $rows[$rowID]['individual_prefix'],
1024 $format = Civi
::settings()->get('display_name_format');
1025 $firstNameWithPrefix = CRM_Utils_Address
::format($formatted, $format, FALSE, FALSE);
1026 $firstNameWithPrefix = trim($firstNameWithPrefix);
1028 // fill uniqueAddress array with last/first name tree
1029 if (isset($uniqueAddress[$address])) {
1030 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name'];
1031 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display'];
1032 // drop unnecessary rows
1033 unset($rows[$rowID]);
1034 // this is the first listing at this address
1037 $uniqueAddress[$address]['ID'] = $rowID;
1038 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name'];
1039 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display'];
1042 foreach ($uniqueAddress as $address => $data) {
1043 // copy data back to $rows
1045 // one last name list per row
1046 foreach ($data['names'] as $last_name => $first_names) {
1051 if (count($first_names) == 1) {
1052 $family = $first_names[current(array_keys($first_names))]['addressee_display'];
1055 // collapse the tree to summarize
1056 $family = trim(implode(" & ", array_keys($first_names)) . " " . $last_name);
1059 $processedNames .= "\n" . $family;
1062 // build display_name string
1063 $processedNames = $family;
1067 $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames;
1072 * Create relationship between contacts who share an address.
1074 * Note that currently we create relationship between
1075 * Individual + Household and Individual + Organization
1077 * @param int $masterAddressId
1078 * Master address id.
1079 * @param int $currentContactId
1080 * Current contact id.
1082 public static function processSharedAddressRelationship($masterAddressId, $currentContactId) {
1083 // get the contact type of contact being edited / created
1084 $currentContactType = CRM_Contact_BAO_Contact
::getContactType($currentContactId);
1086 // if current contact is not of type individual return
1087 if ($currentContactType != 'Individual') {
1091 // get the contact id and contact type of shared contact
1092 // check the contact type of shared contact, return if it is of type Individual
1093 $query = 'SELECT cc.id, cc.contact_type
1094 FROM civicrm_contact cc INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
1097 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$masterAddressId, 'Integer']]);
1100 // master address contact needs to be Household or Organization, otherwise return
1101 if ($dao->contact_type
== 'Individual') {
1104 $sharedContactType = $dao->contact_type
;
1105 $sharedContactId = $dao->id
;
1107 // create relationship between ontacts who share an address
1108 if ($sharedContactType == 'Organization') {
1109 return CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($currentContactId, $sharedContactId);
1112 // get the relationship type id of "Household Member of"
1113 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Household Member of', 'id', 'name_a_b');
1116 throw new CRM_Core_Exception(ts("You seem to have deleted the relationship type 'Household Member of'"));
1120 'is_active' => TRUE,
1121 'relationship_type_id' => $relTypeId,
1122 'contact_id_a' => $currentContactId,
1123 'contact_id_b' => $sharedContactId,
1126 // If already there is a relationship record of $relParam criteria, avoid creating relationship again or else
1127 // it will casue CRM-16588 as the Duplicate Relationship Exception will revert other contact field values on update
1128 if (CRM_Contact_BAO_Relationship
::checkDuplicateRelationship($relParam, $currentContactId, $sharedContactId)) {
1133 // create relationship
1134 civicrm_api3('relationship', 'create', $relParam);
1136 catch (CiviCRM_API3_Exception
$e) {
1137 // We catch and ignore here because this has historically been a best-effort relationship create call.
1138 // presumably it could refuse due to duplication or similar and we would ignore that.
1143 * Check and set the status for shared address delete.
1145 * @param int $addressId
1147 * @param int $contactId
1149 * @param bool $returnStatus
1154 public static function setSharedAddressDeleteStatus($addressId = NULL, $contactId = NULL, $returnStatus = FALSE) {
1155 // check if address that is being deleted has any shared
1157 $entityId = $addressId;
1158 $query = 'SELECT cc.id, cc.display_name
1159 FROM civicrm_contact cc INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
1160 WHERE ca.master_id = %1';
1163 $entityId = $contactId;
1164 $query = 'SELECT cc.id, cc.display_name
1165 FROM civicrm_address ca1
1166 INNER JOIN civicrm_address ca2 ON ca1.id = ca2.master_id
1167 INNER JOIN civicrm_contact cc ON ca2.contact_id = cc.id
1168 WHERE ca1.contact_id = %1';
1171 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$entityId, 'Integer']]);
1174 $sharedContactList = [];
1175 $statusMessage = NULL;
1177 while ($dao->fetch()) {
1178 if (empty($deleteStatus)) {
1179 $deleteStatus[] = ts('The following contact(s) have address records which were shared with the address you removed from this contact. These address records are no longer shared - but they have not been removed or altered.');
1182 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$dao->id}");
1183 $sharedContactList[] = "<a href='{$contactViewUrl}'>{$dao->display_name}</a>";
1184 $deleteStatus[] = "<a href='{$contactViewUrl}'>{$dao->display_name}</a>";
1189 if (!empty($deleteStatus)) {
1190 $statusMessage = implode('<br/>', $deleteStatus) . '<br/>';
1193 if (!$returnStatus) {
1194 CRM_Core_Session
::setStatus($statusMessage, '', 'info');
1198 'contactList' => $sharedContactList,
1199 'count' => $addressCount,
1205 * Call common delete function.
1207 * @see \CRM_Contact_BAO_Contact::on_hook_civicrm_post
1213 public static function del($id) {
1214 return (bool) self
::deleteRecord(['id' => $id]);
1218 * Get options for a given address field.
1219 * @see CRM_Core_DAO::buildOptions
1221 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
1222 * TODO: In context of chainselect, what to return if e.g. a country has no states?
1224 * @param string $fieldName
1225 * @param string $context
1226 * @see CRM_Core_DAO::buildOptionsContext
1227 * @param array $props
1228 * whatever is known about this dao object.
1230 * @return array|bool
1232 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1234 // Special logic for fields whose options depend on context or properties
1235 switch ($fieldName) {
1236 // Filter state_province list based on chosen country or site defaults
1237 case 'state_province_id':
1238 case 'state_province_name':
1239 case 'state_province':
1240 // change $fieldName to DB specific names.
1241 $fieldName = 'state_province_id';
1242 if (empty($props['country_id']) && $context !== 'validate') {
1243 $config = CRM_Core_Config
::singleton();
1244 if (!empty($config->provinceLimit
)) {
1245 $props['country_id'] = $config->provinceLimit
;
1248 $props['country_id'] = $config->defaultContactCountry
;
1251 if (!empty($props['country_id'])) {
1252 if (!CRM_Utils_Rule
::commaSeparatedIntegers(implode(',', (array) $props['country_id']))) {
1253 throw new CRM_Core_Exception(ts('Province limit or default country setting is incorrect'));
1255 $params['condition'] = 'country_id IN (' . implode(',', (array) $props['country_id']) . ')';
1259 // Filter country list based on site defaults
1262 // change $fieldName to DB specific names.
1263 $fieldName = 'country_id';
1264 if ($context != 'get' && $context != 'validate') {
1265 $config = CRM_Core_Config
::singleton();
1266 if (!empty($config->countryLimit
) && is_array($config->countryLimit
)) {
1267 if (!CRM_Utils_Rule
::commaSeparatedIntegers(implode(',', $config->countryLimit
))) {
1268 throw new CRM_Core_Exception(ts('Available Country setting is incorrect'));
1270 $params['condition'] = 'id IN (' . implode(',', $config->countryLimit
) . ')';
1275 // Filter county list based on chosen state
1277 if (!empty($props['state_province_id'])) {
1278 if (!CRM_Utils_Rule
::commaSeparatedIntegers(implode(',', (array) $props['state_province_id']))) {
1279 throw new CRM_Core_Exception(ts('Can only accept Integers for state_province_id filtering'));
1281 $params['condition'] = 'state_province_id IN (' . implode(',', (array) $props['state_province_id']) . ')';
1285 // Not a real field in this entity
1286 case 'world_region':
1288 case 'worldregion_id':
1289 return CRM_Core_BAO_Country
::buildOptions('region_id', $context, $props);
1291 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1295 * Add data from the configured geocoding provider.
1297 * Generally this means latitude & longitude data.
1299 * @param array $params
1301 * TRUE if params could be passed to a provider, else FALSE.
1303 public static function addGeocoderData(&$params) {
1305 $provider = CRM_Utils_GeocodeProvider
::getConfiguredProvider();
1306 $providerExists = TRUE;
1308 catch (CRM_Core_Exception
$e) {
1309 $providerExists = FALSE;
1311 if ($providerExists) {
1312 $provider::format($params);
1314 // core#2379 - Limit geocode length to 14 characters to avoid validation error on save in UI.
1315 foreach (['geo_code_1', 'geo_code_2'] as $geocode) {
1316 if ($params[$geocode] ??
FALSE) {
1317 // ensure that if the geocoding provider (Google, OSM etc) has returned the string 'null' because they can't geocode, ensure that contacts are not placed on null island 0,0
1318 if ($params[$geocode] !== 'null') {
1319 $params[$geocode] = (float) substr($params[$geocode], 0, 14);
1323 return $providerExists;
1327 * Create multiple addresses using legacy methodology.
1329 * @param array $params
1330 * @param bool $fixAddress
1332 * @return array|null
1334 public static function legacyCreate(array $params, bool $fixAddress) {
1335 if (!isset($params['address']) ||
!is_array($params['address'])) {
1338 CRM_Core_BAO_Block
::sortPrimaryFirst($params['address']);
1341 $updateBlankLocInfo = CRM_Utils_Array
::value('updateBlankLocInfo', $params, FALSE);
1342 $contactId = $params['contact_id'];
1343 //get all the addresses for this contact
1344 $addresses = self
::allAddress($contactId);
1346 $isPrimary = $isBilling = TRUE;
1348 foreach ($params['address'] as $key => $value) {
1349 if (!is_array($value)) {
1353 $addressExists = self
::dataExists($value);
1354 if (empty($value['id'])) {
1355 if (!empty($addresses) && !empty($value['location_type_id']) && array_key_exists($value['location_type_id'], $addresses)) {
1356 $value['id'] = $addresses[$value['location_type_id']];
1360 // Note there could be cases when address info already exist ($value[id] is set) for a contact/entity
1361 // BUT info is not present at this time, and therefore we should be really careful when deleting the block.
1362 // $updateBlankLocInfo will help take appropriate decision. CRM-5969
1363 if (isset($value['id']) && !$addressExists && $updateBlankLocInfo) {
1364 //delete the existing record
1365 CRM_Core_BAO_Block
::blockDelete('Address', ['id' => $value['id']]);
1368 elseif (!$addressExists) {
1372 if ($isPrimary && !empty($value['is_primary'])) {
1376 $value['is_primary'] = 0;
1379 if ($isBilling && !empty($value['is_billing'])) {
1383 $value['is_billing'] = 0;
1386 if (empty($value['manual_geo_code'])) {
1387 $value['manual_geo_code'] = 0;
1389 $value['contact_id'] = $contactId;
1390 $blocks[] = self
::add($value, $fixAddress);