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