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