Merge in 5.20
[civicrm-core.git] / CRM / Utils / 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 * Address Utilities
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Utils_Address {
19
20 /**
21 * Format an address string from address fields and a format string.
22 *
23 * Format an address basing on the address fields provided.
24 * Use Setting's address_format if there's no format specified.
25 *
26 * This function is also used to generate a contact's display_name and
27 * sort_name.
28 *
29 * @param array $fields
30 * The address 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 * If true indicates, the call has been made from mailing label.
37 * @param null $tokenFields
38 *
39 * @return string
40 * formatted address string
41 *
42 */
43 public static function format(
44 $fields,
45 $format = NULL,
46 $microformat = FALSE,
47 $mailing = FALSE,
48 $tokenFields = NULL
49 ) {
50 static $config = NULL;
51
52 if (!$format) {
53 $format = Civi::settings()->get('address_format');
54 }
55
56 if ($mailing) {
57 $format = Civi::settings()->get('mailing_format');
58 }
59
60 $formatted = $format;
61
62 $fullPostalCode = CRM_Utils_Array::value('postal_code', $fields);
63 if (!empty($fields['postal_code_suffix'])) {
64 $fullPostalCode .= "-$fields[postal_code_suffix]";
65 }
66
67 // make sure that some of the fields do have values
68 $emptyFields = [
69 'supplemental_address_1',
70 'supplemental_address_2',
71 'supplemental_address_3',
72 'state_province_name',
73 'county',
74 ];
75 foreach ($emptyFields as $f) {
76 if (!isset($fields[$f])) {
77 $fields[$f] = NULL;
78 }
79 }
80
81 //CRM-16876 Display countries in all caps when in mailing mode.
82 if ($mailing && !empty($fields['country'])) {
83 if (Civi::settings()->get('hideCountryMailingLabels')) {
84 $domain = CRM_Core_BAO_Domain::getDomain();
85 $domainLocation = CRM_Core_BAO_Location::getValues(['contact_id' => $domain->contact_id]);
86 $domainAddress = $domainLocation['address'][1];
87 $domainCountryId = $domainAddress['country_id'];
88 if ($fields['country'] == CRM_Core_PseudoConstant::country($domainCountryId)) {
89 $fields['country'] = NULL;
90 }
91 else {
92 //Capitalization display on uppercase to contries with special characters
93 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER, "UTF-8");
94 }
95 }
96 else {
97 $fields['country'] = mb_convert_case($fields['country'], MB_CASE_UPPER, "UTF-8");
98 }
99 }
100
101 if (!$microformat) {
102 // replacements in case of Individual Name Format
103 $replacements = [
104 'contact.display_name' => CRM_Utils_Array::value('display_name', $fields),
105 'contact.individual_prefix' => CRM_Utils_Array::value('individual_prefix', $fields),
106 'contact.formal_title' => CRM_Utils_Array::value('formal_title', $fields),
107 'contact.first_name' => CRM_Utils_Array::value('first_name', $fields),
108 'contact.middle_name' => CRM_Utils_Array::value('middle_name', $fields),
109 'contact.last_name' => CRM_Utils_Array::value('last_name', $fields),
110 'contact.individual_suffix' => CRM_Utils_Array::value('individual_suffix', $fields),
111 'contact.address_name' => CRM_Utils_Array::value('address_name', $fields),
112 'contact.street_address' => CRM_Utils_Array::value('street_address', $fields),
113 'contact.supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', $fields),
114 'contact.supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', $fields),
115 'contact.supplemental_address_3' => CRM_Utils_Array::value('supplemental_address_3', $fields),
116 'contact.city' => CRM_Utils_Array::value('city', $fields),
117 'contact.state_province_name' => CRM_Utils_Array::value('state_province_name', $fields),
118 'contact.county' => CRM_Utils_Array::value('county', $fields),
119 'contact.state_province' => CRM_Utils_Array::value('state_province', $fields),
120 'contact.postal_code' => $fullPostalCode,
121 'contact.country' => CRM_Utils_Array::value('country', $fields),
122 'contact.world_region' => CRM_Utils_Array::value('world_region', $fields),
123 'contact.geo_code_1' => CRM_Utils_Array::value('geo_code_1', $fields),
124 'contact.geo_code_2' => CRM_Utils_Array::value('geo_code_2', $fields),
125 'contact.current_employer' => CRM_Utils_Array::value('current_employer', $fields),
126 'contact.nick_name' => CRM_Utils_Array::value('nick_name', $fields),
127 'contact.email' => CRM_Utils_Array::value('email', $fields),
128 'contact.im' => CRM_Utils_Array::value('im', $fields),
129 'contact.do_not_email' => CRM_Utils_Array::value('do_not_email', $fields),
130 'contact.do_not_phone' => CRM_Utils_Array::value('do_not_phone', $fields),
131 'contact.do_not_mail' => CRM_Utils_Array::value('do_not_mail', $fields),
132 'contact.do_not_sms' => CRM_Utils_Array::value('do_not_sms', $fields),
133 'contact.do_not_trade' => CRM_Utils_Array::value('do_not_trade', $fields),
134 'contact.job_title' => CRM_Utils_Array::value('job_title', $fields),
135 'contact.birth_date' => CRM_Utils_Array::value('birth_date', $fields),
136 'contact.gender' => CRM_Utils_Array::value('gender', $fields),
137 'contact.is_opt_out' => CRM_Utils_Array::value('is_opt_out', $fields),
138 'contact.preferred_mail_format' => CRM_Utils_Array::value('preferred_mail_format', $fields),
139 'contact.phone' => CRM_Utils_Array::value('phone', $fields),
140 'contact.home_URL' => CRM_Utils_Array::value('home_URL', $fields),
141 'contact.contact_source' => CRM_Utils_Array::value('contact_source', $fields),
142 'contact.external_identifier' => CRM_Utils_Array::value('external_identifier', $fields),
143 'contact.contact_id' => CRM_Utils_Array::value('id', $fields),
144 'contact.household_name' => CRM_Utils_Array::value('display_name', $fields),
145 'contact.organization_name' => CRM_Utils_Array::value('display_name', $fields),
146 'contact.legal_name' => CRM_Utils_Array::value('legal_name', $fields),
147 'contact.preferred_communication_method' => CRM_Utils_Array::value('preferred_communication_method', $fields),
148 'contact.communication_style' => CRM_Utils_Array::value('communication_style', $fields),
149 'contact.addressee' => CRM_Utils_Array::value('addressee_display', $fields),
150 'contact.email_greeting' => CRM_Utils_Array::value('email_greeting_display', $fields),
151 'contact.postal_greeting' => CRM_Utils_Array::value('postal_greeting_display', $fields),
152 ];
153 }
154 else {
155 $replacements = [
156 'contact.address_name' => "<span class=\"address-name\">" . $fields['address_name'] . "</span>",
157 'contact.street_address' => "<span class=\"street-address\">" . $fields['street_address'] . "</span>",
158 'contact.supplemental_address_1' => "<span class=\"extended-address\">" . $fields['supplemental_address_1'] . "</span>",
159 'contact.supplemental_address_2' => $fields['supplemental_address_2'],
160 'contact.supplemental_address_3' => $fields['supplemental_address_3'],
161 'contact.city' => "<span class=\"locality\">" . $fields['city'] . "</span>",
162 'contact.state_province_name' => "<span class=\"region\">" . $fields['state_province_name'] . "</span>",
163 'contact.county' => "<span class=\"region\">" . $fields['county'],
164 'contact.state_province' => "<span class=\"region\">" . $fields['state_province'] . "</span>",
165 'contact.postal_code' => "<span class=\"postal-code\">" . $fullPostalCode . "</span>",
166 'contact.country' => "<span class=\"country-name\">" . $fields['country'] . "</span>",
167 'contact.world_region' => "<span class=\"region\">" . $fields['world_region'] . "</span>",
168 ];
169
170 // erase all empty ones, so we dont get blank lines
171 foreach (array_keys($replacements) as $key) {
172 $exactKey = substr($key, 0, 8) == 'contact.' ? substr($key, 8) : $key;
173 if ($key != 'contact.postal_code' &&
174 CRM_Utils_Array::value($exactKey, $fields) == NULL
175 ) {
176 $replacements[$key] = '';
177 }
178 }
179 if (empty($fullPostalCode)) {
180 $replacements['contact.postal_code'] = '';
181 }
182 }
183
184 // replacements in case of Custom Token
185 if (stristr($formatted, 'custom_')) {
186 $customToken = array_keys($fields);
187 foreach ($customToken as $value) {
188 if (substr($value, 0, 7) == 'custom_') {
189 $replacements["contact.{$value}"] = $fields["{$value}"];
190 }
191 }
192 }
193
194 // also sub all token fields
195 if ($tokenFields) {
196 foreach ($tokenFields as $token) {
197 $replacements["{$token}"] = CRM_Utils_Array::value("{$token}", $fields);
198 }
199 }
200
201 // for every token, replace {fooTOKENbar} with fooVALUEbar if
202 // the value is not empty, otherwise drop the whole {fooTOKENbar}
203 foreach ($replacements as $token => $value) {
204 if ($value && is_string($value) || is_numeric($value)) {
205 $formatted = preg_replace("/{([^{}]*)\b{$token}\b([^{}]*)}/u", "\${1}{$value}\${2}", $formatted);
206 }
207 else {
208 $formatted = preg_replace("/{[^{}]*\b{$token}\b[^{}]*}/u", '', $formatted);
209 }
210 }
211
212 // drop any {...} constructs from lines' ends
213 if (!$microformat) {
214 $formatted = "\n$formatted\n";
215 }
216 else {
217 if ($microformat == 1) {
218 $formatted = "\n<div class=\"location vcard\"><span class=\"adr\">\n$formatted</span></div>\n";
219 }
220 else {
221 $formatted = "\n<div class=\"vcard\"><span class=\"adr\">$formatted</span></div>\n";
222 }
223 }
224
225 $formatted = preg_replace('/\n{[^{}]*}/u', "\n", $formatted);
226 $formatted = preg_replace('/{[^{}]*}\n/u', "\n", $formatted);
227
228 // if there are any 'sibling' {...} constructs, replace them with the
229 // contents of the first one; for example, when there's no state_province:
230 // 1. {city}{, }{state_province}{ }{postal_code}
231 // 2. San Francisco{, }{ }12345
232 // 3. San Francisco, 12345
233 $formatted = preg_replace('/{([^{}]*)}({[^{}]*})+/u', '\1', $formatted);
234
235 // drop any remaining curly braces leaving their contents
236 $formatted = str_replace(['{', '}'], '', $formatted);
237
238 // drop any empty lines left after the replacements
239 $formatted = preg_replace('/^[ \t]*[\r\n]+/m', '', $formatted);
240
241 if (!$microformat) {
242 $finalFormatted = $formatted;
243 }
244 else {
245 // remove \n from each line and only add at the end
246 // this hack solves formatting issue, when we convert nl2br
247 $lines = [];
248 $count = 1;
249 $finalFormatted = NULL;
250 $formattedArray = explode("\n", $formatted);
251 $formattedArray = array_filter($formattedArray);
252
253 foreach ($formattedArray as $line) {
254 $line = trim($line);
255 if ($line) {
256 if ($count > 1 && $count < count($formattedArray)) {
257 $line = "$line\n";
258 }
259 $finalFormatted .= $line;
260 $count++;
261 }
262 }
263 }
264 return $finalFormatted;
265 }
266
267 /**
268 * @param $format
269 *
270 * @return array
271 */
272 public static function sequence($format) {
273 // also compute and store the address sequence
274 $addressSequence = [
275 'address_name',
276 'street_address',
277 'supplemental_address_1',
278 'supplemental_address_2',
279 'supplemental_address_3',
280 'city',
281 'county',
282 'state_province',
283 'postal_code',
284 'country',
285 ];
286
287 // get the field sequence from the format
288 $newSequence = [];
289 foreach ($addressSequence as $field) {
290 if (substr_count($format, $field)) {
291 $newSequence[strpos($format, $field)] = $field;
292 }
293 }
294 ksort($newSequence);
295
296 // add the addressSequence fields that are missing in the addressFormat
297 // to the end of the list, so that (for example) if state_province is not
298 // specified in the addressFormat it's still in the address-editing form
299 $newSequence = array_merge($newSequence, $addressSequence);
300 $newSequence = array_unique($newSequence);
301 return $newSequence;
302 }
303
304 /**
305 * Extract the billing fields from the form submission and format them for display.
306 *
307 * @param array $params
308 * @param int $billingLocationTypeID
309 *
310 * @return string
311 */
312 public static function getFormattedBillingAddressFieldsFromParameters($params, $billingLocationTypeID) {
313 $addressParts = [
314 "street_address" => "billing_street_address-{$billingLocationTypeID}",
315 "city" => "billing_city-{$billingLocationTypeID}",
316 "postal_code" => "billing_postal_code-{$billingLocationTypeID}",
317 "state_province" => "state_province-{$billingLocationTypeID}",
318 "country" => "country-{$billingLocationTypeID}",
319 ];
320
321 $addressFields = [];
322 foreach ($addressParts as $name => $field) {
323 $value = CRM_Utils_Array::value($field, $params);
324 $alternateName = 'billing_' . $name . '_id-' . $billingLocationTypeID;
325 $alternate2 = 'billing_' . $name . '-' . $billingLocationTypeID;
326 if (isset($params[$alternate2]) && !isset($params[$alternateName])) {
327 $alternateName = $alternate2;
328 }
329 //Include values which prepend 'billing_' to country and state_province.
330 if (!empty($params[$alternateName])) {
331 if (empty($value) || !is_numeric($value)) {
332 $value = $params[$alternateName];
333 }
334 }
335 if (is_numeric($value) && ($name == 'state_province' || $name == 'country')) {
336 if ($name == 'state_province') {
337 $addressFields[$name] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
338 $addressFields[$name . '_name'] = CRM_Core_PseudoConstant::stateProvince($value);
339 }
340 if ($name == 'country') {
341 $addressFields[$name] = CRM_Core_PseudoConstant::countryIsoCode($value);
342 }
343 }
344 else {
345 $addressFields[$name] = $value;
346 }
347 }
348 return CRM_Utils_Address::format($addressFields);
349 }
350
351 }