Merge pull request #13042 from jackrabbithanna/dev-core-475
[civicrm-core.git] / CRM / Contact / Form / Edit / Address.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class is used to build address block.
36 */
37 class CRM_Contact_Form_Edit_Address {
38
39 /**
40 * Build form for address input fields.
41 *
42 * @param CRM_Core_Form $form
43 * @param int $addressBlockCount
44 * The index of the address array (if multiple addresses on a page).
45 * @param bool $sharing
46 * False, if we want to skip the address sharing features.
47 * @param bool $inlineEdit
48 * True when edit used in inline edit.
49 */
50 public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharing = TRUE, $inlineEdit = FALSE) {
51 // passing this via the session is AWFUL. we need to fix this
52 if (!$addressBlockCount) {
53 $blockId = ($form->get('Address_Block_Count')) ? $form->get('Address_Block_Count') : 1;
54 }
55 else {
56 $blockId = $addressBlockCount;
57 }
58
59 $form->applyFilter('__ALL__', 'trim');
60
61 $js = array();
62 if (!$inlineEdit) {
63 $js = array('onChange' => 'checkLocation( this.id );', 'placeholder' => NULL);
64 }
65
66 //make location type required for inline edit
67 $form->addField("address[$blockId][location_type_id]", array('entity' => 'address', 'class' => 'eight', 'option_url' => NULL) + $js, $inlineEdit);
68 if (!$inlineEdit) {
69 $js = array('id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
70 }
71
72 $form->addField(
73 "address[$blockId][is_primary]", array(
74 'entity' => 'address',
75 'label' => ts('Primary location for this contact'),
76 'text' => ts('Primary location for this contact')) + $js);
77
78 if (!$inlineEdit) {
79 $js = array('id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );');
80 }
81
82 $form->addField(
83 "address[$blockId][is_billing]", array(
84 'entity' => 'address',
85 'label' => ts('Billing location for this contact'),
86 'text' => ts('Billing location for this contact')) + $js);
87
88 // hidden element to store master address id
89 $form->addField("address[$blockId][master_id]", array('entity' => 'address', 'type' => 'hidden'));
90 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
91 'address_options', TRUE, NULL, TRUE
92 );
93
94 $elements = array(
95 'address_name',
96 'street_address',
97 'supplemental_address_1',
98 'supplemental_address_2',
99 'supplemental_address_3',
100 'city',
101 'postal_code',
102 'postal_code_suffix',
103 'country_id',
104 'state_province_id',
105 'county_id',
106 'geo_code_1',
107 'geo_code_2',
108 'street_number',
109 'street_name',
110 'street_unit',
111 );
112
113 foreach ($elements as $name) {
114 //Remove id from name, to allow comparison against enabled addressOptions.
115 $nameWithoutID = strpos($name, '_id') !== FALSE ? substr($name, 0, -3) : $name;
116 // Skip fields which are not enabled in the address options.
117 if (empty($addressOptions[$nameWithoutID])) {
118 $continue = TRUE;
119 //Don't skip street parsed fields when parsing is enabled.
120 if (in_array($nameWithoutID, array(
121 'street_number',
122 'street_name',
123 'street_unit',
124 )) && !empty($addressOptions['street_address_parsing'])
125 ) {
126 $continue = FALSE;
127 }
128 if ($continue) {
129 continue;
130 }
131 }
132 if ($name == 'address_name') {
133 $name = 'name';
134 }
135
136 $params = array('entity' => 'address');
137
138 if ($name == 'postal_code_suffix') {
139 $params['label'] = ts('Suffix');
140 }
141
142 $form->addField("address[$blockId][$name]", $params);
143 }
144
145 $entityId = NULL;
146 if (!empty($form->_values['address']) && !empty($form->_values['address'][$blockId])) {
147 $entityId = $form->_values['address'][$blockId]['id'];
148 }
149
150 // CRM-11665 geocode override option
151 $geoCode = FALSE;
152 if (CRM_Utils_GeocodeProvider::getUsableClassName()) {
153 $geoCode = TRUE;
154 $form->addElement('checkbox',
155 "address[$blockId][manual_geo_code]",
156 ts('Override automatic geocoding')
157 );
158 }
159 $form->assign('geoCode', $geoCode);
160
161 self::addCustomDataToForm($form, $entityId, $blockId);
162
163 if ($sharing) {
164 // shared address
165 $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
166
167 // Override the default profile links to add address form
168 $profileLinks = CRM_Contact_BAO_Contact::getEntityRefCreateLinks('shared_address');
169 $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), array('create' => $profileLinks));
170 }
171 }
172
173 /**
174 * Check for correct state / country mapping.
175 *
176 * @param array $fields
177 * @param array $files
178 * @param CRM_Core_Form $self
179 *
180 * @return array|bool
181 * if no errors
182 */
183 public static function formRule($fields, $files = array(), $self = NULL) {
184 $errors = array();
185
186 $customDataRequiredFields = array();
187 if ($self && property_exists($self, '_addressRequireOmission')) {
188 $customDataRequiredFields = explode(',', $self->_addressRequireOmission);
189 }
190
191 if (!empty($fields['address']) && is_array($fields['address'])) {
192 foreach ($fields['address'] as $instance => $addressValues) {
193
194 if (CRM_Utils_System::isNull($addressValues)) {
195 // DETACH 'required' form rule error to
196 // custom data only if address data not exists upon submission
197 if (!empty($customDataRequiredFields)) {
198 foreach ($customDataRequiredFields as $customElementName) {
199 $elementName = "address[$instance][$customElementName]";
200 if ($self->getElementError($elementName)) {
201 // set element error to none
202 $self->setElementError($elementName, NULL);
203 }
204 }
205 }
206 continue;
207 }
208
209 // DETACH 'required' form rule error to
210 // custom data if address data not exists upon submission
211 // or if master address is selected
212 if (!empty($customDataRequiredFields) && (!CRM_Core_BAO_Address::dataExists($addressValues) || !empty($addressValues['master_id']))) {
213 foreach ($customDataRequiredFields as $customElementName) {
214 $elementName = "address[$instance][$customElementName]";
215 if ($self->getElementError($elementName)) {
216 // set element error to none
217 $self->setElementError($elementName, NULL);
218 }
219 }
220 }
221
222 if (!empty($addressValues['use_shared_address']) && empty($addressValues['master_id'])) {
223 $errors["address[$instance][use_shared_address]"] = ts('Please select valid shared contact or a contact with valid address.');
224 }
225 }
226 }
227
228 return empty($errors) ? TRUE : $errors;
229 }
230
231 /**
232 * Set default values for address block.
233 *
234 * @param array $defaults
235 * Defaults associated array.
236 * @param CRM_Core_Form $form
237 * Form object.
238 */
239 public static function setDefaultValues(&$defaults, &$form) {
240 $addressValues = array();
241 if (isset($defaults['address']) && is_array($defaults['address']) &&
242 !CRM_Utils_System::isNull($defaults['address'])
243 ) {
244
245 // start of contact shared adddress defaults
246 $sharedAddresses = array();
247 $masterAddress = array();
248
249 // get contact name of shared contact names
250 $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
251
252 foreach ($defaults['address'] as $key => $addressValue) {
253 if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
254 $master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id'];
255 $sharedAddresses[$key]['shared_address_display'] = array(
256 'address' => $addressValue['display'],
257 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
258 'options' => CRM_Core_BAO_Address::getValues(array(
259 'entity_id' => $master_cid,
260 'contact_id' => $master_cid,
261 )),
262 'master_id' => $addressValue['master_id'],
263 );
264 $defaults['address'][$key]['master_contact_id'] = $master_cid;
265 }
266 else {
267 $defaults['address'][$key]['use_shared_address'] = 0;
268 }
269
270 //check if any address is shared by any other contacts
271 $masterAddress[$key] = CRM_Core_BAO_Address::checkContactSharedAddress($addressValue['id']);
272 }
273
274 $form->assign('sharedAddresses', $sharedAddresses);
275 $form->assign('masterAddress', $masterAddress);
276 // end of shared address defaults
277
278 // start of parse address functionality
279 // build street address, CRM-5450.
280 if ($form->_parseStreetAddress) {
281 $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
282 foreach ($defaults['address'] as $cnt => & $address) {
283 $streetAddress = NULL;
284 foreach (array(
285 'street_number',
286 'street_number_suffix',
287 'street_name',
288 'street_unit',
289 ) as $fld) {
290 if (in_array($fld, array(
291 'street_name',
292 'street_unit',
293 ))) {
294 $streetAddress .= ' ';
295 }
296 // CRM-17619 - if the street number suffix begins with a number, add a space
297 $numsuffix = CRM_Utils_Array::value($fld, $address);
298 if ($fld === 'street_number_suffix' && !empty($numsuffix)) {
299 if (ctype_digit(substr($numsuffix, 0, 1))) {
300 $streetAddress .= ' ';
301 }
302 }
303 $streetAddress .= CRM_Utils_Array::value($fld, $address);
304 }
305 $streetAddress = trim($streetAddress);
306 if (!empty($streetAddress)) {
307 $address['street_address'] = $streetAddress;
308 }
309 if (isset($address['street_number'])) {
310 // CRM-17619 - if the street number suffix begins with a number, add a space
311 $thesuffix = CRM_Utils_Array::value('street_number_suffix', $address);
312 if ($thesuffix) {
313 if (ctype_digit(substr($thesuffix, 0, 1))) {
314 $address['street_number'] .= " ";
315 }
316 }
317 $address['street_number'] .= $thesuffix;
318 }
319 // build array for set default.
320 foreach ($parseFields as $field) {
321 $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address);
322 }
323 // don't load fields, use js to populate.
324 foreach (array('street_number', 'street_name', 'street_unit') as $f) {
325 if (isset($address[$f])) {
326 unset($address[$f]);
327 }
328 }
329 }
330 $form->assign('allAddressFieldValues', json_encode($addressValues));
331
332 //hack to handle show/hide address fields.
333 $parsedAddress = array();
334 if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])
335 ) {
336 foreach ($_POST['address'] as $cnt => $values) {
337 $showField = 'streetAddress';
338 foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
339 if (!empty($values[$fld])) {
340 $showField = 'addressElements';
341 break;
342 }
343 }
344 $parsedAddress[$cnt] = $showField;
345 }
346 }
347 $form->assign('showHideAddressFields', $parsedAddress);
348 $form->assign('loadShowHideAddressFields', empty($parsedAddress) ? FALSE : TRUE);
349 }
350 // end of parse address functionality
351 }
352 }
353
354 /**
355 * Store required custom data info.
356 *
357 * @param CRM_Core_Form $form
358 * @param array $groupTree
359 */
360 public static function storeRequiredCustomDataInfo(&$form, $groupTree) {
361 if (in_array(CRM_Utils_System::getClassName($form), array('CRM_Contact_Form_Contact', 'CRM_Contact_Form_Inline_Address'))) {
362 $requireOmission = NULL;
363 foreach ($groupTree as $csId => $csVal) {
364 // only process Address entity fields
365 if ($csVal['extends'] != 'Address') {
366 continue;
367 }
368
369 foreach ($csVal['fields'] as $cdId => $cdVal) {
370 if ($cdVal['is_required']) {
371 $elementName = $cdVal['element_name'];
372 if (in_array($elementName, $form->_required)) {
373 // store the omitted rule for a element, to be used later on
374 $requireOmission .= $cdVal['element_custom_name'] . ',';
375 }
376 }
377 }
378 }
379
380 $form->_addressRequireOmission = rtrim($requireOmission, ',');
381 }
382 }
383
384 /**
385 * Add custom data to the form.
386 *
387 * @param CRM_Core_Form $form
388 * @param int $entityId
389 * @param int $blockId
390 */
391 protected static function addCustomDataToForm(&$form, $entityId, $blockId) {
392 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', NULL, $entityId);
393
394 if (isset($groupTree) && is_array($groupTree)) {
395 // use simplified formatted groupTree
396 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
397
398 // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
399 foreach ($groupTree as $id => $group) {
400 foreach ($group['fields'] as $fldId => $field) {
401 $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
402 $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
403 }
404 }
405
406 $defaults = array();
407 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults);
408
409 // since we change element name for address custom data, we need to format the setdefault values
410 $addressDefaults = array();
411 foreach ($defaults as $key => $val) {
412 if (!isset($val)) {
413 continue;
414 }
415
416 // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
417 // this works for all types custom data
418 $keyValues = explode('[', str_replace(']', '', $key));
419 $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
420 }
421
422 $form->setDefaults($addressDefaults);
423
424 // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
425 // And we can't set it to 'address_' because we want to set it in a slightly different format.
426 CRM_Core_BAO_CustomGroup::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
427
428 // during contact editing : if no address is filled
429 // required custom data must not produce 'required' form rule error
430 // more handling done in formRule func
431 CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
432
433 $tplGroupTree = CRM_Core_Smarty::singleton()
434 ->get_template_vars('address_groupTree');
435 $tplGroupTree = empty($tplGroupTree) ? array() : $tplGroupTree;
436
437 $form->assign('address_groupTree', $tplGroupTree + array($blockId => $groupTree));
438 // unset the temp smarty var that got created
439 $form->assign('dnc_groupTree', NULL);
440 }
441 // address custom data processing ends ..
442 }
443
444 }