Merge pull request #13982 from colemanw/then
[civicrm-core.git] / CRM / Contact / Form / Contact.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 generates form components generic to all the contact types.
36 *
37 * It delegates the work to lower level subclasses and integrates the changes
38 * back in. It also uses a lot of functionality with the CRM API's, so any change
39 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
40 *
41 */
42 class CRM_Contact_Form_Contact extends CRM_Core_Form {
43
44 /**
45 * The contact type of the form.
46 *
47 * @var string
48 */
49 public $_contactType;
50
51 /**
52 * The contact type of the form.
53 *
54 * @var string
55 */
56 public $_contactSubType;
57
58 /**
59 * The contact id, used when editing the form
60 *
61 * @var int
62 */
63 public $_contactId;
64
65 /**
66 * The default group id passed in via the url.
67 *
68 * @var int
69 */
70 public $_gid;
71
72 /**
73 * The default tag id passed in via the url.
74 *
75 * @var int
76 */
77 public $_tid;
78
79 /**
80 * Name of de-dupe button
81 *
82 * @var string
83 */
84 protected $_dedupeButtonName;
85
86 /**
87 * Name of optional save duplicate button.
88 *
89 * @var string
90 */
91 protected $_duplicateButtonName;
92
93 protected $_editOptions = [];
94
95 protected $_oldSubtypes = [];
96
97 public $_blocks;
98
99 public $_values = [];
100
101 public $_action;
102
103 public $_customValueCount;
104 /**
105 * The array of greetings with option group and filed names.
106 *
107 * @var array
108 */
109 public $_greetings;
110
111 /**
112 * Do we want to parse street address.
113 */
114 public $_parseStreetAddress;
115
116 /**
117 * Check contact has a subtype or not.
118 */
119 public $_isContactSubType;
120
121 /**
122 * Lets keep a cache of all the values that we retrieved.
123 * THis is an attempt to avoid the number of update statements
124 * during the write phase
125 */
126 public $_preEditValues;
127
128 /**
129 * Explicitly declare the entity api name.
130 */
131 public function getDefaultEntity() {
132 return 'Contact';
133 }
134
135 /**
136 * Explicitly declare the form context.
137 */
138 public function getDefaultContext() {
139 return 'create';
140 }
141
142 /**
143 * Build all the data structures needed to build the form.
144 */
145 public function preProcess() {
146 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
147
148 $this->_dedupeButtonName = $this->getButtonName('refresh', 'dedupe');
149 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
150
151 CRM_Core_Resources::singleton()
152 ->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
153
154 $session = CRM_Core_Session::singleton();
155 if ($this->_action == CRM_Core_Action::ADD) {
156 // check for add contacts permissions
157 if (!CRM_Core_Permission::check('add contacts')) {
158 CRM_Utils_System::permissionDenied();
159 CRM_Utils_System::civiExit();
160 }
161 $this->_contactType = CRM_Utils_Request::retrieve('ct', 'String',
162 $this, TRUE, NULL, 'REQUEST'
163 );
164 if (!in_array($this->_contactType,
165 ['Individual', 'Household', 'Organization']
166 )
167 ) {
168 CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type'));
169 }
170
171 $this->_isContactSubType = FALSE;
172 if ($this->_contactSubType = CRM_Utils_Request::retrieve('cst', 'String', $this)) {
173 $this->_isContactSubType = TRUE;
174 }
175
176 if (
177 $this->_contactSubType &&
178 !(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE))
179 ) {
180 CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType]));
181 }
182
183 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer',
184 CRM_Core_DAO::$_nullObject,
185 FALSE, NULL, 'GET'
186 );
187 $this->_tid = CRM_Utils_Request::retrieve('tid', 'Integer',
188 CRM_Core_DAO::$_nullObject,
189 FALSE, NULL, 'GET'
190 );
191 $typeLabel = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $this->_contactSubType ?
192 $this->_contactSubType : $this->_contactType
193 );
194 $typeLabel = implode(' / ', $typeLabel);
195
196 CRM_Utils_System::setTitle(ts('New %1', [1 => $typeLabel]));
197 $session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1'));
198 $this->_contactId = NULL;
199 }
200 else {
201 //update mode
202 if (!$this->_contactId) {
203 $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
204 }
205
206 if ($this->_contactId) {
207 $defaults = [];
208 $params = ['id' => $this->_contactId];
209 $returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'];
210 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
211
212 if (empty($defaults['id'])) {
213 CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId]));
214 }
215
216 $this->_contactType = CRM_Utils_Array::value('contact_type', $defaults);
217 $this->_contactSubType = CRM_Utils_Array::value('contact_sub_type', $defaults);
218
219 // check for permissions
220 $session = CRM_Core_Session::singleton();
221 if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
222 CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
223 }
224
225 $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
226 if ($defaults['is_deceased']) {
227 $displayName .= ' <span class="crm-contact-deceased">(deceased)</span>';
228 }
229 $displayName = ts('Edit %1', [1 => $displayName]);
230
231 // Check if this is default domain contact CRM-10482
232 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) {
233 $displayName .= ' (' . ts('default organization') . ')';
234 }
235
236 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
237 CRM_Utils_System::setTitle($displayName);
238 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
239 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
240
241 $urlParams = 'reset=1&cid=' . $this->_contactId;
242 if ($context) {
243 $urlParams .= "&context=$context";
244 }
245
246 if (CRM_Utils_Rule::qfKey($qfKey)) {
247
248 $urlParams .= "&key=$qfKey";
249
250 }
251 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
252
253 $values = $this->get('values');
254 // get contact values.
255 if (!empty($values)) {
256 $this->_values = $values;
257 }
258 else {
259 $params = [
260 'id' => $this->_contactId,
261 'contact_id' => $this->_contactId,
262 'noRelationships' => TRUE,
263 'noNotes' => TRUE,
264 'noGroups' => TRUE,
265 ];
266
267 $contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE);
268 $this->set('values', $this->_values);
269 }
270 }
271 else {
272 CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type'));
273 }
274 }
275
276 // parse street address, CRM-5450
277 $this->_parseStreetAddress = $this->get('parseStreetAddress');
278 if (!isset($this->_parseStreetAddress)) {
279 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
280 'address_options'
281 );
282 $this->_parseStreetAddress = FALSE;
283 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
284 $this->_parseStreetAddress = TRUE;
285 }
286 $this->set('parseStreetAddress', $this->_parseStreetAddress);
287 }
288 $this->assign('parseStreetAddress', $this->_parseStreetAddress);
289
290 $this->_editOptions = $this->get('contactEditOptions');
291 if (CRM_Utils_System::isNull($this->_editOptions)) {
292 $this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
293 'contact_edit_options', TRUE, NULL,
294 FALSE, 'name', TRUE, 'AND v.filter = 0'
295 );
296 $this->set('contactEditOptions', $this->_editOptions);
297 }
298
299 // build demographics only for Individual contact type
300 if ($this->_contactType != 'Individual' &&
301 array_key_exists('Demographics', $this->_editOptions)
302 ) {
303 unset($this->_editOptions['Demographics']);
304 }
305
306 // in update mode don't show notes
307 if ($this->_contactId && array_key_exists('Notes', $this->_editOptions)) {
308 unset($this->_editOptions['Notes']);
309 }
310
311 $this->assign('editOptions', $this->_editOptions);
312 $this->assign('contactType', $this->_contactType);
313 $this->assign('contactSubType', $this->_contactSubType);
314
315 // get the location blocks.
316 $this->_blocks = $this->get('blocks');
317 if (CRM_Utils_System::isNull($this->_blocks)) {
318 $this->_blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
319 'contact_edit_options', TRUE, NULL,
320 FALSE, 'name', TRUE, 'AND v.filter = 1'
321 );
322 $this->set('blocks', $this->_blocks);
323 }
324 $this->assign('blocks', $this->_blocks);
325
326 // this is needed for custom data.
327 $this->assign('entityID', $this->_contactId);
328
329 // also keep the convention.
330 $this->assign('contactId', $this->_contactId);
331
332 // location blocks.
333 CRM_Contact_Form_Location::preProcess($this);
334
335 // retain the multiple count custom fields value
336 if (!empty($_POST['hidden_custom'])) {
337 $customGroupCount = CRM_Utils_Array::value('hidden_custom_group_count', $_POST);
338
339 if ($contactSubType = CRM_Utils_Array::value('contact_sub_type', $_POST)) {
340 $paramSubType = implode(',', $contactSubType);
341 }
342
343 $this->_getCachedTree = FALSE;
344 unset($customGroupCount[0]);
345 foreach ($customGroupCount as $groupID => $groupCount) {
346 if ($groupCount > 1) {
347 $this->set('groupID', $groupID);
348 //loop the group
349 for ($i = 0; $i <= $groupCount; $i++) {
350 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
351 $i, $this->_contactType, $this->_contactId
352 );
353 CRM_Contact_Form_Edit_CustomData::buildQuickForm($this);
354 }
355 }
356 }
357
358 //reset all the ajax stuff, for normal processing
359 if (isset($this->_groupTree)) {
360 $this->_groupTree = NULL;
361 }
362 $this->set('groupID', NULL);
363 $this->_getCachedTree = TRUE;
364 }
365
366 // execute preProcess dynamically by js else execute normal preProcess
367 if (array_key_exists('CustomData', $this->_editOptions)) {
368 //assign a parameter to pass for sub type multivalue
369 //custom field to load
370 if ($this->_contactSubType || isset($paramSubType)) {
371 $paramSubType = (isset($paramSubType)) ? $paramSubType :
372 str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_contactSubType, CRM_Core_DAO::VALUE_SEPARATOR));
373
374 $this->assign('paramSubType', $paramSubType);
375 }
376
377 if (CRM_Utils_Request::retrieve('type', 'String')) {
378 CRM_Contact_Form_Edit_CustomData::preProcess($this);
379 }
380 else {
381 $contactSubType = $this->_contactSubType;
382 // need contact sub type to build related grouptree array during post process
383 if (!empty($_POST['contact_sub_type'])) {
384 $contactSubType = $_POST['contact_sub_type'];
385 }
386 //only custom data has preprocess hence directly call it
387 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
388 1, $this->_contactType, $this->_contactId
389 );
390 $this->assign('customValueCount', $this->_customValueCount);
391 }
392 }
393 }
394
395 /**
396 * Set default values for the form.
397 *
398 * Note that in edit/view mode the default values are retrieved from the database
399 */
400 public function setDefaultValues() {
401 $defaults = $this->_values;
402
403 if ($this->_action & CRM_Core_Action::ADD) {
404 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
405 // set group and tag defaults if any
406 if ($this->_gid) {
407 $defaults['group'][] = $this->_gid;
408 }
409 if ($this->_tid) {
410 $defaults['tag'][$this->_tid] = 1;
411 }
412 }
413 if ($this->_contactSubType) {
414 $defaults['contact_sub_type'] = $this->_contactSubType;
415 }
416 }
417 else {
418 foreach ($defaults['email'] as $dontCare => & $val) {
419 if (isset($val['signature_text'])) {
420 $val['signature_text_hidden'] = $val['signature_text'];
421 }
422 if (isset($val['signature_html'])) {
423 $val['signature_html_hidden'] = $val['signature_html'];
424 }
425 }
426
427 if (!empty($defaults['contact_sub_type'])) {
428 $defaults['contact_sub_type'] = $this->_oldSubtypes;
429 }
430 }
431 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
432 foreach ($this->_editOptions as $name => $label) {
433 if (!in_array($name, ['Address', 'Notes'])) {
434 $className = 'CRM_Contact_Form_Edit_' . $name;
435 $className::setDefaultValues($this, $defaults);
436 }
437 }
438
439 //set address block defaults
440 CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this);
441
442 if (!empty($defaults['image_URL'])) {
443 $this->assign("imageURL", CRM_Utils_File::getImageURL($defaults['image_URL']));
444 }
445
446 //set location type and country to default for each block
447 $this->blockSetDefaults($defaults);
448
449 $this->_preEditValues = $defaults;
450 return $defaults;
451 }
452
453 /**
454 * Do the set default related to location type id, primary location, default country.
455 *
456 * @param array $defaults
457 */
458 public function blockSetDefaults(&$defaults) {
459 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
460 sort($locationTypeKeys);
461
462 // get the default location type
463 $locationType = CRM_Core_BAO_LocationType::getDefault();
464
465 // unset primary location type
466 $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
467 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
468
469 // reset the array sequence
470 $locationTypeKeys = array_values($locationTypeKeys);
471
472 // get default phone and im provider id.
473 $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
474 $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service',
475 FALSE, FALSE, FALSE, ' AND is_default = 1'
476 ));
477 $defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type',
478 FALSE, FALSE, FALSE, ' AND is_default = 1'
479 ));
480
481 $allBlocks = $this->_blocks;
482 if (array_key_exists('Address', $this->_editOptions)) {
483 $allBlocks['Address'] = $this->_editOptions['Address'];
484 }
485
486 $config = CRM_Core_Config::singleton();
487 foreach ($allBlocks as $blockName => $label) {
488 $name = strtolower($blockName);
489 $hasPrimary = $updateMode = FALSE;
490
491 // user is in update mode.
492 if (array_key_exists($name, $defaults) &&
493 !CRM_Utils_System::isNull($defaults[$name])
494 ) {
495 $updateMode = TRUE;
496 }
497
498 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) {
499 // make we require one primary block, CRM-5505
500 if ($updateMode) {
501 if (!$hasPrimary) {
502 $hasPrimary = CRM_Utils_Array::value(
503 'is_primary',
504 CRM_Utils_Array::value($instance, $defaults[$name])
505 );
506 }
507 continue;
508 }
509
510 //set location to primary for first one.
511 if ($instance == 1) {
512 $hasPrimary = TRUE;
513 $defaults[$name][$instance]['is_primary'] = TRUE;
514 $defaults[$name][$instance]['location_type_id'] = $locationType->id;
515 }
516 else {
517 $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id;
518 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
519 }
520
521 //set default country
522 if ($name == 'address' && $config->defaultContactCountry) {
523 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
524 }
525
526 //set default state/province
527 if ($name == 'address' && $config->defaultContactStateProvince) {
528 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince;
529 }
530
531 //set default phone type.
532 if ($name == 'phone' && $defPhoneTypeId) {
533 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
534 }
535 //set default website type.
536 if ($name == 'website' && $defWebsiteTypeId) {
537 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
538 }
539
540 //set default im provider.
541 if ($name == 'im' && $defIMProviderId) {
542 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
543 }
544 }
545
546 if (!$hasPrimary) {
547 $defaults[$name][1]['is_primary'] = TRUE;
548 }
549 }
550 }
551
552 /**
553 * add the rules (mainly global rules) for form.
554 * All local rules are added near the element
555 *
556 * @see valid_date
557 */
558 public function addRules() {
559 // skip adding formRules when custom data is build
560 if ($this->_addBlockName || ($this->_action & CRM_Core_Action::DELETE)) {
561 return;
562 }
563
564 $this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'], $this->_contactId);
565
566 // Call Locking check if editing existing contact
567 if ($this->_contactId) {
568 $this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId);
569 }
570
571 if (array_key_exists('Address', $this->_editOptions)) {
572 $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
573 }
574
575 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
576 $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
577 }
578 }
579
580 /**
581 * Global validation rules for the form.
582 *
583 * @param array $fields
584 * Posted values of the form.
585 * @param array $errors
586 * List of errors to be posted back to the form.
587 * @param int $contactId
588 * Contact id if doing update.
589 *
590 * @return bool
591 * email/openId
592 */
593 public static function formRule($fields, &$errors, $contactId, $contactType) {
594 $config = CRM_Core_Config::singleton();
595
596 // validations.
597 //1. for each block only single value can be marked as is_primary = true.
598 //2. location type id should be present if block data present.
599 //3. check open id across db and other each block for duplicate.
600 //4. at least one location should be primary.
601 //5. also get primaryID from email or open id block.
602
603 // take the location blocks.
604 $blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
605 'contact_edit_options', TRUE, NULL,
606 FALSE, 'name', TRUE, 'AND v.filter = 1'
607 );
608
609 $otherEditOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
610 'contact_edit_options', TRUE, NULL,
611 FALSE, 'name', TRUE, 'AND v.filter = 0'
612 );
613 //get address block inside.
614 if (array_key_exists('Address', $otherEditOptions)) {
615 $blocks['Address'] = $otherEditOptions['Address'];
616 }
617
618 $website_types = [];
619 $openIds = [];
620 $primaryID = FALSE;
621 foreach ($blocks as $name => $label) {
622 $hasData = $hasPrimary = [];
623 $name = strtolower($name);
624 if (!empty($fields[$name]) && is_array($fields[$name])) {
625 foreach ($fields[$name] as $instance => $blockValues) {
626 $dataExists = self::blockDataExists($blockValues);
627
628 if (!$dataExists && $name == 'address') {
629 $dataExists = CRM_Utils_Array::value('use_shared_address', $fields['address'][$instance]);
630 }
631
632 if ($dataExists) {
633 if ($name == 'website') {
634 if (!empty($blockValues['website_type_id'])) {
635 if (empty($website_types[$blockValues['website_type_id']])) {
636 $website_types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
637 }
638 else {
639 $errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
640 }
641 }
642
643 // skip remaining checks for website
644 continue;
645 }
646
647 $hasData[] = $instance;
648 if (!empty($blockValues['is_primary'])) {
649 $hasPrimary[] = $instance;
650 if (!$primaryID &&
651 in_array($name, [
652 'email',
653 'openid',
654 ]) && !empty($blockValues[$name])
655 ) {
656 $primaryID = $blockValues[$name];
657 }
658 }
659
660 if (empty($blockValues['location_type_id'])) {
661 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]);
662 }
663 }
664
665 if ($name == 'openid' && !empty($blockValues[$name])) {
666 $oid = new CRM_Core_DAO_OpenID();
667 $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
668 $cid = isset($contactId) ? $contactId : 0;
669 if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
670 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]);
671 }
672 }
673 }
674
675 if (empty($hasPrimary) && !empty($hasData)) {
676 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]);
677 }
678
679 if (count($hasPrimary) > 1) {
680 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
681 [1 => $label]
682 );
683 }
684 }
685 }
686
687 //do validations for all opend ids they should be distinct.
688 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
689 foreach ($openIds as $instance => $value) {
690 if (!array_key_exists($instance, array_unique($openIds))) {
691 $errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]);
692 }
693 }
694 }
695
696 // street number should be digit + suffix, CRM-5450
697 $parseStreetAddress = CRM_Utils_Array::value('street_address_parsing',
698 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
699 'address_options'
700 )
701 );
702 if ($parseStreetAddress) {
703 if (isset($fields['address']) &&
704 is_array($fields['address'])
705 ) {
706 $invalidStreetNumbers = [];
707 foreach ($fields['address'] as $cnt => $address) {
708 if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
709 $parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
710 if (empty($parsedAddress['street_number'])) {
711 $invalidStreetNumbers[] = $cnt;
712 }
713 }
714 }
715
716 if (!empty($invalidStreetNumbers)) {
717 $first = $invalidStreetNumbers[0];
718 foreach ($invalidStreetNumbers as & $num) {
719 $num = CRM_Contact_Form_Contact::ordinalNumber($num);
720 }
721 $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', [1 => implode(', ', $invalidStreetNumbers)]);
722 }
723 }
724 }
725
726 // Check for duplicate contact if it wasn't already handled by ajax or disabled
727 if (!Civi::settings()->get('contact_ajax_check_similar') || !empty($fields['_qf_Contact_refresh_dedupe'])) {
728 self::checkDuplicateContacts($fields, $errors, $contactId, $contactType);
729 }
730
731 return $primaryID;
732 }
733
734 /**
735 * Build the form object.
736 */
737 public function buildQuickForm() {
738 //load form for child blocks
739 if ($this->_addBlockName) {
740 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
741 return $className::buildQuickForm($this);
742 }
743
744 if ($this->_action == CRM_Core_Action::UPDATE) {
745 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
746 $deleteURL = [
747 CRM_Core_Action::DELETE => [
748 'name' => ts('Delete Contact Image'),
749 'url' => 'civicrm/contact/image',
750 'qs' => 'reset=1&cid=%%id%%&action=delete',
751 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
752 ],
753 ];
754 $deleteURL = CRM_Core_Action::formLink($deleteURL,
755 CRM_Core_Action::DELETE,
756 [
757 'id' => $this->_contactId,
758 ],
759 ts('more'),
760 FALSE,
761 'contact.image.delete',
762 'Contact',
763 $this->_contactId
764 );
765 $this->assign('deleteURL', $deleteURL);
766 }
767
768 //build contact type specific fields
769 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
770 $className::buildQuickForm($this);
771
772 // Ajax duplicate checking
773 $checkSimilar = Civi::settings()->get('contact_ajax_check_similar');
774 $this->assign('checkSimilar', $checkSimilar);
775 if ($checkSimilar == 1) {
776 $ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType];
777 $this->assign('ruleFields', CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams));
778 }
779
780 // build Custom data if Custom data present in edit option
781 $buildCustomData = 'noCustomDataPresent';
782 if (array_key_exists('CustomData', $this->_editOptions)) {
783 $buildCustomData = "customDataPresent";
784 }
785
786 // subtype is a common field. lets keep it here
787 $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType]);
788 if (!empty($subtypes)) {
789 $this->addField('contact_sub_type', [
790 'label' => ts('Contact Type'),
791 'options' => $subtypes,
792 'class' => $buildCustomData,
793 'multiple' => 'multiple',
794 'option_url' => NULL,
795 ]);
796 }
797
798 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
799 foreach ($this->_editOptions as $name => $label) {
800 if ($name == 'Address') {
801 $this->_blocks['Address'] = $this->_editOptions['Address'];
802 continue;
803 }
804 if ($name == 'TagsAndGroups') {
805 continue;
806 }
807 $className = 'CRM_Contact_Form_Edit_' . $name;
808 $className::buildQuickForm($this);
809 }
810
811 // build tags and groups
812 CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL,
813 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
814
815 // build location blocks.
816 CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
817 CRM_Contact_Form_Location::buildQuickForm($this);
818
819 // add attachment
820 $this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]);
821
822 // add the dedupe button
823 $this->addElement('submit',
824 $this->_dedupeButtonName,
825 ts('Check for Matching Contact(s)')
826 );
827 $this->addElement('submit',
828 $this->_duplicateButtonName,
829 ts('Save Matching Contact')
830 );
831 $this->addElement('submit',
832 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
833 ts('Save With Duplicate Household')
834 );
835
836 $buttons = [
837 [
838 'type' => 'upload',
839 'name' => ts('Save'),
840 'subName' => 'view',
841 'isDefault' => TRUE,
842 ],
843 ];
844 if (CRM_Core_Permission::check('add contacts')) {
845 $buttons[] = [
846 'type' => 'upload',
847 'name' => ts('Save and New'),
848 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
849 'subName' => 'new',
850 ];
851 }
852 $buttons[] = [
853 'type' => 'cancel',
854 'name' => ts('Cancel'),
855 ];
856
857 if (!empty($this->_values['contact_sub_type'])) {
858 $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
859 trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
860 );
861 }
862 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
863
864 $this->addButtons($buttons);
865 }
866
867 /**
868 * Form submission of new/edit contact is processed.
869 */
870 public function postProcess() {
871 // check if dedupe button, if so return.
872 $buttonName = $this->controller->getButtonName();
873 if ($buttonName == $this->_dedupeButtonName) {
874 return;
875 }
876
877 //get the submitted values in an array
878 $params = $this->controller->exportValues($this->_name);
879 if (!isset($params['preferred_communication_method'])) {
880 // If this field is empty QF will trim it so we have to add it in.
881 $params['preferred_communication_method'] = 'null';
882 }
883
884 $group = CRM_Utils_Array::value('group', $params);
885 if (!empty($group) && is_array($group)) {
886 unset($params['group']);
887 foreach ($group as $key => $value) {
888 $params['group'][$value] = 1;
889 }
890 }
891
892 if (!empty($params['image_URL'])) {
893 CRM_Contact_BAO_Contact::processImageParams($params);
894 }
895
896 if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
897 $params['current_employer'] = $params['current_employer_id'];
898 }
899
900 // don't carry current_employer_id field,
901 // since we don't want to directly update DAO object without
902 // handling related business logic ( eg related membership )
903 if (isset($params['current_employer_id'])) {
904 unset($params['current_employer_id']);
905 }
906
907 $params['contact_type'] = $this->_contactType;
908 if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
909 $params['contact_sub_type'] = [$this->_contactSubType];
910 }
911
912 if ($this->_contactId) {
913 $params['contact_id'] = $this->_contactId;
914 }
915
916 //make deceased date null when is_deceased = false
917 if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
918 $params['is_deceased'] = FALSE;
919 $params['deceased_date'] = NULL;
920 }
921
922 if (isset($params['contact_id'])) {
923 // process membership status for deceased contact
924 $deceasedParams = [
925 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
926 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE),
927 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL),
928 ];
929 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
930 }
931
932 // action is taken depending upon the mode
933 if ($this->_action & CRM_Core_Action::UPDATE) {
934 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
935 }
936 else {
937 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
938 }
939
940 //CRM-5143
941 //if subtype is set, send subtype as extend to validate subtype customfield
942 $customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
943
944 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
945 $this->_contactId,
946 $customFieldExtends,
947 TRUE
948 );
949 if ($this->_contactId && !empty($this->_oldSubtypes)) {
950 CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId,
951 $params['contact_type'],
952 $this->_oldSubtypes,
953 $params['contact_sub_type']
954 );
955 }
956
957 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
958 // this is a chekbox, so mark false if we dont get a POST value
959 $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
960 }
961
962 // process shared contact address.
963 CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
964
965 if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
966 unset($params['group']);
967 }
968 elseif (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE)) {
969 // figure out which all groups are intended to be removed
970 $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
971 if (is_array($contactGroupList)) {
972 foreach ($contactGroupList as $key) {
973 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
974 $params['group'][$key['group_id']] = -1;
975 }
976 }
977 }
978 }
979
980 // parse street address, CRM-5450
981 $parseStatusMsg = NULL;
982 if ($this->_parseStreetAddress) {
983 $parseResult = self::parseAddress($params);
984 $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
985 }
986
987 $blocks = ['email', 'phone', 'im', 'openid', 'address', 'website'];
988 foreach ($blocks as $block) {
989 if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) {
990 foreach ($this->_preEditValues[$block] as $count => $value) {
991 if (!empty($value['id'])) {
992 $params[$block][$count]['id'] = $value['id'];
993 $params[$block]['isIdSet'] = TRUE;
994 }
995 }
996 }
997 }
998
999 // Allow un-setting of location info, CRM-5969
1000 $params['updateBlankLocInfo'] = TRUE;
1001
1002 $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
1003
1004 // status message
1005 if ($this->_contactId) {
1006 $message = ts('%1 has been updated.', [1 => $contact->display_name]);
1007 }
1008 else {
1009 $message = ts('%1 has been created.', [1 => $contact->display_name]);
1010 }
1011
1012 // set the contact ID
1013 $this->_contactId = $contact->id;
1014
1015 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
1016 //add contact to tags
1017 if (isset($params['tag'])) {
1018 $params['tag'] = array_flip(explode(',', $params['tag']));
1019 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1020 }
1021 //save free tags
1022 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1023 CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1024 }
1025 }
1026
1027 if (!empty($parseStatusMsg)) {
1028 $message .= "<br />$parseStatusMsg";
1029 }
1030 if (!empty($updateMembershipMsg)) {
1031 $message .= "<br />$updateMembershipMsg";
1032 }
1033
1034 $session = CRM_Core_Session::singleton();
1035 $session->setStatus($message, ts('Contact Saved'), 'success');
1036
1037 // add the recently viewed contact
1038 $recentOther = [];
1039 if (($session->get('userID') == $contact->id) ||
1040 CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)
1041 ) {
1042 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
1043 }
1044
1045 if (($session->get('userID') != $this->_contactId) && CRM_Core_Permission::check('delete contacts')) {
1046 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
1047 }
1048
1049 CRM_Utils_Recent::add($contact->display_name,
1050 CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id),
1051 $contact->id,
1052 $this->_contactType,
1053 $contact->id,
1054 $contact->display_name,
1055 $recentOther
1056 );
1057
1058 // here we replace the user context with the url to view this contact
1059 $buttonName = $this->controller->getButtonName();
1060 if ($buttonName == $this->getButtonName('upload', 'new')) {
1061 $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType));
1062 $resetStr = "reset=1&ct={$contact->contact_type}";
1063 $resetStr .= (count($contactSubTypes) == 1) ? "&cst=" . array_pop($contactSubTypes) : '';
1064 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
1065 }
1066 else {
1067 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
1068 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
1069 //validate the qfKey
1070 $urlParams = 'reset=1&cid=' . $contact->id;
1071 if ($context) {
1072 $urlParams .= "&context=$context";
1073 }
1074 if (CRM_Utils_Rule::qfKey($qfKey)) {
1075 $urlParams .= "&key=$qfKey";
1076 }
1077
1078 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
1079 }
1080
1081 // now invoke the post hook
1082 if ($this->_action & CRM_Core_Action::UPDATE) {
1083 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
1084 }
1085 else {
1086 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
1087 }
1088 }
1089
1090 /**
1091 * Is there any real significant data in the hierarchical location array.
1092 *
1093 * @param array $fields
1094 * The hierarchical value representation of this location.
1095 *
1096 * @return bool
1097 * true if data exists, false otherwise
1098 */
1099 public static function blockDataExists(&$fields) {
1100 if (!is_array($fields)) {
1101 return FALSE;
1102 }
1103
1104 static $skipFields = [
1105 'location_type_id',
1106 'is_primary',
1107 'phone_type_id',
1108 'provider_id',
1109 'country_id',
1110 'website_type_id',
1111 'master_id',
1112 ];
1113 foreach ($fields as $name => $value) {
1114 $skipField = FALSE;
1115 foreach ($skipFields as $skip) {
1116 if (strpos("[$skip]", $name) !== FALSE) {
1117 if ($name == 'phone') {
1118 continue;
1119 }
1120 $skipField = TRUE;
1121 break;
1122 }
1123 }
1124 if ($skipField) {
1125 continue;
1126 }
1127 if (is_array($value)) {
1128 if (self::blockDataExists($value)) {
1129 return TRUE;
1130 }
1131 }
1132 else {
1133 if (!empty($value)) {
1134 return TRUE;
1135 }
1136 }
1137 }
1138
1139 return FALSE;
1140 }
1141
1142 /**
1143 * That checks for duplicate contacts.
1144 *
1145 * @param array $fields
1146 * Fields array which are submitted.
1147 * @param $errors
1148 * @param int $contactID
1149 * Contact id.
1150 * @param string $contactType
1151 * Contact type.
1152 */
1153 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1154 // if this is a forced save, ignore find duplicate rule
1155 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1156
1157 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', [$contactID]);
1158 if ($ids) {
1159
1160 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1161
1162 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1163 $duplicateContactsLinks .= ts('One matching contact was found. ', [
1164 'count' => count($contactLinks['rows']),
1165 'plural' => '%count matching contacts were found.<br />',
1166 ]);
1167 if ($contactLinks['msg'] == 'view') {
1168 $duplicateContactsLinks .= ts('You can View the existing contact', [
1169 'count' => count($contactLinks['rows']),
1170 'plural' => 'You can View the existing contacts',
1171 ]);
1172 }
1173 else {
1174 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', [
1175 'count' => count($contactLinks['rows']),
1176 'plural' => 'You can View or Edit the existing contacts',
1177 ]);
1178 }
1179 if ($contactLinks['msg'] == 'merge') {
1180 // We should also get a merge link if this is for an existing contact
1181 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1182 }
1183 $duplicateContactsLinks .= '.';
1184 $duplicateContactsLinks .= '</div>';
1185 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1186 $row = '';
1187 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
1188 $row .= ' <tr> ';
1189 $row .= ' <td class="matching-contacts-name"> ';
1190 $row .= CRM_Utils_Array::value('display_name', $contactLinks['rows'][$i]);
1191 $row .= ' </td>';
1192 $row .= ' <td class="matching-contacts-email"> ';
1193 $row .= CRM_Utils_Array::value('primary_email', $contactLinks['rows'][$i]);
1194 $row .= ' </td>';
1195 $row .= ' <td class="action-items"> ';
1196 $row .= CRM_Utils_Array::value('view', $contactLinks['rows'][$i]);
1197 $row .= CRM_Utils_Array::value('edit', $contactLinks['rows'][$i]);
1198 $row .= CRM_Utils_Array::value('merge', $contactLinks['rows'][$i]);
1199 $row .= ' </td>';
1200 $row .= ' </tr> ';
1201 }
1202
1203 $duplicateContactsLinks .= $row . '</table>';
1204 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1205
1206 $errors['_qf_default'] = $duplicateContactsLinks;
1207
1208 // let smarty know that there are duplicates
1209 $template = CRM_Core_Smarty::singleton();
1210 $template->assign('isDuplicate', 1);
1211 }
1212 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1213 // add a session message for no matching contacts
1214 CRM_Core_Session::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1215 }
1216 }
1217 }
1218
1219 /**
1220 * Use the form name to create the tpl file name.
1221 *
1222 * @return string
1223 */
1224 public function getTemplateFileName() {
1225 if ($this->_contactSubType) {
1226 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1227 $template = CRM_Core_Form::getTemplate();
1228 if ($template->template_exists($templateFile)) {
1229 return $templateFile;
1230 }
1231 }
1232 return parent::getTemplateFileName();
1233 }
1234
1235 /**
1236 * Parse all address blocks present in given params
1237 * and return parse result for all address blocks,
1238 * This function either parse street address in to child
1239 * elements or build street address from child elements.
1240 *
1241 * @param array $params
1242 * of key value consist of address blocks.
1243 *
1244 * @return array
1245 * as array of success/fails for each address block
1246 */
1247 public function parseAddress(&$params) {
1248 $parseSuccess = $parsedFields = [];
1249 if (!is_array($params['address']) ||
1250 CRM_Utils_System::isNull($params['address'])
1251 ) {
1252 return $parseSuccess;
1253 }
1254
1255 foreach ($params['address'] as $instance => & $address) {
1256 $buildStreetAddress = FALSE;
1257 $parseFieldName = 'street_address';
1258 foreach ([
1259 'street_number',
1260 'street_name',
1261 'street_unit',
1262 ] as $fld) {
1263 if (!empty($address[$fld])) {
1264 $parseFieldName = 'street_number';
1265 $buildStreetAddress = TRUE;
1266 break;
1267 }
1268 }
1269
1270 // main parse string.
1271 $parseString = CRM_Utils_Array::value($parseFieldName, $address);
1272
1273 // parse address field.
1274 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
1275
1276 if ($buildStreetAddress) {
1277 //hack to ignore spaces between number and suffix.
1278 //here user gives input as street_number so it has to
1279 //be street_number and street_number_suffix, but
1280 //due to spaces though preg detect string as street_name
1281 //consider it as 'street_number_suffix'.
1282 $suffix = $parsedFields['street_number_suffix'];
1283 if (!$suffix) {
1284 $suffix = $parsedFields['street_name'];
1285 }
1286 $address['street_number_suffix'] = $suffix;
1287 $address['street_number'] = $parsedFields['street_number'];
1288
1289 $streetAddress = NULL;
1290 foreach ([
1291 'street_number',
1292 'street_number_suffix',
1293 'street_name',
1294 'street_unit',
1295 ] as $fld) {
1296 if (in_array($fld, [
1297 'street_name',
1298 'street_unit',
1299 ])) {
1300 $streetAddress .= ' ';
1301 }
1302 // CRM-17619 - if the street number suffix begins with a number, add a space
1303 $thesuffix = CRM_Utils_Array::value('street_number_suffix', $address);
1304 if ($fld === 'street_number_suffix' && $thesuffix) {
1305 if (ctype_digit(substr($thesuffix, 0, 1))) {
1306 $streetAddress .= ' ';
1307 }
1308 }
1309 $streetAddress .= CRM_Utils_Array::value($fld, $address);
1310 }
1311 $address['street_address'] = trim($streetAddress);
1312 $parseSuccess[$instance] = TRUE;
1313 }
1314 else {
1315 $success = TRUE;
1316 // consider address is automatically parseable,
1317 // when we should found street_number and street_name
1318 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
1319 $success = FALSE;
1320 }
1321
1322 // check for original street address string.
1323 if (empty($parseString)) {
1324 $success = TRUE;
1325 }
1326
1327 $parseSuccess[$instance] = $success;
1328
1329 // we do not reset element values, but keep what we've parsed
1330 // in case of partial matches: CRM-8378
1331
1332 // merge parse address in to main address block.
1333 $address = array_merge($address, $parsedFields);
1334 }
1335 }
1336
1337 return $parseSuccess;
1338 }
1339
1340 /**
1341 * Check parse result and if some address block fails then this
1342 * function return the status message for all address blocks.
1343 *
1344 * @param array $parseResult
1345 * An array of address blk instance and its status.
1346 *
1347 * @return null|string
1348 * $statusMsg string status message for all address blocks.
1349 */
1350 public static function parseAddressStatusMsg($parseResult) {
1351 $statusMsg = NULL;
1352 if (!is_array($parseResult) || empty($parseResult)) {
1353 return $statusMsg;
1354 }
1355
1356 $parseFails = [];
1357 foreach ($parseResult as $instance => $success) {
1358 if (!$success) {
1359 $parseFails[] = self::ordinalNumber($instance);
1360 }
1361 }
1362
1363 if (!empty($parseFails)) {
1364 $statusMsg = ts("Complete street address(es) have been saved. However we were unable to split the address in the %1 address block(s) into address elements (street number, street name, street unit) due to an unrecognized address format. You can set the address elements manually by clicking 'Edit Address Elements' next to the Street Address field while in edit mode.",
1365 [1 => implode(', ', $parseFails)]
1366 );
1367 }
1368
1369 return $statusMsg;
1370 }
1371
1372 /**
1373 * Convert normal number to ordinal number format.
1374 * like 1 => 1st, 2 => 2nd and so on...
1375 *
1376 * @param int $number
1377 * number to convert in to ordinal number.
1378 *
1379 * @return string
1380 * ordinal number for given number.
1381 */
1382 public static function ordinalNumber($number) {
1383 if (empty($number)) {
1384 return NULL;
1385 }
1386
1387 $str = 'th';
1388 switch (floor($number / 10) % 10) {
1389 case 1:
1390 default:
1391 switch ($number % 10) {
1392 case 1:
1393 $str = 'st';
1394 break;
1395
1396 case 2:
1397 $str = 'nd';
1398 break;
1399
1400 case 3:
1401 $str = 'rd';
1402 break;
1403 }
1404 }
1405
1406 return "$number$str";
1407 }
1408
1409 /**
1410 * Update membership status to deceased.
1411 * function return the status message for updated membership.
1412 *
1413 * @param array $deceasedParams
1414 * having contact id and deceased value.
1415 *
1416 * @return null|string
1417 * $updateMembershipMsg string status message for updated membership.
1418 */
1419 public function updateMembershipStatus($deceasedParams) {
1420 $updateMembershipMsg = NULL;
1421 $contactId = CRM_Utils_Array::value('contact_id', $deceasedParams);
1422 $deceasedDate = CRM_Utils_Array::value('deceased_date', $deceasedParams);
1423
1424 // process to set membership status to deceased for both active/inactive membership
1425 if ($contactId &&
1426 $this->_contactType == 'Individual' && !empty($deceasedParams['is_deceased'])
1427 ) {
1428
1429 $session = CRM_Core_Session::singleton();
1430 $userId = $session->get('userID');
1431 if (!$userId) {
1432 $userId = $contactId;
1433 }
1434
1435 // get deceased status id
1436 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1437 $deceasedStatusId = array_search('Deceased', $allStatus);
1438 if (!$deceasedStatusId) {
1439 return $updateMembershipMsg;
1440 }
1441
1442 $today = time();
1443 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1444 return $updateMembershipMsg;
1445 }
1446
1447 // get non deceased membership
1448 $dao = new CRM_Member_DAO_Membership();
1449 $dao->contact_id = $contactId;
1450 $dao->whereAdd("status_id != $deceasedStatusId");
1451 $dao->find();
1452 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1453 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1454 $memCount = 0;
1455 while ($dao->fetch()) {
1456 // update status to deceased (for both active/inactive membership )
1457 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id,
1458 'status_id', $deceasedStatusId
1459 );
1460
1461 // add membership log
1462 $membershipLog = [
1463 'membership_id' => $dao->id,
1464 'status_id' => $deceasedStatusId,
1465 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1466 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1467 'modified_id' => $userId,
1468 'modified_date' => date('Ymd'),
1469 'membership_type_id' => $dao->membership_type_id,
1470 'max_related' => $dao->max_related,
1471 ];
1472
1473 CRM_Member_BAO_MembershipLog::add($membershipLog);
1474
1475 //create activity when membership status is changed
1476 $activityParam = [
1477 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1478 'source_contact_id' => $userId,
1479 'target_contact_id' => $dao->contact_id,
1480 'source_record_id' => $dao->id,
1481 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1482 'status_id' => 2,
1483 'version' => 3,
1484 'priority_id' => 2,
1485 'activity_date_time' => date('Y-m-d H:i:s'),
1486 'is_auto' => 0,
1487 'is_current_revision' => 1,
1488 'is_deleted' => 0,
1489 ];
1490 $activityResult = civicrm_api('activity', 'create', $activityParam);
1491
1492 $memCount++;
1493 }
1494
1495 // set status msg
1496 if ($memCount) {
1497 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1498 [1 => $memCount]
1499 );
1500 }
1501 }
1502
1503 return $updateMembershipMsg;
1504 }
1505
1506 }