Remove overlay.tpl
[civicrm-core.git] / CRM / Contact / Form / Edit / Address.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class is used to build address block
38 */
39 class CRM_Contact_Form_Edit_Address {
40
41 /**
42 * build form for address input fields
43 *
44 * @param object $form - CRM_Core_Form (or subclass)
45 * @param int $addressBlockCount - the index of the address array (if multiple addresses on a page)
46 * @param boolean $sharing - false, if we want to skip the address sharing features
47 * @param boolean $inlineEdit true when edit used in inline edit
48 *
49 * @return void
50 *
51 * @access public
52 * @static
53 */
54 static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharing = TRUE, $inlineEdit = FALSE) {
55 // passing this via the session is AWFUL. we need to fix this
56 if (!$addressBlockCount) {
57 $blockId = ($form->get('Address_Block_Count')) ? $form->get('Address_Block_Count') : 1;
58 }
59 else {
60 $blockId = $addressBlockCount;
61 }
62
63 $config = CRM_Core_Config::singleton();
64 $countryDefault = $config->defaultContactCountry;
65
66 $form->applyFilter('__ALL__', 'trim');
67
68 $js = array();
69 if ( !$inlineEdit ) {
70 $js = array('onChange' => 'checkLocation( this.id );');
71 }
72
73 $form->addElement('select',
74 "address[$blockId][location_type_id]",
75 ts('Location Type'),
76 array(
77 '' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'),
78 $js
79 );
80
81 if ( !$inlineEdit ) {
82 $js = array('id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
83 }
84 else {
85 //make location type required for inline edit
86 $form->addRule( "address[$blockId][location_type_id]", ts('%1 is a required field.', array(1 => ts('Location Type'))), 'required');
87 }
88
89 $form->addElement(
90 'checkbox',
91 "address[$blockId][is_primary]",
92 ts('Primary location for this contact'),
93 ts('Primary location for this contact'),
94 $js
95 );
96
97 if ( !$inlineEdit ) {
98 $js = array('id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );');
99 }
100
101 $form->addElement(
102 'checkbox',
103 "address[$blockId][is_billing]",
104 ts('Billing location for this contact'),
105 ts('Billing location for this contact'),
106 $js
107 );
108
109 // hidden element to store master address id
110 $form->addElement('hidden', "address[$blockId][master_id]");
111
112 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
113 'address_options', TRUE, NULL, TRUE
114 );
115 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
116
117 $elements = array(
118 'address_name' => array(ts('Address Name'), $attributes['address_name'], NULL),
119 'street_address' => array(ts('Street Address'), $attributes['street_address'], NULL),
120 'supplemental_address_1' => array(ts('Supplemental Address 1'), $attributes['supplemental_address_1'], NULL),
121 'supplemental_address_2' => array(ts('Supplemental Address 2'), $attributes['supplemental_address_2'], NULL),
122 'city' => array(ts('City'), $attributes['city'], NULL),
123 'postal_code' => array(ts('Zip / Postal Code'), array_merge($attributes['postal_code'], array('class' => 'crm_postal_code')), NULL),
124 'postal_code_suffix' => array(ts('Postal Code Suffix'), array('size' => 4, 'maxlength' => 12, 'class' => 'crm_postal_code_suffix'), NULL),
125 'county_id' => array(ts('County'), $attributes['county_id'], NULL),
126 'state_province_id' => array(ts('State / Province'), $attributes['state_province_id'], NULL),
127 'country_id' => array(ts('Country'), $attributes['country_id'], NULL),
128 'geo_code_1' => array(ts('Latitude'), array('size' => 9, 'maxlength' => 11), NULL),
129 'geo_code_2' => array(ts('Longitude'), array('size' => 9, 'maxlength' => 11), NULL),
130 'street_number' => array(ts('Street Number'), $attributes['street_number'], NULL),
131 'street_name' => array(ts('Street Name'), $attributes['street_name'], NULL),
132 'street_unit' => array(ts('Apt/Unit/Suite'), $attributes['street_unit'], NULL),
133 );
134
135 $stateCountryMap = array();
136 foreach ($elements as $name => $v) {
137 list($title, $attributes, $select) = $v;
138
139 $nameWithoutID = strpos($name, '_id') !== FALSE ? substr($name, 0, -3) : $name;
140 if (empty($addressOptions[$nameWithoutID])) {
141 $continue = TRUE;
142 if (in_array($nameWithoutID, array(
143 'street_number', 'street_name', 'street_unit')) && !empty($addressOptions['street_address_parsing'])) {
144 $continue = FALSE;
145 }
146 if ($continue) {
147 continue;
148 }
149 }
150
151 if (!$attributes) {
152 $attributes = $attributes[$name];
153 }
154
155 //build normal select if country is not present in address block
156 if ($name == 'state_province_id' && !$addressOptions['country']) {
157 $select = 'stateProvince';
158 }
159
160 if (!$select) {
161 if ($name == 'country_id' || $name == 'state_province_id' || $name == 'county_id') {
162 if ($name == 'country_id') {
163 $stateCountryMap[$blockId]['country'] = "address_{$blockId}_{$name}";
164 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
165 }
166 elseif ($name == 'state_province_id') {
167 $stateCountryMap[$blockId]['state_province'] = "address_{$blockId}_{$name}";
168 if ($countryDefault) {
169 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvinceForCountry($countryDefault);
170 }
171 else {
172 $selectOptions = array('' => ts('- select a country -'));
173 }
174 }
175 elseif ($name == 'county_id') {
176 $stateCountryMap[$blockId]['county'] = "address_{$blockId}_{$name}";
177 if ($form->getSubmitValue("address[{$blockId}][state_province_id]")) {
178 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant::countyForState($form->getSubmitValue("address[{$blockId}][state_province_id]"));
179 }
180 elseif ($form->getSubmitValue("address[{$blockId}][county_id]")) {
181 $selectOptions = array('' => ts('- select a state -')) + CRM_Core_PseudoConstant::county();
182 }
183 else {
184 $selectOptions = array('' => ts('- select a state -'));
185 }
186 }
187 $form->addElement('select',
188 "address[$blockId][$name]",
189 $title,
190 $selectOptions
191 );
192 }
193 else {
194 if ($name == 'address_name') {
195 $name = 'name';
196 }
197
198 $form->addElement('text',
199 "address[$blockId][$name]",
200 $title,
201 $attributes
202 );
203 }
204 }
205 else {
206 if ($name == 'state_province_id') {
207 $stateCountryMap[$blockId]['state_province'] = "address_{$blockId}_{$name}";
208 }
209 $form->addElement('select',
210 "address[$blockId][$name]",
211 $title,
212 array('' => ts('- select -')) + CRM_Core_PseudoConstant::$select()
213 );
214 }
215 }
216
217 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
218
219 $entityId = NULL;
220 if (!empty($form->_values['address']) && !empty($form->_values['address'][$blockId])) {
221 $entityId = $form->_values['address'][$blockId]['id'];
222 }
223
224 // CRM-11665 geocode override option
225 $geoCode = FALSE;
226 if (!empty($config->geocodeMethod)) {
227 $geoCode = TRUE;
228 $form->addElement('checkbox',
229 "address[$blockId][manual_geo_code]",
230 ts('Override automatic geocoding')
231 );
232 }
233 $form->assign('geoCode', $geoCode);
234
235 // Process any address custom data -
236 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address',
237 $form,
238 $entityId
239 );
240
241 if (isset($groupTree) && is_array($groupTree)) {
242 // use simplified formatted groupTree
243 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
244
245 // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
246 foreach ($groupTree as $id => $group) {
247 foreach ($group['fields'] as $fldId => $field) {
248 $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
249 $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
250 }
251 }
252
253 $defaults = array();
254 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults);
255
256 // since we change element name for address custom data, we need to format the setdefault values
257 $addressDefaults = array();
258 foreach ($defaults as $key => $val) {
259 if ( empty( $val ) ) {
260 continue;
261 }
262
263 // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
264 // this works for all types custom data
265 $keyValues = explode('[', str_replace(']', '', $key));
266 $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
267 }
268
269 $form->setDefaults($addressDefaults);
270
271 // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
272 // And we can't set it to 'address_' because we want to set it in a slightly different format.
273 CRM_Core_BAO_CustomGroup::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
274
275 // during contact editing : if no address is filled
276 // required custom data must not produce 'required' form rule error
277 // more handling done in formRule func
278 if (!$inlineEdit) {
279 CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
280 }
281
282 $template = CRM_Core_Smarty::singleton();
283 $tplGroupTree = $template->get_template_vars('address_groupTree');
284 $tplGroupTree = empty($tplGroupTree) ? array(
285 ) : $tplGroupTree;
286
287 $form->assign('address_groupTree', $tplGroupTree + array($blockId => $groupTree));
288 // unset the temp smarty var that got created
289 $form->assign('dnc_groupTree', NULL);
290 }
291 // address custom data processing ends ..
292
293 if ($sharing) {
294 // shared address
295 $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
296
297 // get the reserved for address
298 $profileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'shared_address', 'id', 'name');
299
300 if (!$profileId) {
301 CRM_Core_Error::fatal(ts('Your install is missing required "Shared Address" profile.'));
302 }
303
304 CRM_Contact_Form_NewContact::buildQuickForm($form, $blockId, array($profileId));
305 }
306 }
307
308 /**
309 * check for correct state / country mapping.
310 *
311 * @param array reference $fields - submitted form values.
312 * @param array reference $errors - if any errors found add to this array. please.
313 *
314 * @return true if no errors
315 * array of errors if any present.
316 *
317 * @access public
318 * @static
319 */
320 static function formRule($fields, $files, $self) {
321 $errors = array();
322
323 $customDataRequiredFields = array();
324 if ($self && property_exists($self, '_addressRequireOmission')) {
325 $customDataRequiredFields = explode(',', $self->_addressRequireOmission);
326 }
327
328 // check for state/county match if not report error to user.
329 if (!empty($fields['address']) && is_array($fields['address'])) {
330 foreach ($fields['address'] as $instance => $addressValues) {
331
332 if (CRM_Utils_System::isNull($addressValues)) {
333 // DETACH 'required' form rule error to
334 // custom data only if address data not exists upon submission
335 if (!empty($customDataRequiredFields)) {
336 foreach($customDataRequiredFields as $customElementName) {
337 $elementName = "address[$instance][$customElementName]";
338 if ($self->getElementError($elementName)) {
339 // set element error to none
340 $self->setElementError($elementName, NULL);
341 }
342 }
343 }
344 continue;
345 }
346
347 // DETACH 'required' form rule error to
348 // custom data only if address data not exists upon submission
349 if (!empty($customDataRequiredFields) && !CRM_Core_BAO_Address::dataExists($addressValues)) {
350 foreach($customDataRequiredFields as $customElementName) {
351 $elementName = "address[$instance][$customElementName]";
352 if ($self->getElementError($elementName)) {
353 // set element error to none
354 $self->setElementError($elementName, NULL);
355 }
356 }
357 }
358
359 $countryId = CRM_Utils_Array::value('country_id', $addressValues);
360
361 $stateProvinceId = CRM_Utils_Array::value('state_province_id', $addressValues);
362
363 //do check for mismatch countries
364 if ($stateProvinceId && $countryId) {
365 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
366 $stateProvinceDAO->id = $stateProvinceId;
367 $stateProvinceDAO->find(TRUE);
368 if ($stateProvinceDAO->country_id != $countryId) {
369 // countries mismatch hence display error
370 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
371 $countries = CRM_Core_PseudoConstant::country();
372 $errors["address[$instance][state_province_id]"] = ts('State/Province %1 is not part of %2. It belongs to %3.',
373 array(
374 1 => $stateProvinces[$stateProvinceId],
375 2 => $countries[$countryId],
376 3 => $countries[$stateProvinceDAO->country_id]
377 )
378 );
379 }
380 }
381
382 $countyId = CRM_Utils_Array::value('county_id', $addressValues);
383
384 //state county validation
385 if ($stateProvinceId && $countyId) {
386 $countyDAO = new CRM_Core_DAO_County();
387 $countyDAO->id = $countyId;
388 $countyDAO->find(TRUE);
389 if ($countyDAO->state_province_id != $stateProvinceId) {
390 $counties = CRM_Core_PseudoConstant::county();
391 $errors["address[$instance][county_id]"] = ts('County %1 is not part of %2. It belongs to %3.',
392 array(
393 1 => $counties[$countyId],
394 2 => $stateProvinces[$stateProvinceId],
395 3 => $stateProvinces[$countyDAO->state_province_id]
396 )
397 );
398 }
399 }
400
401 if (!empty($addressValues['use_shared_address']) && empty($addressValues['master_id'])) {
402 $errors["address[$instance][use_shared_address]"] = ts('Please select valid shared contact or a contact with valid address.');
403 }
404 }
405 }
406
407 return empty($errors) ? TRUE : $errors;
408 }
409
410 static function fixStateSelect(&$form,
411 $countryElementName,
412 $stateElementName,
413 $countyElementName,
414 $countryDefaultValue,
415 $stateDefaultValue = NULL
416 ) {
417 $countryID = $stateID = NULL;
418 if (isset($form->_elementIndex[$countryElementName])) {
419 //get the country id to load states -
420 //first check for submitted value,
421 //then check for user passed value.
422 //finally check for element default val.
423 $submittedVal = $form->getSubmitValue($countryElementName);
424 if ($submittedVal) {
425 $countryID = $submittedVal;
426 }
427 elseif ($countryDefaultValue) {
428 $countryID = $countryDefaultValue;
429 }
430 else {
431 $countryID = CRM_Utils_Array::value(0, $form->getElementValue($countryElementName));
432 }
433 }
434 $stateTitle = ts('State/Province');
435 if (isset($form->_fields[$stateElementName]['title'])) {
436 $stateTitle = $form->_fields[$stateElementName]['title'];
437 }
438
439 if (isset($form->_elementIndex[$stateElementName])) {
440 $submittedValState = $form->getSubmitValue($stateElementName);
441 if ($submittedValState) {
442 $stateID = $submittedValState;
443 }
444 elseif ($stateDefaultValue) {
445 $stateID = $stateDefaultValue;
446 }
447 else {
448 $stateID = CRM_Utils_Array::value(0, $form->getElementValue($stateElementName));
449 }
450 }
451
452 if (isset($form->_elementIndex[$stateElementName])) {
453 if ($countryID) {
454 $stateProvinces = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID);
455 }
456 else {
457 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
458 }
459
460 $stateSelect = & $form->addElement('select', $stateElementName, $stateTitle,
461 array('' => ts('- select -')) + $stateProvinces);
462 }
463
464 if (isset($form->_elementIndex[$stateElementName]) && isset($form->_elementIndex[$countyElementName])) {
465 if ($stateID) {
466 $counties = CRM_Core_PseudoConstant::countyForState($stateID);
467 }
468 else {
469 $counties = CRM_Core_PseudoConstant::county();
470 }
471
472 $form->addElement('select', $countyElementName, ts('County'), array('' => ts('- select -')) + $counties);
473 }
474
475 // CRM-7296 freeze the select for state if address is shared with household
476 // CRM-9070 freeze the select for state if it is view only
477 if (isset($form->_fields) && !empty($form->_fields[$stateElementName]) &&
478 (!empty($form->_fields[$stateElementName]['is_shared']) || !empty($form->_fields[$stateElementName]['is_view']))
479 ) {
480 $stateSelect->freeze();
481 }
482 }
483
484 /**
485 * function to set default values for address block
486 *
487 * @param array $defaults defaults associated array
488 * @param object $form form object
489 *
490 * @static
491 * @access public
492 */
493 static function setDefaultValues( &$defaults, &$form ) {
494 $addressValues = array();
495 if (isset($defaults['address']) && is_array($defaults['address']) &&
496 !CRM_Utils_System::isNull($defaults['address'])
497 ) {
498
499 // start of contact shared adddress defaults
500 $sharedAddresses = array();
501 $masterAddress = array();
502
503 // get contact name of shared contact names
504 $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
505
506 foreach ($defaults['address'] as $key => $addressValue) {
507 if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
508 $sharedAddresses[$key]['shared_address_display'] = array(
509 'address' => $addressValue['display'],
510 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
511 );
512 }
513 else {
514 $defaults['address'][$key]['use_shared_address'] = 0;
515 }
516
517 //check if any address is shared by any other contacts
518 $masterAddress[$key] = CRM_Core_BAO_Address::checkContactSharedAddress($addressValue['id']);
519 }
520
521 $form->assign('sharedAddresses', $sharedAddresses);
522 $form->assign('masterAddress', $masterAddress);
523 // end of shared address defaults
524
525 // start of parse address functionality
526 // build street address, CRM-5450.
527 if ($form->_parseStreetAddress) {
528 $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
529 foreach ($defaults['address'] as $cnt => & $address) {
530 $streetAddress = NULL;
531 foreach (array(
532 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
533 if (in_array($fld, array(
534 'street_name', 'street_unit'))) {
535 $streetAddress .= ' ';
536 }
537 $streetAddress .= CRM_Utils_Array::value($fld, $address);
538 }
539 $streetAddress = trim($streetAddress);
540 if (!empty($streetAddress)) {
541 $address['street_address'] = $streetAddress;
542 }
543 if (isset($address['street_number'])) {
544 $address['street_number'] .= CRM_Utils_Array::value('street_number_suffix', $address);
545 }
546
547 // build array for set default.
548 foreach ($parseFields as $field) {
549 $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address);
550 }
551 // don't load fields, use js to populate.
552 foreach (array('street_number', 'street_name', 'street_unit') as $f) {
553 if (isset($address[$f])) {
554 unset($address[$f]);
555 }
556 }
557 }
558 $form->assign('allAddressFieldValues', json_encode($addressValues));
559
560 //hack to handle show/hide address fields.
561 $parsedAddress = array();
562 if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])
563 ) {
564 foreach ($_POST['address'] as $cnt => $values) {
565 $showField = 'streetAddress';
566 foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
567 if (!empty($values[$fld])) {
568 $showField = 'addressElements';
569 break;
570 }
571 }
572 $parsedAddress[$cnt] = $showField;
573 }
574 }
575 $form->assign('showHideAddressFields', $parsedAddress);
576 $form->assign('loadShowHideAddressFields', empty($parsedAddress) ? FALSE : TRUE);
577 }
578 // end of parse address functionality
579 }
580 }
581
582
583 static function storeRequiredCustomDataInfo(&$form, $groupTree) {
584 if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
585 $requireOmission = NULL;
586 foreach ($groupTree as $csId => $csVal) {
587 // only process Address entity fields
588 if ($csVal['extends'] != 'Address') {
589 continue;
590 }
591
592 foreach ($csVal['fields'] as $cdId => $cdVal) {
593 if ($cdVal['is_required']) {
594 $elementName = $cdVal['element_name'];
595 if (in_array($elementName, $form->_required)) {
596 // store the omitted rule for a element, to be used later on
597 $requireOmission .= $cdVal['element_custom_name'] . ',';
598 }
599 }
600 }
601 }
602
603 $form->_addressRequireOmission = rtrim($requireOmission, ',');
604 }
605 }
606 }