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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 class CRM_Utils_Address
{
21 * Format an address string from address fields and a format string.
23 * Format an address basing on the address fields provided.
24 * Use Setting's address_format if there's no format specified.
26 * This function is also used to generate a contact's display_name and
29 * @param array $fields
31 * @param string $format
32 * The desired address format.
33 * @param bool $microformat
34 * If true indicates, the address to be built in hcard-microformat standard.
35 * @param bool $mailing
36 * Should ALWAYS be false.
37 * @param string[] $tokenFields
40 * formatted address string
43 public static function format(
50 static $config = NULL;
54 $format = Civi
::settings()->get('address_format');
58 $format = Civi
::settings()->get('mailing_format');
63 $fullPostalCode = $fields['postal_code'] ??
NULL;
64 if (!empty($fields['postal_code_suffix'])) {
65 $fullPostalCode .= "-$fields[postal_code_suffix]";
68 // make sure that some of the fields do have values
70 'supplemental_address_1',
71 'supplemental_address_2',
72 'supplemental_address_3',
73 'state_province_name',
76 foreach ($emptyFields as $f) {
77 if (!isset($fields[$f])) {
82 //CRM-16876 Display countries in all caps when in mailing mode.
83 if ($mailing && !empty($fields['country'])) {
84 if (Civi
::settings()->get('hideCountryMailingLabels')) {
85 $domain = CRM_Core_BAO_Domain
::getDomain();
86 $domainLocation = CRM_Core_BAO_Location
::getValues(['contact_id' => $domain->contact_id
]);
87 $domainAddress = $domainLocation['address'][1];
88 $domainCountryId = $domainAddress['country_id'];
89 if ($fields['country'] == CRM_Core_PseudoConstant
::country($domainCountryId)) {
90 $fields['country'] = NULL;
93 //Capitalization display on uppercase to contries with special characters
94 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER
, "UTF-8");
98 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER
, "UTF-8");
103 // replacements in case of Individual Name Format
105 'contact.display_name' => $fields['display_name'] ??
NULL,
106 'contact.individual_prefix' => $fields['individual_prefix'] ??
NULL,
107 'contact.formal_title' => $fields['formal_title'] ??
NULL,
108 'contact.first_name' => $fields['first_name'] ??
NULL,
109 'contact.middle_name' => $fields['middle_name'] ??
NULL,
110 'contact.last_name' => $fields['last_name'] ??
NULL,
111 'contact.individual_suffix' => $fields['individual_suffix'] ??
NULL,
112 'contact.address_name' => $fields['address_name'] ??
NULL,
113 'contact.street_address' => $fields['street_address'] ??
NULL,
114 'contact.supplemental_address_1' => $fields['supplemental_address_1'] ??
NULL,
115 'contact.supplemental_address_2' => $fields['supplemental_address_2'] ??
NULL,
116 'contact.supplemental_address_3' => $fields['supplemental_address_3'] ??
NULL,
117 'contact.city' => $fields['city'] ??
NULL,
118 'contact.state_province_name' => $fields['state_province_name'] ??
NULL,
119 'contact.county' => $fields['county'] ??
NULL,
120 'contact.state_province' => $fields['state_province'] ??
NULL,
121 'contact.postal_code' => $fullPostalCode,
122 'contact.country' => $fields['country'] ??
NULL,
123 'contact.world_region' => $fields['world_region'] ??
NULL,
124 'contact.geo_code_1' => $fields['geo_code_1'] ??
NULL,
125 'contact.geo_code_2' => $fields['geo_code_2'] ??
NULL,
126 'contact.current_employer' => $fields['current_employer'] ??
NULL,
127 'contact.nick_name' => $fields['nick_name'] ??
NULL,
128 'contact.email' => $fields['email'] ??
NULL,
129 'contact.im' => $fields['im'] ??
NULL,
130 'contact.do_not_email' => $fields['do_not_email'] ??
NULL,
131 'contact.do_not_phone' => $fields['do_not_phone'] ??
NULL,
132 'contact.do_not_mail' => $fields['do_not_mail'] ??
NULL,
133 'contact.do_not_sms' => $fields['do_not_sms'] ??
NULL,
134 'contact.do_not_trade' => $fields['do_not_trade'] ??
NULL,
135 'contact.job_title' => $fields['job_title'] ??
NULL,
136 'contact.birth_date' => $fields['birth_date'] ??
NULL,
137 'contact.gender' => $fields['gender'] ??
NULL,
138 'contact.is_opt_out' => $fields['is_opt_out'] ??
NULL,
139 'contact.preferred_mail_format' => $fields['preferred_mail_format'] ??
NULL,
140 'contact.phone' => $fields['phone'] ??
NULL,
141 'contact.home_URL' => $fields['home_URL'] ??
NULL,
142 'contact.contact_source' => $fields['contact_source'] ??
NULL,
143 'contact.external_identifier' => $fields['external_identifier'] ??
NULL,
144 'contact.contact_id' => $fields['id'] ??
NULL,
145 'contact.household_name' => $fields['household_name'] ??
NULL,
146 'contact.organization_name' => $fields['organization_name'] ??
NULL,
147 'contact.legal_name' => $fields['legal_name'] ??
NULL,
148 'contact.preferred_communication_method' => $fields['preferred_communication_method'] ??
NULL,
149 'contact.communication_style' => $fields['communication_style'] ??
NULL,
150 'contact.addressee' => $fields['addressee_display'] ??
NULL,
151 'contact.email_greeting' => $fields['email_greeting_display'] ??
NULL,
152 'contact.postal_greeting' => $fields['postal_greeting_display'] ??
NULL,
157 'contact.address_name' => "<span class=\"address-name\">" . $fields['address_name'] . "</span>",
158 'contact.street_address' => "<span class=\"street-address\">" . $fields['street_address'] . "</span>",
159 'contact.supplemental_address_1' => "<span class=\"extended-address\">" . $fields['supplemental_address_1'] . "</span>",
160 'contact.supplemental_address_2' => $fields['supplemental_address_2'],
161 'contact.supplemental_address_3' => $fields['supplemental_address_3'],
162 'contact.city' => "<span class=\"locality\">" . $fields['city'] . "</span>",
163 'contact.state_province_name' => "<span class=\"region\">" . $fields['state_province_name'] . "</span>",
164 'contact.county' => "<span class=\"region\">" . $fields['county'],
165 'contact.state_province' => "<span class=\"region\">" . $fields['state_province'] . "</span>",
166 'contact.postal_code' => "<span class=\"postal-code\">" . $fullPostalCode . "</span>",
167 'contact.country' => "<span class=\"country-name\">" . $fields['country'] . "</span>",
168 'contact.world_region' => "<span class=\"region\">" . $fields['world_region'] . "</span>",
171 // erase all empty ones, so we dont get blank lines
172 foreach (array_keys($replacements) as $key) {
173 $exactKey = substr($key, 0, 8) == 'contact.' ?
substr($key, 8) : $key;
174 if ($key != 'contact.postal_code' &&
175 CRM_Utils_Array
::value($exactKey, $fields) == NULL
177 $replacements[$key] = '';
180 if (empty($fullPostalCode)) {
181 $replacements['contact.postal_code'] = '';
185 // replacements in case of Custom Token
186 if (stristr($formatted, 'custom_')) {
187 $customToken = array_keys($fields);
188 foreach ($customToken as $value) {
189 if (substr($value, 0, 7) == 'custom_') {
190 $replacements["contact.{$value}"] = $fields["{$value}"];
195 // also sub all token fields
197 foreach ($tokenFields as $token) {
198 $replacements["{$token}"] = $fields["{$token}"] ??
NULL;
202 // for every token, replace {fooTOKENbar} with fooVALUEbar if
203 // the value is not empty, otherwise drop the whole {fooTOKENbar}
204 foreach ($replacements as $token => $value) {
205 if ($value && is_string($value) ||
is_numeric($value)) {
206 $formatted = preg_replace("/{([^{}]*)\b{$token}\b([^{}]*)}/u", "\${1}{$value}\${2}", $formatted);
209 $formatted = preg_replace("/{[^{}]*\b{$token}\b[^{}]*}/u", '', $formatted);
213 // drop any {...} constructs from lines' ends
215 $formatted = "\n$formatted\n";
218 if ($microformat == 1) {
219 $formatted = "\n<div class=\"location vcard\"><span class=\"adr\">\n$formatted</span></div>\n";
222 $formatted = "\n<div class=\"vcard\"><span class=\"adr\">$formatted</span></div>\n";
226 $formatted = preg_replace('/\n{[^{}]*}/u', "\n", $formatted);
227 $formatted = preg_replace('/{[^{}]*}\n/u', "\n", $formatted);
229 // if there are any 'sibling' {...} constructs, replace them with the
230 // contents of the first one; for example, when there's no state_province:
231 // 1. {city}{, }{state_province}{ }{postal_code}
232 // 2. San Francisco{, }{ }12345
233 // 3. San Francisco, 12345
234 $formatted = preg_replace('/{([^{}]*)}({[^{}]*})+/u', '\1', $formatted);
236 // drop any remaining curly braces leaving their contents
237 $formatted = str_replace(['{', '}'], '', $formatted);
239 // drop any empty lines left after the replacements
240 $formatted = preg_replace('/^[ \t]*[\r\n]+/m', '', $formatted);
243 $finalFormatted = $formatted;
246 // remove \n from each line and only add at the end
247 // this hack solves formatting issue, when we convert nl2br
250 $finalFormatted = NULL;
251 $formattedArray = explode("\n", $formatted);
252 $formattedArray = array_filter($formattedArray);
254 foreach ($formattedArray as $line) {
257 if ($count > 1 && $count < count($formattedArray)) {
260 $finalFormatted .= $line;
265 return $finalFormatted;
269 * Format a mailing label.
273 * This function is split off from format() which is doing too much for cleanup.
275 * It is ONLY called from 2 label task classes and MUST NOT be called from
276 * anywhere else as it is changing.
278 * @param array $fields
279 * The address fields.
280 * @param string $format
281 * The desired address format.
282 * @param bool $microformat
283 * If true indicates, the address to be built in hcard-microformat standard.
284 * @param bool $mailing
285 * If true indicates, the call has been made from mailing label.
286 * @param null $tokenFields
289 * formatted address string
292 public static function formatMailingLabel(
295 $microformat = FALSE,
299 static $config = NULL;
300 $microformat = FALSE;
303 $format = Civi
::settings()->get('address_format');
307 $format = Civi
::settings()->get('mailing_format');
310 $formatted = $format;
312 $fullPostalCode = $fields['postal_code'] ??
NULL;
313 if (!empty($fields['postal_code_suffix'])) {
314 $fullPostalCode .= "-$fields[postal_code_suffix]";
317 // make sure that some of the fields do have values
319 'supplemental_address_1',
320 'supplemental_address_2',
321 'supplemental_address_3',
322 'state_province_name',
325 foreach ($emptyFields as $f) {
326 if (!isset($fields[$f])) {
331 //CRM-16876 Display countries in all caps when in mailing mode.
332 if ($mailing && !empty($fields['country'])) {
333 if (Civi
::settings()->get('hideCountryMailingLabels')) {
334 $domain = CRM_Core_BAO_Domain
::getDomain();
335 $domainLocation = CRM_Core_BAO_Location
::getValues(['contact_id' => $domain->contact_id
]);
336 $domainAddress = $domainLocation['address'][1];
337 $domainCountryId = $domainAddress['country_id'];
338 if ($fields['country'] == CRM_Core_PseudoConstant
::country($domainCountryId)) {
339 $fields['country'] = NULL;
342 //Capitalization display on uppercase to contries with special characters
343 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER
, "UTF-8");
347 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER
, "UTF-8");
352 // replacements in case of Individual Name Format
354 'contact.display_name' => $fields['display_name'] ??
NULL,
355 'contact.individual_prefix' => $fields['individual_prefix'] ??
NULL,
356 'contact.formal_title' => $fields['formal_title'] ??
NULL,
357 'contact.first_name' => $fields['first_name'] ??
NULL,
358 'contact.middle_name' => $fields['middle_name'] ??
NULL,
359 'contact.last_name' => $fields['last_name'] ??
NULL,
360 'contact.individual_suffix' => $fields['individual_suffix'] ??
NULL,
361 'contact.address_name' => $fields['address_name'] ??
NULL,
362 'contact.street_address' => $fields['street_address'] ??
NULL,
363 'contact.supplemental_address_1' => $fields['supplemental_address_1'] ??
NULL,
364 'contact.supplemental_address_2' => $fields['supplemental_address_2'] ??
NULL,
365 'contact.supplemental_address_3' => $fields['supplemental_address_3'] ??
NULL,
366 'contact.city' => $fields['city'] ??
NULL,
367 'contact.state_province_name' => $fields['state_province_name'] ??
NULL,
368 'contact.county' => $fields['county'] ??
NULL,
369 'contact.state_province' => $fields['state_province'] ??
NULL,
370 'contact.postal_code' => $fullPostalCode,
371 'contact.country' => $fields['country'] ??
NULL,
372 'contact.world_region' => $fields['world_region'] ??
NULL,
373 'contact.geo_code_1' => $fields['geo_code_1'] ??
NULL,
374 'contact.geo_code_2' => $fields['geo_code_2'] ??
NULL,
375 'contact.current_employer' => $fields['current_employer'] ??
NULL,
376 'contact.nick_name' => $fields['nick_name'] ??
NULL,
377 'contact.email' => $fields['email'] ??
NULL,
378 'contact.im' => $fields['im'] ??
NULL,
379 'contact.do_not_email' => $fields['do_not_email'] ??
NULL,
380 'contact.do_not_phone' => $fields['do_not_phone'] ??
NULL,
381 'contact.do_not_mail' => $fields['do_not_mail'] ??
NULL,
382 'contact.do_not_sms' => $fields['do_not_sms'] ??
NULL,
383 'contact.do_not_trade' => $fields['do_not_trade'] ??
NULL,
384 'contact.job_title' => $fields['job_title'] ??
NULL,
385 'contact.birth_date' => $fields['birth_date'] ??
NULL,
386 'contact.gender' => $fields['gender'] ??
NULL,
387 'contact.is_opt_out' => $fields['is_opt_out'] ??
NULL,
388 'contact.preferred_mail_format' => $fields['preferred_mail_format'] ??
NULL,
389 'contact.phone' => $fields['phone'] ??
NULL,
390 'contact.home_URL' => $fields['home_URL'] ??
NULL,
391 'contact.contact_source' => $fields['contact_source'] ??
NULL,
392 'contact.external_identifier' => $fields['external_identifier'] ??
NULL,
393 'contact.contact_id' => $fields['id'] ??
NULL,
394 'contact.household_name' => $fields['household_name'] ??
NULL,
395 'contact.organization_name' => $fields['organization_name'] ??
NULL,
396 'contact.legal_name' => $fields['legal_name'] ??
NULL,
397 'contact.preferred_communication_method' => $fields['preferred_communication_method'] ??
NULL,
398 'contact.communication_style' => $fields['communication_style'] ??
NULL,
399 'contact.addressee' => $fields['addressee_display'] ??
NULL,
400 'contact.email_greeting' => $fields['email_greeting_display'] ??
NULL,
401 'contact.postal_greeting' => $fields['postal_greeting_display'] ??
NULL,
406 'contact.address_name' => "<span class=\"address-name\">" . $fields['address_name'] . "</span>",
407 'contact.street_address' => "<span class=\"street-address\">" . $fields['street_address'] . "</span>",
408 'contact.supplemental_address_1' => "<span class=\"extended-address\">" . $fields['supplemental_address_1'] . "</span>",
409 'contact.supplemental_address_2' => $fields['supplemental_address_2'],
410 'contact.supplemental_address_3' => $fields['supplemental_address_3'],
411 'contact.city' => "<span class=\"locality\">" . $fields['city'] . "</span>",
412 'contact.state_province_name' => "<span class=\"region\">" . $fields['state_province_name'] . "</span>",
413 'contact.county' => "<span class=\"region\">" . $fields['county'],
414 'contact.state_province' => "<span class=\"region\">" . $fields['state_province'] . "</span>",
415 'contact.postal_code' => "<span class=\"postal-code\">" . $fullPostalCode . "</span>",
416 'contact.country' => "<span class=\"country-name\">" . $fields['country'] . "</span>",
417 'contact.world_region' => "<span class=\"region\">" . $fields['world_region'] . "</span>",
420 // erase all empty ones, so we dont get blank lines
421 foreach (array_keys($replacements) as $key) {
422 $exactKey = substr($key, 0, 8) == 'contact.' ?
substr($key, 8) : $key;
423 if ($key != 'contact.postal_code' &&
424 CRM_Utils_Array
::value($exactKey, $fields) == NULL
426 $replacements[$key] = '';
429 if (empty($fullPostalCode)) {
430 $replacements['contact.postal_code'] = '';
434 // replacements in case of Custom Token
435 if (stristr($formatted, 'custom_')) {
436 $customToken = array_keys($fields);
437 foreach ($customToken as $value) {
438 if (substr($value, 0, 7) == 'custom_') {
439 $replacements["contact.{$value}"] = $fields["{$value}"];
444 // also sub all token fields
446 foreach ($tokenFields as $token) {
447 $replacements["{$token}"] = $fields["{$token}"] ??
NULL;
451 // for every token, replace {fooTOKENbar} with fooVALUEbar if
452 // the value is not empty, otherwise drop the whole {fooTOKENbar}
453 foreach ($replacements as $token => $value) {
454 if ($value && is_string($value) ||
is_numeric($value)) {
455 $formatted = preg_replace("/{([^{}]*)\b{$token}\b([^{}]*)}/u", "\${1}{$value}\${2}", $formatted);
458 $formatted = preg_replace("/{[^{}]*\b{$token}\b[^{}]*}/u", '', $formatted);
462 // drop any {...} constructs from lines' ends
464 $formatted = "\n$formatted\n";
467 if ($microformat == 1) {
468 $formatted = "\n<div class=\"location vcard\"><span class=\"adr\">\n$formatted</span></div>\n";
471 $formatted = "\n<div class=\"vcard\"><span class=\"adr\">$formatted</span></div>\n";
475 $formatted = preg_replace('/\n{[^{}]*}/u', "\n", $formatted);
476 $formatted = preg_replace('/{[^{}]*}\n/u', "\n", $formatted);
478 // if there are any 'sibling' {...} constructs, replace them with the
479 // contents of the first one; for example, when there's no state_province:
480 // 1. {city}{, }{state_province}{ }{postal_code}
481 // 2. San Francisco{, }{ }12345
482 // 3. San Francisco, 12345
483 $formatted = preg_replace('/{([^{}]*)}({[^{}]*})+/u', '\1', $formatted);
485 // drop any remaining curly braces leaving their contents
486 $formatted = str_replace(['{', '}'], '', $formatted);
488 // drop any empty lines left after the replacements
489 $formatted = preg_replace('/^[ \t]*[\r\n]+/m', '', $formatted);
492 $finalFormatted = $formatted;
495 // remove \n from each line and only add at the end
496 // this hack solves formatting issue, when we convert nl2br
499 $finalFormatted = NULL;
500 $formattedArray = explode("\n", $formatted);
501 $formattedArray = array_filter($formattedArray);
503 foreach ($formattedArray as $line) {
506 if ($count > 1 && $count < count($formattedArray)) {
509 $finalFormatted .= $line;
514 return $finalFormatted;
518 * @param string $format
522 public static function sequence($format) {
523 // also compute and store the address sequence
527 'supplemental_address_1',
528 'supplemental_address_2',
529 'supplemental_address_3',
537 // get the field sequence from the format
539 foreach ($addressSequence as $field) {
540 if (substr_count($format, $field)) {
541 $newSequence[strpos($format, $field)] = $field;
546 // add the addressSequence fields that are missing in the addressFormat
547 // to the end of the list, so that (for example) if state_province is not
548 // specified in the addressFormat it's still in the address-editing form
549 $newSequence = array_merge($newSequence, $addressSequence);
550 $newSequence = array_unique($newSequence);
555 * Extract the billing fields from the form submission and format them for display.
557 * @param array $params
558 * @param int $billingLocationTypeID
562 public static function getFormattedBillingAddressFieldsFromParameters($params, $billingLocationTypeID) {
564 "street_address" => "billing_street_address-{$billingLocationTypeID}",
565 "city" => "billing_city-{$billingLocationTypeID}",
566 "postal_code" => "billing_postal_code-{$billingLocationTypeID}",
567 "state_province" => "state_province-{$billingLocationTypeID}",
568 "country" => "country-{$billingLocationTypeID}",
572 foreach ($addressParts as $name => $field) {
573 $value = $params[$field] ??
NULL;
574 $alternateName = 'billing_' . $name . '_id-' . $billingLocationTypeID;
575 $alternate2 = 'billing_' . $name . '-' . $billingLocationTypeID;
576 if (isset($params[$alternate2]) && !isset($params[$alternateName])) {
577 $alternateName = $alternate2;
579 //Include values which prepend 'billing_' to country and state_province.
580 if (!empty($params[$alternateName])) {
581 if (empty($value) ||
!is_numeric($value)) {
582 $value = $params[$alternateName];
585 if (is_numeric($value) && ($name == 'state_province' ||
$name == 'country')) {
586 if ($name == 'state_province') {
587 $addressFields[$name] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
588 $addressFields[$name . '_name'] = CRM_Core_PseudoConstant
::stateProvince($value);
590 if ($name == 'country') {
591 $addressFields[$name] = CRM_Core_PseudoConstant
::countryIsoCode($value);
595 $addressFields[$name] = $value;
598 return CRM_Utils_Address
::format($addressFields);