Merge pull request #24117 from civicrm/5.52
[civicrm-core.git] / CRM / Core / BAO / Address.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This is class to handle address related functions.
20 */
21 class CRM_Core_BAO_Address extends CRM_Core_DAO_Address {
22 use CRM_Contact_AccessTrait;
23
24 /**
25 * Takes an associative array and creates a address.
26 *
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
32 *
33 * @return array|NULL|self
34 * array of created address
35 */
36 public static function create(&$params, $fixAddress = TRUE) {
37 if (!isset($params['address']) || !is_array($params['address'])) {
38 return self::add($params, $fixAddress);
39 }
40 CRM_Core_Error::deprecatedFunctionWarning('Use legacyCreate if not doing a single crud action');
41 return self::legacyCreate($params, $fixAddress);
42 }
43
44 /**
45 * Takes an associative array and adds address.
46 *
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
52 *
53 * @return CRM_Core_BAO_Address|null
54 */
55 public static function add(&$params, $fixAddress = FALSE) {
56
57 $address = new CRM_Core_DAO_Address();
58 $checkPermissions = $params['check_permissions'] ?? TRUE;
59
60 // fixAddress mode to be done
61 if ($fixAddress) {
62 CRM_Core_BAO_Address::fixAddress($params);
63 }
64
65 $hook = empty($params['id']) ? 'create' : 'edit';
66 CRM_Utils_Hook::pre($hook, 'Address', CRM_Utils_Array::value('id', $params), $params);
67
68 CRM_Core_BAO_Block::handlePrimary($params, get_class());
69 CRM_Core_BAO_Block::handleBilling($params, get_class());
70
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);
74 }
75
76 $address->copyValues($params);
77 $address->save();
78
79 if ($address->id) {
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);
83 }
84
85 if (isset($params['custom'])) {
86 $addressCustom = $params['custom'];
87 }
88 else {
89 $customFields = CRM_Core_BAO_CustomField::getFields('Address', FALSE, TRUE, NULL, NULL,
90 FALSE, FALSE, $checkPermissions ? CRM_Core_Permission::EDIT : FALSE);
91
92 if (!empty($customFields)) {
93 $addressCustom = CRM_Core_BAO_CustomField::postProcess($params,
94 $address->id,
95 'Address',
96 FALSE,
97 $checkPermissions
98 );
99 }
100 }
101 if (!empty($addressCustom)) {
102 CRM_Core_BAO_CustomValueTable::store($addressCustom, 'civicrm_address', $address->id, $hook);
103 }
104
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);
109
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);
112 }
113
114 return $address;
115 }
116
117 /**
118 * Format the address params to have reasonable values.
119 *
120 * @param array $params
121 * (reference ) an assoc array of name/value pairs.
122 */
123 public static function fixAddress(&$params) {
124 if (!empty($params['billing_street_address'])) {
125 //Check address is coming from online contribution / registration page
126 //Fixed :CRM-5076
127 $billing = [
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',
135 ];
136
137 foreach ($billing as $key => $val) {
138 if ($value = CRM_Utils_Array::value($val, $params)) {
139 if (!empty($params[$key])) {
140 unset($params[$val]);
141 }
142 else {
143 //add new key and removed old
144 $params[$key] = $value;
145 unset($params[$val]);
146 }
147 }
148 }
149 }
150
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'],
155 $match
156 )
157 ) {
158 $params['postal_code'] = $match[1];
159 $params['postal_code_suffix'] = $match[2];
160 }
161
162 // add country id if not set
163 if ((!isset($params['country_id']) || !is_numeric($params['country_id'])) &&
164 isset($params['country'])
165 ) {
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);
172 }
173 $params['country_id'] = $country->id;
174 }
175
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'])
179 ) {
180 if (!empty($params['state_province'])) {
181 $state_province = new CRM_Core_DAO_StateProvince();
182 $state_province->name = $params['state_province'];
183
184 // add country id if present
185 if (!empty($params['country_id'])) {
186 $state_province->country_id = $params['country_id'];
187 }
188
189 if (!$state_province->find(TRUE)) {
190 unset($state_province->name);
191 $state_province->abbreviation = $params['state_province'];
192 $state_province->find(TRUE);
193 }
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;
198 }
199 }
200 else {
201 $params['state_province_id'] = 'null';
202 }
203 }
204
205 // add county id if county is set
206 // CRM-7837
207 if ((!isset($params['county_id']) || !is_numeric($params['county_id']))
208 && isset($params['county']) && !empty($params['county'])
209 ) {
210 $county = new CRM_Core_DAO_County();
211 $county->name = $params['county'];
212
213 if (isset($params['state_province_id'])) {
214 $county->state_province_id = $params['state_province_id'];
215 }
216
217 if ($county->find(TRUE)) {
218 $params['county_id'] = $county->id;
219 }
220 }
221
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']))
227 ) {
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'],
232 'country_id'
233 );
234 }
235
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';
241 }
242 elseif (!is_numeric($params['state_province_id']) ||
243 ((int ) $params['state_province_id'] < 1000)
244 ) {
245 // CRM-3393 ( the hacky 1000 check)
246 $params['state_province_id'] = 'null';
247 }
248 }
249
250 if (isset($params['country_id'])) {
251 if (empty($params['country_id'])) {
252 $params['country_id'] = 'null';
253 }
254 elseif (!is_numeric($params['country_id']) ||
255 ((int ) $params['country_id'] < 1000)
256 ) {
257 // CRM-3393 ( the hacky 1000 check)
258 $params['country_id'] = 'null';
259 }
260 }
261
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']);
265 }
266
267 if (isset($params['country_id']) && is_numeric($params['country_id'])) {
268 $params['country'] = CRM_Core_PseudoConstant::country($params['country_id']);
269 }
270
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
275 ) {
276 CRM_Utils_Address_USPS::checkAddress($params);
277 }
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,
283 'address_options'
284 ),
285 FALSE
286 );
287
288 if ($parseStreetAddress && !empty($params['street_address'])) {
289 foreach (['street_number', 'street_name', 'street_unit', 'street_number_suffix'] as $fld) {
290 unset($params[$fld]);
291 }
292 // main parse string.
293 $parseString = $params['street_address'] ?? NULL;
294 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
295
296 // merge parse address in to main address block.
297 $params = array_merge($params, $parsedFields);
298 }
299
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);
304 }
305
306 }
307
308 /**
309 * Check if there is data to create the object.
310 *
311 * @param array $params
312 * (reference ) an assoc array of name/value pairs.
313 *
314 * @return bool
315 */
316 public static function dataExists(&$params) {
317 //check if location type is set if not return false
318 if (!isset($params['location_type_id'])) {
319 return FALSE;
320 }
321
322 $config = CRM_Core_Config::singleton();
323 foreach ($params as $name => $value) {
324 if (in_array($name, [
325 'is_primary',
326 'location_type_id',
327 'id',
328 'contact_id',
329 'is_billing',
330 'display',
331 'master_id',
332 ])) {
333 continue;
334 }
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
339 // iso code
340 $defaultCountry = CRM_Core_BAO_Country::defaultContactCountry();
341 // full name
342 $defaultCountryName = CRM_Core_BAO_Country::defaultContactCountryName();
343
344 if ($defaultCountry) {
345 if ($value == $defaultCountry ||
346 $value == $defaultCountryName ||
347 $value == $config->defaultContactCountry
348 ) {
349 // do nothing
350 }
351 else {
352 return TRUE;
353 }
354 }
355 else {
356 // return if null default
357 return TRUE;
358 }
359 }
360 else {
361 return TRUE;
362 }
363 }
364 }
365
366 return FALSE;
367 }
368
369 /**
370 * Given the list of params in the params array, fetch the object
371 * and store the values in the values array
372 *
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
378 *
379 * @return array
380 * array with address fields
381 */
382 public static function &getValues($entityBlock, $microformat = FALSE, $fieldName = 'contact_id') {
383 if (empty($entityBlock)) {
384 return NULL;
385 }
386 $addresses = [];
387 $address = new CRM_Core_BAO_Address();
388
389 if (empty($entityBlock['entity_table'])) {
390 $address->$fieldName = $entityBlock[$fieldName] ?? NULL;
391 }
392 else {
393 $addressIds = [];
394 $addressIds = self::allEntityAddress($entityBlock);
395
396 if (!empty($addressIds[1])) {
397 $address->id = $addressIds[1];
398 }
399 else {
400 return $addresses;
401 }
402 }
403 if (isset($entityBlock['is_billing']) && $entityBlock['is_billing'] == 1) {
404 $address->orderBy('is_billing desc, id');
405 }
406 else {
407 //get primary address as a first block.
408 $address->orderBy('is_primary desc, id');
409 }
410
411 $address->find();
412
413 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
414 $count = 1;
415 while ($address->fetch()) {
416 // deprecate reference.
417 if ($count > 1) {
418 foreach (['state', 'state_name', 'country', 'world_region'] as $fld) {
419 if (isset($address->$fld)) {
420 unset($address->$fld);
421 }
422 }
423 }
424 $stree = $address->street_address;
425 $values = [];
426 CRM_Core_DAO::storeValues($address, $values);
427
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;
431 }
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;
437 }
438
439 if (!empty($address->country_id)) {
440 $address->country = CRM_Core_PseudoConstant::country($address->country_id);
441 $values['country'] = $address->country;
442
443 //get world region
444 $regionId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $address->country_id, 'region_id');
445 $values['world_region'] = CRM_Core_PseudoConstant::worldregion($regionId);
446 }
447
448 $address->addDisplay($microformat);
449
450 $values['display'] = $address->display;
451 $values['display_text'] = $address->display_text;
452
453 if (isset($address->master_id) && !CRM_Utils_System::isNull($address->master_id)) {
454 $values['use_shared_address'] = 1;
455 }
456
457 $addresses[$count] = $values;
458
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!
461 if ($count > 1) {
462 $addresses[$count]['is_primary'] = 0;
463 }
464
465 $count++;
466 }
467
468 return $addresses;
469 }
470
471 /**
472 * Add the formatted address to $this-> display.
473 *
474 * @param bool $microformat
475 * Unexplained parameter that I've always wondered about.
476 */
477 public function addDisplay($microformat = FALSE) {
478 $fields = [
479 // added this for CRM 1200
480 'address_id' => $this->id,
481 // CRM-4003
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 ?? "",
494 ];
495
496 if (isset($this->county_id) && $this->county_id) {
497 $fields['county'] = CRM_Core_PseudoConstant::county($this->county_id);
498 }
499 else {
500 $fields['county'] = NULL;
501 }
502
503 $this->display = CRM_Utils_Address::format($fields, NULL, $microformat);
504 $this->display_text = CRM_Utils_Address::format($fields);
505 }
506
507 /**
508 * Get all the addresses for a specified contact_id, with the primary address being first
509 *
510 * @param int $id
511 * The contact id.
512 *
513 * @param bool $updateBlankLocInfo
514 *
515 * @return array
516 * the array of adrress data
517 */
518 public static function allAddress($id, $updateBlankLocInfo = FALSE) {
519 if (!$id) {
520 return NULL;
521 }
522
523 $query = "
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']];
529
530 $addresses = [];
531 $dao = CRM_Core_DAO::executeQuery($query, $params);
532 $count = 1;
533 while ($dao->fetch()) {
534 if ($updateBlankLocInfo) {
535 $addresses[$count++] = $dao->address_id;
536 }
537 else {
538 $addresses[$dao->location_type_id] = $dao->address_id;
539 }
540 }
541 return $addresses;
542 }
543
544 /**
545 * Get all the addresses for a specified location_block id, with the primary address being first
546 *
547 * @param array $entityElements
548 * The array containing entity_id and.
549 * entity_table name
550 *
551 * @return array
552 * the array of adrress data
553 */
554 public static function allEntityAddress(&$entityElements) {
555 $addresses = [];
556 if (empty($entityElements)) {
557 return $addresses;
558 }
559
560 $entityId = $entityElements['entity_id'];
561 $entityTable = $entityElements['entity_table'];
562
563 $sql = "
564 SELECT civicrm_address.id as address_id
565 FROM civicrm_loc_block loc, civicrm_location_type ltype, civicrm_address, {$entityTable} ev
566 WHERE ev.id = %1
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 ";
571
572 $params = [1 => [$entityId, 'Integer']];
573 $dao = CRM_Core_DAO::executeQuery($sql, $params);
574 $locationCount = 1;
575 while ($dao->fetch()) {
576 $addresses[$locationCount] = $dao->address_id;
577 $locationCount++;
578 }
579 return $addresses;
580 }
581
582 /**
583 * Get address sequence.
584 *
585 * @return array
586 * Array of address sequence.
587 */
588 public static function addressSequence() {
589 $addressSequence = CRM_Utils_Address::sequence(\Civi::settings()->get('address_format'));
590
591 $countryState = $cityPostal = FALSE;
592 foreach ($addressSequence as $key => $field) {
593 if (
594 in_array($field, ['country', 'state_province']) &&
595 !$countryState
596 ) {
597 $countryState = TRUE;
598 $addressSequence[$key] = 'country_state_province';
599 }
600 elseif (
601 in_array($field, ['city', 'postal_code']) &&
602 !$cityPostal
603 ) {
604 $cityPostal = TRUE;
605 $addressSequence[$key] = 'city_postal_code';
606 }
607 elseif (
608 in_array($field, ['country', 'state_province', 'city', 'postal_code'])
609 ) {
610 unset($addressSequence[$key]);
611 }
612 }
613
614 return $addressSequence;
615 }
616
617 /**
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"
621 *
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
624 *
625 * @param string $streetAddress
626 * Street address including number and apt.
627 * @param string $locale
628 * Locale used to parse address.
629 *
630 * @return array
631 * parsed fields values.
632 */
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)) {
636 $locale = 'en_US';
637 }
638
639 $emptyParseFields = $parseFields = [
640 'street_name' => '',
641 'street_unit' => '',
642 'street_number' => '',
643 'street_number_suffix' => '',
644 ];
645
646 if (empty($streetAddress)) {
647 return $parseFields;
648 }
649
650 $streetAddress = trim($streetAddress);
651
652 $matches = [];
653 if (in_array($locale, ['en_CA', 'fr_CA'])
654 && preg_match('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', $streetAddress, $matches)
655 ) {
656 $parseFields['street_unit'] = $matches[1];
657 // unset from rest of street address
658 $streetAddress = preg_replace('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', '', $streetAddress);
659 }
660
661 // get street number and suffix.
662 $matches = [];
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];
668
669 // get street number.
670 $matches = [];
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);
675 }
676
677 // unset from main street address.
678 $streetAddress = preg_replace('/^[A-Za-z0-9]+([\S]+)/', '', $streetAddress);
679 $streetAddress = trim($streetAddress);
680 }
681 }
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);
687 }
688
689 // If street number is too large, we cannot store it.
690 if ($parseFields['street_number'] > CRM_Utils_Type::INT_MAX) {
691 return $emptyParseFields;
692 }
693
694 // suffix might be like 1/2
695 $matches = [];
696 if (preg_match('/^\d\/\d/', $streetAddress, $matches)) {
697 $parseFields['street_number_suffix'] .= $matches[0];
698
699 // unset from main street address.
700 $streetAddress = preg_replace('/^\d+\/\d+/', '', $streetAddress);
701 $streetAddress = trim($streetAddress);
702 }
703
704 // now get the street unit.
705 // supportable street unit formats.
706 $streetUnitFormats = [
707 'APT',
708 'APARTMENT',
709 'BSMT',
710 'BASEMENT',
711 'BLDG',
712 'BUILDING',
713 'DEPT',
714 'DEPARTMENT',
715 'FL',
716 'FLOOR',
717 'FRNT',
718 'FRONT',
719 'HNGR',
720 'HANGER',
721 'LBBY',
722 'LOBBY',
723 'LOWR',
724 'LOWER',
725 'OFC',
726 'OFFICE',
727 'PH',
728 'PENTHOUSE',
729 'TRLR',
730 'TRAILER',
731 'UPPR',
732 'RM',
733 'ROOM',
734 'SIDE',
735 'SLIP',
736 'KEY',
737 'LOT',
738 'PIER',
739 'REAR',
740 'SPC',
741 'SPACE',
742 'STOP',
743 'STE',
744 'SUITE',
745 'UNIT',
746 '#',
747 ];
748
749 // overwriting $streetUnitFormats for 'en_CA' and 'fr_CA' locale
750 if (in_array($locale, [
751 'en_CA',
752 'fr_CA',
753 ])) {
754 $streetUnitFormats = ['APT', 'APP', 'SUITE', 'BUREAU', 'UNIT'];
755 }
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';
759 $matches = [];
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);
764 }
765
766 // consider remaining string as street name.
767 $parseFields['street_name'] = $streetAddress;
768
769 //run parsed fields through stripSpaces to clean
770 foreach ($parseFields as $parseField => $value) {
771 $parseFields[$parseField] = CRM_Utils_String::stripSpaces($value);
772 }
773 //CRM-14459 if the field is too long we should assume it didn't get it right & skip rather than allow
774 // the DB to fatal
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;
779 }
780 }
781
782 return $parseFields;
783 }
784
785 /**
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.
790 *
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
796 *
797 * @param string $locale
798 * The locale to be checked
799 *
800 * @return bool
801 */
802 public static function isSupportedParsingLocale($locale = NULL) {
803 if (!$locale) {
804 $config = CRM_Core_Config::singleton();
805 $locale = $config->lcMessages;
806 }
807
808 $parsingSupportedLocales = ['en_US', 'en_CA', 'fr_CA'];
809
810 if (in_array($locale, $parsingSupportedLocales)) {
811 return TRUE;
812 }
813
814 return FALSE;
815 }
816
817 /**
818 * Validate the address fields based on the address options enabled.
819 * in the Address Settings
820 *
821 * @param array $fields
822 * An array of importable/exportable contact fields.
823 *
824 * @return array
825 * an array of contact fields and only the enabled address options
826 */
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,
832 'address_options'
833 );
834 }
835
836 if (is_array($fields) && !empty($fields)) {
837 foreach ($addressOptions as $key => $value) {
838 if (!$value && isset($fields[$key])) {
839 unset($fields[$key]);
840 }
841 }
842 }
843 return $fields;
844 }
845
846 /**
847 * Check if current address is used by any other contacts.
848 *
849 * @param int $addressId
850 * Address id.
851 *
852 * @return int
853 * count of contacts that use this shared address
854 */
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']]);
858 }
859
860 /**
861 * Check if current address fields are shared with any other address.
862 *
863 * @param array $fields
864 * Address fields in profile.
865 * @param int $contactId
866 * Contact id.
867 *
868 */
869 public static function checkContactSharedAddressFields(&$fields, $contactId) {
870 if (!$contactId || !is_array($fields) || empty($fields)) {
871 return;
872 }
873
874 $sharedLocations = [];
875
876 $query = "
877 SELECT is_primary,
878 location_type_id
879 FROM civicrm_address
880 WHERE contact_id = %1
881 AND master_id IS NOT NULL";
882
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';
888 }
889 }
890
891 //no need to process further.
892 if (empty($sharedLocations)) {
893 return;
894 }
895
896 $addressFields = [
897 'city',
898 'county',
899 'country',
900 'geo_code_1',
901 'geo_code_2',
902 'postal_code',
903 'address_name',
904 'state_province',
905 'street_address',
906 'postal_code_suffix',
907 'supplemental_address_1',
908 'supplemental_address_2',
909 'supplemental_address_3',
910 ];
911
912 foreach ($fields as $name => & $values) {
913 if (!is_array($values) || empty($values)) {
914 continue;
915 }
916
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'];
922 }
923
924 if (in_array($fldName, $addressFields) &&
925 in_array($locType, $sharedLocations)
926 ) {
927 $values['is_shared'] = TRUE;
928 }
929 }
930 }
931
932 /**
933 * Fix the shared address if address is already shared
934 * or if address will be shared with itself.
935 *
936 * @param array $params
937 * Associated array of address params.
938 */
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;
944 }
945
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');
950 }
951 }
952
953 /**
954 * Update the shared addresses if master address is modified.
955 *
956 * @param int $addressId
957 * Address id.
958 * @param array $params
959 * Associated array of address params.
960 * @param string $parentOperation Operation being taken on the parent entity.
961 */
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']]);
965
966 // Default to TRUE if not set to maintain api backward compatibility.
967 $createRelationship = $params['add_relationship'] ?? TRUE;
968
969 // unset contact id
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']);
975 }
976 }
977 else {
978 // else no new shares will be created, only update shared addresses
979 $skipFields[] = 'master_id';
980 }
981 foreach ($skipFields as $value) {
982 unset($params[$value]);
983 }
984
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);
990 }
991 $addressDAO->copyValues($params);
992 $addressDAO->id = $dao->id;
993 $addressDAO->save();
994 $addressDAO->copyCustomFields($addressId, $addressDAO->id, $parentOperation);
995 }
996 }
997
998 /**
999 * Merge contacts with the Same address to get one shared label.
1000 * @param array $rows
1001 * Array[contact_id][contactDetails].
1002 */
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'];
1014 }
1015 else {
1016 $name = $rows[$rowID]['display_name'];
1017 }
1018
1019 // CRM-15120
1020 $formatted = [
1021 'first_name' => $rows[$rowID]['first_name'],
1022 'individual_prefix' => $rows[$rowID]['individual_prefix'],
1023 ];
1024 $format = Civi::settings()->get('display_name_format');
1025 $firstNameWithPrefix = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE);
1026 $firstNameWithPrefix = trim($firstNameWithPrefix);
1027
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
1035 }
1036 else {
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'];
1040 }
1041 }
1042 foreach ($uniqueAddress as $address => $data) {
1043 // copy data back to $rows
1044 $count = 0;
1045 // one last name list per row
1046 foreach ($data['names'] as $last_name => $first_names) {
1047 // too many to list
1048 if ($count > 2) {
1049 break;
1050 }
1051 if (count($first_names) == 1) {
1052 $family = $first_names[current(array_keys($first_names))]['addressee_display'];
1053 }
1054 else {
1055 // collapse the tree to summarize
1056 $family = trim(implode(" & ", array_keys($first_names)) . " " . $last_name);
1057 }
1058 if ($count) {
1059 $processedNames .= "\n" . $family;
1060 }
1061 else {
1062 // build display_name string
1063 $processedNames = $family;
1064 }
1065 $count++;
1066 }
1067 $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames;
1068 }
1069 }
1070
1071 /**
1072 * Create relationship between contacts who share an address.
1073 *
1074 * Note that currently we create relationship between
1075 * Individual + Household and Individual + Organization
1076 *
1077 * @param int $masterAddressId
1078 * Master address id.
1079 * @param int $currentContactId
1080 * Current contact id.
1081 */
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);
1085
1086 // if current contact is not of type individual return
1087 if ($currentContactType != 'Individual') {
1088 return;
1089 }
1090
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
1095 WHERE ca.id = %1';
1096
1097 $dao = CRM_Core_DAO::executeQuery($query, [1 => [$masterAddressId, 'Integer']]);
1098 $dao->fetch();
1099
1100 // master address contact needs to be Household or Organization, otherwise return
1101 if ($dao->contact_type == 'Individual') {
1102 return;
1103 }
1104 $sharedContactType = $dao->contact_type;
1105 $sharedContactId = $dao->id;
1106
1107 // create relationship between ontacts who share an address
1108 if ($sharedContactType == 'Organization') {
1109 return CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($currentContactId, $sharedContactId);
1110 }
1111
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');
1114
1115 if (!$relTypeId) {
1116 throw new CRM_Core_Exception(ts("You seem to have deleted the relationship type 'Household Member of'"));
1117 }
1118
1119 $relParam = [
1120 'is_active' => TRUE,
1121 'relationship_type_id' => $relTypeId,
1122 'contact_id_a' => $currentContactId,
1123 'contact_id_b' => $sharedContactId,
1124 ];
1125
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)) {
1129 return;
1130 }
1131
1132 try {
1133 // create relationship
1134 civicrm_api3('relationship', 'create', $relParam);
1135 }
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.
1139 }
1140 }
1141
1142 /**
1143 * Check and set the status for shared address delete.
1144 *
1145 * @param int $addressId
1146 * Address id.
1147 * @param int $contactId
1148 * Contact id.
1149 * @param bool $returnStatus
1150 * By default false.
1151 *
1152 * @return string
1153 */
1154 public static function setSharedAddressDeleteStatus($addressId = NULL, $contactId = NULL, $returnStatus = FALSE) {
1155 // check if address that is being deleted has any shared
1156 if ($addressId) {
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';
1161 }
1162 else {
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';
1169 }
1170
1171 $dao = CRM_Core_DAO::executeQuery($query, [1 => [$entityId, 'Integer']]);
1172
1173 $deleteStatus = [];
1174 $sharedContactList = [];
1175 $statusMessage = NULL;
1176 $addressCount = 0;
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.');
1180 }
1181
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>";
1185
1186 $addressCount++;
1187 }
1188
1189 if (!empty($deleteStatus)) {
1190 $statusMessage = implode('<br/>', $deleteStatus) . '<br/>';
1191 }
1192
1193 if (!$returnStatus) {
1194 CRM_Core_Session::setStatus($statusMessage, '', 'info');
1195 }
1196 else {
1197 return [
1198 'contactList' => $sharedContactList,
1199 'count' => $addressCount,
1200 ];
1201 }
1202 }
1203
1204 /**
1205 * Call common delete function.
1206 *
1207 * @see \CRM_Contact_BAO_Contact::on_hook_civicrm_post
1208 *
1209 * @param int $id
1210 * @deprecated
1211 * @return bool
1212 */
1213 public static function del($id) {
1214 return (bool) self::deleteRecord(['id' => $id]);
1215 }
1216
1217 /**
1218 * Get options for a given address field.
1219 * @see CRM_Core_DAO::buildOptions
1220 *
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?
1223 *
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.
1229 *
1230 * @return array|bool
1231 */
1232 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1233 $params = [];
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;
1246 }
1247 else {
1248 $props['country_id'] = $config->defaultContactCountry;
1249 }
1250 }
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'));
1254 }
1255 $params['condition'] = 'country_id IN (' . implode(',', (array) $props['country_id']) . ')';
1256 }
1257 break;
1258
1259 // Filter country list based on site defaults
1260 case 'country_id':
1261 case 'country':
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'));
1269 }
1270 $params['condition'] = 'id IN (' . implode(',', $config->countryLimit) . ')';
1271 }
1272 }
1273 break;
1274
1275 // Filter county list based on chosen state
1276 case 'county_id':
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'));
1280 }
1281 $params['condition'] = 'state_province_id IN (' . implode(',', (array) $props['state_province_id']) . ')';
1282 }
1283 break;
1284
1285 // Not a real field in this entity
1286 case 'world_region':
1287 case 'worldregion':
1288 case 'worldregion_id':
1289 return CRM_Core_BAO_Country::buildOptions('region_id', $context, $props);
1290 }
1291 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1292 }
1293
1294 /**
1295 * Add data from the configured geocoding provider.
1296 *
1297 * Generally this means latitude & longitude data.
1298 *
1299 * @param array $params
1300 * @return bool
1301 * TRUE if params could be passed to a provider, else FALSE.
1302 */
1303 public static function addGeocoderData(&$params) {
1304 try {
1305 $provider = CRM_Utils_GeocodeProvider::getConfiguredProvider();
1306 $providerExists = TRUE;
1307 }
1308 catch (CRM_Core_Exception $e) {
1309 $providerExists = FALSE;
1310 }
1311 if ($providerExists) {
1312 $provider::format($params);
1313 }
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);
1320 }
1321 }
1322 }
1323 return $providerExists;
1324 }
1325
1326 /**
1327 * Create multiple addresses using legacy methodology.
1328 *
1329 * @param array $params
1330 * @param bool $fixAddress
1331 *
1332 * @return array|null
1333 */
1334 public static function legacyCreate(array $params, bool $fixAddress) {
1335 if (!isset($params['address']) || !is_array($params['address'])) {
1336 return NULL;
1337 }
1338 CRM_Core_BAO_Block::sortPrimaryFirst($params['address']);
1339 $contactId = NULL;
1340
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);
1345
1346 $isPrimary = $isBilling = TRUE;
1347 $blocks = [];
1348 foreach ($params['address'] as $key => $value) {
1349 if (!is_array($value)) {
1350 continue;
1351 }
1352
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']];
1357 }
1358 }
1359
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']]);
1366 continue;
1367 }
1368 elseif (!$addressExists) {
1369 continue;
1370 }
1371
1372 if ($isPrimary && !empty($value['is_primary'])) {
1373 $isPrimary = FALSE;
1374 }
1375 else {
1376 $value['is_primary'] = 0;
1377 }
1378
1379 if ($isBilling && !empty($value['is_billing'])) {
1380 $isBilling = FALSE;
1381 }
1382 else {
1383 $value['is_billing'] = 0;
1384 }
1385
1386 if (empty($value['manual_geo_code'])) {
1387 $value['manual_geo_code'] = 0;
1388 }
1389 $value['contact_id'] = $contactId;
1390 $blocks[] = self::add($value, $fixAddress);
1391 }
1392 return $blocks;
1393 }
1394
1395 }