3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components generic to all the contact types.
21 * It delegates the work to lower level subclasses and integrates the changes
22 * back in. It also uses a lot of functionality with the CRM API's, so any change
23 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
26 class CRM_Contact_Form_Contact
extends CRM_Core_Form
{
29 * The contact type of the form.
36 * The contact type of the form.
40 public $_contactSubType;
43 * The contact id, used when editing the form
50 * The default group id passed in via the url.
57 * The default tag id passed in via the url.
64 * Name of de-dupe button
68 protected $_dedupeButtonName;
71 * Name of optional save duplicate button.
75 protected $_duplicateButtonName;
77 protected $_editOptions = [];
79 protected $_oldSubtypes = [];
87 public $_customValueCount;
89 * The array of greetings with option group and filed names.
96 * Do we want to parse street address.
99 public $_parseStreetAddress;
102 * Check contact has a subtype or not.
105 public $_isContactSubType;
108 * Lets keep a cache of all the values that we retrieved.
109 * THis is an attempt to avoid the number of update statements
110 * during the write phase
113 public $_preEditValues;
116 * Explicitly declare the entity api name.
118 public function getDefaultEntity() {
123 * Explicitly declare the form context.
125 public function getDefaultContext() {
130 * Build all the data structures needed to build the form.
132 public function preProcess() {
133 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
135 $this->_dedupeButtonName
= $this->getButtonName('refresh', 'dedupe');
136 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
138 CRM_Core_Resources
::singleton()
139 ->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
141 $session = CRM_Core_Session
::singleton();
142 if ($this->_action
== CRM_Core_Action
::ADD
) {
143 // check for add contacts permissions
144 if (!CRM_Core_Permission
::check('add contacts')) {
145 CRM_Utils_System
::permissionDenied();
146 CRM_Utils_System
::civiExit();
148 $this->_contactType
= CRM_Utils_Request
::retrieve('ct', 'String',
149 $this, TRUE, NULL, 'REQUEST'
151 if (!in_array($this->_contactType
,
152 ['Individual', 'Household', 'Organization']
155 CRM_Core_Error
::statusBounce(ts('Could not get a contact id and/or contact type'));
158 $this->_isContactSubType
= FALSE;
159 if ($this->_contactSubType
= CRM_Utils_Request
::retrieve('cst', 'String', $this)) {
160 $this->_isContactSubType
= TRUE;
164 $this->_contactSubType
&&
165 !(CRM_Contact_BAO_ContactType
::isExtendsContactType($this->_contactSubType
, $this->_contactType
, TRUE))
167 CRM_Core_Error
::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType
]));
170 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Integer',
171 CRM_Core_DAO
::$_nullObject,
174 $this->_tid
= CRM_Utils_Request
::retrieve('tid', 'Integer',
175 CRM_Core_DAO
::$_nullObject,
178 $typeLabel = CRM_Contact_BAO_ContactType
::contactTypePairs(TRUE, $this->_contactSubType ?
179 $this->_contactSubType
: $this->_contactType
181 $typeLabel = implode(' / ', $typeLabel);
183 CRM_Utils_System
::setTitle(ts('New %1', [1 => $typeLabel]));
184 $session->pushUserContext(CRM_Utils_System
::url('civicrm/dashboard', 'reset=1'));
185 $this->_contactId
= NULL;
189 if (!$this->_contactId
) {
190 $this->_contactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
193 if ($this->_contactId
) {
195 $params = ['id' => $this->_contactId
];
196 $returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'];
197 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
199 if (empty($defaults['id'])) {
200 CRM_Core_Error
::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId
]));
203 $this->_contactType
= CRM_Utils_Array
::value('contact_type', $defaults);
204 $this->_contactSubType
= CRM_Utils_Array
::value('contact_sub_type', $defaults);
206 // check for permissions
207 $session = CRM_Core_Session
::singleton();
208 if (!CRM_Contact_BAO_Contact_Permission
::allow($this->_contactId
, CRM_Core_Permission
::EDIT
)) {
209 CRM_Core_Error
::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
212 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactId
);
213 if ($defaults['is_deceased']) {
214 $displayName .= ' <span class="crm-contact-deceased">(' . ts('deceased') . ')</span>';
216 $displayName = ts('Edit %1', [1 => $displayName]);
218 // Check if this is default domain contact CRM-10482
219 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
220 $displayName .= ' (' . ts('default organization') . ')';
223 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
224 CRM_Utils_System
::setTitle($displayName);
225 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
226 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
228 $urlParams = 'reset=1&cid=' . $this->_contactId
;
230 $urlParams .= "&context=$context";
233 if (CRM_Utils_Rule
::qfKey($qfKey)) {
235 $urlParams .= "&key=$qfKey";
238 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
240 $values = $this->get('values');
241 // get contact values.
242 if (!empty($values)) {
243 $this->_values
= $values;
247 'id' => $this->_contactId
,
248 'contact_id' => $this->_contactId
,
249 'noRelationships' => TRUE,
254 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
255 $this->set('values', $this->_values
);
259 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
263 // parse street address, CRM-5450
264 $this->_parseStreetAddress
= $this->get('parseStreetAddress');
265 if (!isset($this->_parseStreetAddress
)) {
266 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
269 $this->_parseStreetAddress
= FALSE;
270 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
271 $this->_parseStreetAddress
= TRUE;
273 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
275 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
277 $this->_editOptions
= $this->get('contactEditOptions');
278 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
279 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
280 'contact_edit_options', TRUE, NULL,
281 FALSE, 'name', TRUE, 'AND v.filter = 0'
283 $this->set('contactEditOptions', $this->_editOptions
);
286 // build demographics only for Individual contact type
287 if ($this->_contactType
!= 'Individual' &&
288 array_key_exists('Demographics', $this->_editOptions
)
290 unset($this->_editOptions
['Demographics']);
293 // in update mode don't show notes
294 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
295 unset($this->_editOptions
['Notes']);
298 $this->assign('editOptions', $this->_editOptions
);
299 $this->assign('contactType', $this->_contactType
);
300 $this->assign('contactSubType', $this->_contactSubType
);
302 // get the location blocks.
303 $this->_blocks
= $this->get('blocks');
304 if (CRM_Utils_System
::isNull($this->_blocks
)) {
305 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
306 'contact_edit_options', TRUE, NULL,
307 FALSE, 'name', TRUE, 'AND v.filter = 1'
309 $this->set('blocks', $this->_blocks
);
311 $this->assign('blocks', $this->_blocks
);
313 // this is needed for custom data.
314 $this->assign('entityID', $this->_contactId
);
316 // also keep the convention.
317 $this->assign('contactId', $this->_contactId
);
320 CRM_Contact_Form_Location
::preProcess($this);
322 // retain the multiple count custom fields value
323 if (!empty($_POST['hidden_custom'])) {
324 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
326 if ($contactSubType = CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
327 $paramSubType = implode(',', $contactSubType);
330 $this->_getCachedTree
= FALSE;
331 unset($customGroupCount[0]);
332 foreach ($customGroupCount as $groupID => $groupCount) {
333 if ($groupCount > 1) {
334 $this->set('groupID', $groupID);
336 for ($i = 0; $i <= $groupCount; $i++
) {
337 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
338 $i, $this->_contactType
, $this->_contactId
340 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
345 //reset all the ajax stuff, for normal processing
346 if (isset($this->_groupTree
)) {
347 $this->_groupTree
= NULL;
349 $this->set('groupID', NULL);
350 $this->_getCachedTree
= TRUE;
353 // execute preProcess dynamically by js else execute normal preProcess
354 if (array_key_exists('CustomData', $this->_editOptions
)) {
355 //assign a parameter to pass for sub type multivalue
356 //custom field to load
357 if ($this->_contactSubType ||
isset($paramSubType)) {
358 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
359 str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
361 $this->assign('paramSubType', $paramSubType);
364 if (CRM_Utils_Request
::retrieve('type', 'String')) {
365 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
368 $contactSubType = $this->_contactSubType
;
369 // need contact sub type to build related grouptree array during post process
370 if (!empty($_POST['contact_sub_type'])) {
371 $contactSubType = $_POST['contact_sub_type'];
373 //only custom data has preprocess hence directly call it
374 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
375 1, $this->_contactType
, $this->_contactId
377 $this->assign('customValueCount', $this->_customValueCount
);
383 * Set default values for the form.
385 * Note that in edit/view mode the default values are retrieved from the database
387 public function setDefaultValues() {
388 $defaults = $this->_values
;
390 if ($this->_action
& CRM_Core_Action
::ADD
) {
391 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
392 // set group and tag defaults if any
394 $defaults['group'][] = $this->_gid
;
397 $defaults['tag'][$this->_tid
] = 1;
400 if ($this->_contactSubType
) {
401 $defaults['contact_sub_type'] = $this->_contactSubType
;
405 foreach ($defaults['email'] as $dontCare => & $val) {
406 if (isset($val['signature_text'])) {
407 $val['signature_text_hidden'] = $val['signature_text'];
409 if (isset($val['signature_html'])) {
410 $val['signature_html_hidden'] = $val['signature_html'];
414 if (!empty($defaults['contact_sub_type'])) {
415 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
418 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
419 foreach ($this->_editOptions
as $name => $label) {
420 if (!in_array($name, ['Address', 'Notes'])) {
421 $className = 'CRM_Contact_Form_Edit_' . $name;
422 $className::setDefaultValues($this, $defaults);
426 //set address block defaults
427 CRM_Contact_Form_Edit_Address
::setDefaultValues($defaults, $this);
429 if (!empty($defaults['image_URL'])) {
430 $this->assign("imageURL", CRM_Utils_File
::getImageURL($defaults['image_URL']));
433 //set location type and country to default for each block
434 $this->blockSetDefaults($defaults);
436 $this->_preEditValues
= $defaults;
441 * Do the set default related to location type id, primary location, default country.
443 * @param array $defaults
445 public function blockSetDefaults(&$defaults) {
446 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
447 sort($locationTypeKeys);
449 // get the default location type
450 $locationType = CRM_Core_BAO_LocationType
::getDefault();
452 // unset primary location type
453 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
454 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
456 // reset the array sequence
457 $locationTypeKeys = array_values($locationTypeKeys);
459 // get default phone and im provider id.
460 $defPhoneTypeId = key(CRM_Core_OptionGroup
::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
461 $defIMProviderId = key(CRM_Core_OptionGroup
::values('instant_messenger_service',
462 FALSE, FALSE, FALSE, ' AND is_default = 1'
464 $defWebsiteTypeId = key(CRM_Core_OptionGroup
::values('website_type',
465 FALSE, FALSE, FALSE, ' AND is_default = 1'
468 $allBlocks = $this->_blocks
;
469 if (array_key_exists('Address', $this->_editOptions
)) {
470 $allBlocks['Address'] = $this->_editOptions
['Address'];
473 $config = CRM_Core_Config
::singleton();
474 foreach ($allBlocks as $blockName => $label) {
475 $name = strtolower($blockName);
476 $hasPrimary = $updateMode = FALSE;
478 // user is in update mode.
479 if (array_key_exists($name, $defaults) &&
480 !CRM_Utils_System
::isNull($defaults[$name])
485 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
486 // make we require one primary block, CRM-5505
489 $hasPrimary = CRM_Utils_Array
::value(
491 CRM_Utils_Array
::value($instance, $defaults[$name])
497 //set location to primary for first one.
498 if ($instance == 1) {
500 $defaults[$name][$instance]['is_primary'] = TRUE;
501 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
504 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
505 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
508 //set default country
509 if ($name == 'address' && $config->defaultContactCountry
) {
510 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
513 //set default state/province
514 if ($name == 'address' && $config->defaultContactStateProvince
) {
515 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
518 //set default phone type.
519 if ($name == 'phone' && $defPhoneTypeId) {
520 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
522 //set default website type.
523 if ($name == 'website' && $defWebsiteTypeId) {
524 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
527 //set default im provider.
528 if ($name == 'im' && $defIMProviderId) {
529 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
534 $defaults[$name][1]['is_primary'] = TRUE;
540 * add the rules (mainly global rules) for form.
541 * All local rules are added near the element
545 public function addRules() {
546 // skip adding formRules when custom data is build
547 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
551 $this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'], $this->_contactId
);
553 // Call Locking check if editing existing contact
554 if ($this->_contactId
) {
555 $this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId
);
558 if (array_key_exists('Address', $this->_editOptions
)) {
559 $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
562 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
563 $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
568 * Global validation rules for the form.
570 * @param array $fields
571 * Posted values of the form.
572 * @param array $errors
573 * List of errors to be posted back to the form.
574 * @param int $contactId
575 * Contact id if doing update.
576 * @param string $contactType
581 public static function formRule($fields, &$errors, $contactId, $contactType) {
582 $config = CRM_Core_Config
::singleton();
585 //1. for each block only single value can be marked as is_primary = true.
586 //2. location type id should be present if block data present.
587 //3. check open id across db and other each block for duplicate.
588 //4. at least one location should be primary.
589 //5. also get primaryID from email or open id block.
591 // take the location blocks.
592 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
593 'contact_edit_options', TRUE, NULL,
594 FALSE, 'name', TRUE, 'AND v.filter = 1'
597 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
598 'contact_edit_options', TRUE, NULL,
599 FALSE, 'name', TRUE, 'AND v.filter = 0'
601 //get address block inside.
602 if (array_key_exists('Address', $otherEditOptions)) {
603 $blocks['Address'] = $otherEditOptions['Address'];
609 foreach ($blocks as $name => $label) {
610 $hasData = $hasPrimary = [];
611 $name = strtolower($name);
612 if (!empty($fields[$name]) && is_array($fields[$name])) {
613 foreach ($fields[$name] as $instance => $blockValues) {
614 $dataExists = self
::blockDataExists($blockValues);
616 if (!$dataExists && $name == 'address') {
617 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
621 if ($name == 'website') {
622 if (!empty($blockValues['website_type_id'])) {
623 if (empty($website_types[$blockValues['website_type_id']])) {
624 $website_types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
627 $errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
631 // skip remaining checks for website
635 $hasData[] = $instance;
636 if (!empty($blockValues['is_primary'])) {
637 $hasPrimary[] = $instance;
642 ]) && !empty($blockValues[$name])
644 $primaryID = $blockValues[$name];
648 if (empty($blockValues['location_type_id'])) {
649 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]);
653 if ($name == 'openid' && !empty($blockValues[$name])) {
654 $oid = new CRM_Core_DAO_OpenID();
655 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
656 $cid = isset($contactId) ?
$contactId : 0;
657 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
658 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]);
663 if (empty($hasPrimary) && !empty($hasData)) {
664 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]);
667 if (count($hasPrimary) > 1) {
668 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
675 //do validations for all opend ids they should be distinct.
676 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
677 foreach ($openIds as $instance => $value) {
678 if (!array_key_exists($instance, array_unique($openIds))) {
679 $errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]);
684 // street number should be digit + suffix, CRM-5450
685 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
686 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
690 if ($parseStreetAddress) {
691 if (isset($fields['address']) &&
692 is_array($fields['address'])
694 $invalidStreetNumbers = [];
695 foreach ($fields['address'] as $cnt => $address) {
696 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
697 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
698 if (empty($parsedAddress['street_number'])) {
699 $invalidStreetNumbers[] = $cnt;
704 if (!empty($invalidStreetNumbers)) {
705 $first = $invalidStreetNumbers[0];
706 foreach ($invalidStreetNumbers as & $num) {
707 $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
709 $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)]);
714 // Check for duplicate contact if it wasn't already handled by ajax or disabled
715 if (!Civi
::settings()->get('contact_ajax_check_similar') ||
!empty($fields['_qf_Contact_refresh_dedupe'])) {
716 self
::checkDuplicateContacts($fields, $errors, $contactId, $contactType);
723 * Build the form object.
725 public function buildQuickForm() {
726 //load form for child blocks
727 if ($this->_addBlockName
) {
728 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
729 return $className::buildQuickForm($this);
732 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
733 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
735 CRM_Core_Action
::DELETE
=> [
736 'name' => ts('Delete Contact Image'),
737 'url' => 'civicrm/contact/image',
738 'qs' => 'reset=1&cid=%%id%%&action=delete',
739 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
742 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
743 CRM_Core_Action
::DELETE
,
745 'id' => $this->_contactId
,
749 'contact.image.delete',
753 $this->assign('deleteURL', $deleteURL);
756 //build contact type specific fields
757 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
758 $className::buildQuickForm($this);
760 // Ajax duplicate checking
761 $checkSimilar = Civi
::settings()->get('contact_ajax_check_similar');
762 $this->assign('checkSimilar', $checkSimilar);
763 if ($checkSimilar == 1) {
764 $ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType
];
765 $this->assign('ruleFields', CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams));
768 // build Custom data if Custom data present in edit option
769 $buildCustomData = 'noCustomDataPresent';
770 if (array_key_exists('CustomData', $this->_editOptions
)) {
771 $buildCustomData = "customDataPresent";
774 // subtype is a common field. lets keep it here
775 $subtypes = CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType
]);
776 if (!empty($subtypes)) {
777 $this->addField('contact_sub_type', [
778 'label' => ts('Contact Type'),
779 'options' => $subtypes,
780 'class' => $buildCustomData,
781 'multiple' => 'multiple',
782 'option_url' => NULL,
786 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
787 foreach ($this->_editOptions
as $name => $label) {
788 if ($name == 'Address') {
789 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
792 if ($name == 'TagsAndGroups') {
795 $className = 'CRM_Contact_Form_Edit_' . $name;
796 $className::buildQuickForm($this);
799 // build tags and groups
800 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
801 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
803 // build location blocks.
804 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
805 CRM_Contact_Form_Location
::buildQuickForm($this);
808 $this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]);
810 // add the dedupe button
811 $this->addElement('submit',
812 $this->_dedupeButtonName
,
813 ts('Check for Matching Contact(s)')
815 $this->addElement('submit',
816 $this->_duplicateButtonName
,
817 ts('Save Matching Contact')
819 $this->addElement('submit',
820 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
821 ts('Save With Duplicate Household')
827 'name' => ts('Save'),
832 if (CRM_Core_Permission
::check('add contacts')) {
835 'name' => ts('Save and New'),
836 'spacing' => ' ',
842 'name' => ts('Cancel'),
845 if (!empty($this->_values
['contact_sub_type'])) {
846 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
847 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
850 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
852 $this->addButtons($buttons);
856 * Form submission of new/edit contact is processed.
858 public function postProcess() {
859 // check if dedupe button, if so return.
860 $buttonName = $this->controller
->getButtonName();
861 if ($buttonName == $this->_dedupeButtonName
) {
865 //get the submitted values in an array
866 $params = $this->controller
->exportValues($this->_name
);
867 if (!isset($params['preferred_communication_method'])) {
868 // If this field is empty QF will trim it so we have to add it in.
869 $params['preferred_communication_method'] = 'null';
872 $group = CRM_Utils_Array
::value('group', $params);
873 if (!empty($group) && is_array($group)) {
874 unset($params['group']);
875 foreach ($group as $key => $value) {
876 $params['group'][$value] = 1;
880 if (!empty($params['image_URL'])) {
881 CRM_Contact_BAO_Contact
::processImageParams($params);
884 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
885 $params['current_employer'] = $params['current_employer_id'];
888 // don't carry current_employer_id field,
889 // since we don't want to directly update DAO object without
890 // handling related business logic ( eg related membership )
891 if (isset($params['current_employer_id'])) {
892 unset($params['current_employer_id']);
895 $params['contact_type'] = $this->_contactType
;
896 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
897 $params['contact_sub_type'] = [$this->_contactSubType
];
900 if ($this->_contactId
) {
901 $params['contact_id'] = $this->_contactId
;
904 //make deceased date null when is_deceased = false
905 if ($this->_contactType
== 'Individual' && !empty($this->_editOptions
['Demographics']) && empty($params['is_deceased'])) {
906 $params['is_deceased'] = FALSE;
907 $params['deceased_date'] = NULL;
910 if (isset($params['contact_id'])) {
911 // process membership status for deceased contact
913 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
914 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
915 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
917 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
920 // action is taken depending upon the mode
921 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
922 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
925 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
929 //if subtype is set, send subtype as extend to validate subtype customfield
930 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
932 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
937 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
938 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
939 $params['contact_type'],
941 $params['contact_sub_type']
945 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
946 // this is a chekbox, so mark false if we dont get a POST value
947 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
950 // process shared contact address.
951 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
953 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
954 unset($params['group']);
956 elseif (!empty($params['contact_id']) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
957 // figure out which all groups are intended to be removed
958 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
959 if (is_array($contactGroupList)) {
960 foreach ($contactGroupList as $key) {
961 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
962 $params['group'][$key['group_id']] = -1;
968 // parse street address, CRM-5450
969 $parseStatusMsg = NULL;
970 if ($this->_parseStreetAddress
) {
971 $parseResult = self
::parseAddress($params);
972 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
975 $blocks = ['email', 'phone', 'im', 'openid', 'address', 'website'];
976 foreach ($blocks as $block) {
977 if (!empty($this->_preEditValues
[$block]) && is_array($this->_preEditValues
[$block])) {
978 foreach ($this->_preEditValues
[$block] as $count => $value) {
979 if (!empty($value['id'])) {
980 $params[$block][$count]['id'] = $value['id'];
981 $params[$block]['isIdSet'] = TRUE;
987 // Allow un-setting of location info, CRM-5969
988 $params['updateBlankLocInfo'] = TRUE;
990 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
993 if ($this->_contactId
) {
994 $message = ts('%1 has been updated.', [1 => $contact->display_name
]);
997 $message = ts('%1 has been created.', [1 => $contact->display_name
]);
1000 // set the contact ID
1001 $this->_contactId
= $contact->id
;
1003 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
1004 //add contact to tags
1005 if (isset($params['tag'])) {
1006 $params['tag'] = array_flip(explode(',', $params['tag']));
1007 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1010 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1011 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1015 if (!empty($parseStatusMsg)) {
1016 $message .= "<br />$parseStatusMsg";
1018 if (!empty($updateMembershipMsg)) {
1019 $message .= "<br />$updateMembershipMsg";
1022 $session = CRM_Core_Session
::singleton();
1023 $session->setStatus($message, ts('Contact Saved'), 'success');
1025 // add the recently viewed contact
1027 if (($session->get('userID') == $contact->id
) ||
1028 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1030 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1033 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1034 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1037 CRM_Utils_Recent
::add($contact->display_name
,
1038 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1040 $this->_contactType
,
1042 $contact->display_name
,
1046 // here we replace the user context with the url to view this contact
1047 $buttonName = $this->controller
->getButtonName();
1048 if ($buttonName == $this->getButtonName('upload', 'new')) {
1049 $contactSubTypes = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_contactSubType
));
1050 $resetStr = "reset=1&ct={$contact->contact_type}";
1051 $resetStr .= (count($contactSubTypes) == 1) ?
"&cst=" . array_pop($contactSubTypes) : '';
1052 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1055 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
1056 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1057 //validate the qfKey
1058 $urlParams = 'reset=1&cid=' . $contact->id
;
1060 $urlParams .= "&context=$context";
1062 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1063 $urlParams .= "&key=$qfKey";
1066 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1069 // now invoke the post hook
1070 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1071 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1074 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1079 * Is there any real significant data in the hierarchical location array.
1081 * @param array $fields
1082 * The hierarchical value representation of this location.
1085 * true if data exists, false otherwise
1087 public static function blockDataExists(&$fields) {
1088 if (!is_array($fields)) {
1092 static $skipFields = [
1101 foreach ($fields as $name => $value) {
1103 foreach ($skipFields as $skip) {
1104 if (strpos("[$skip]", $name) !== FALSE) {
1105 if ($name == 'phone') {
1115 if (is_array($value)) {
1116 if (self
::blockDataExists($value)) {
1121 if (!empty($value)) {
1131 * That checks for duplicate contacts.
1133 * @param array $fields
1134 * Fields array which are submitted.
1136 * @param int $contactID
1138 * @param string $contactType
1141 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1142 // if this is a forced save, ignore find duplicate rule
1143 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1145 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts($fields, $contactType, 'Supervised', [$contactID]);
1148 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1150 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1151 $duplicateContactsLinks .= ts('One matching contact was found. ', [
1152 'count' => count($contactLinks['rows']),
1153 'plural' => '%count matching contacts were found.<br />',
1155 if ($contactLinks['msg'] == 'view') {
1156 $duplicateContactsLinks .= ts('You can View the existing contact', [
1157 'count' => count($contactLinks['rows']),
1158 'plural' => 'You can View the existing contacts',
1162 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', [
1163 'count' => count($contactLinks['rows']),
1164 'plural' => 'You can View or Edit the existing contacts',
1167 if ($contactLinks['msg'] == 'merge') {
1168 // We should also get a merge link if this is for an existing contact
1169 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1171 $duplicateContactsLinks .= '.';
1172 $duplicateContactsLinks .= '</div>';
1173 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1175 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1177 $row .= ' <td class="matching-contacts-name"> ';
1178 $row .= CRM_Utils_Array
::value('display_name', $contactLinks['rows'][$i]);
1180 $row .= ' <td class="matching-contacts-email"> ';
1181 $row .= CRM_Utils_Array
::value('primary_email', $contactLinks['rows'][$i]);
1183 $row .= ' <td class="action-items"> ';
1184 $row .= CRM_Utils_Array
::value('view', $contactLinks['rows'][$i]);
1185 $row .= CRM_Utils_Array
::value('edit', $contactLinks['rows'][$i]);
1186 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1191 $duplicateContactsLinks .= $row . '</table>';
1192 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1194 $errors['_qf_default'] = $duplicateContactsLinks;
1196 // let smarty know that there are duplicates
1197 $template = CRM_Core_Smarty
::singleton();
1198 $template->assign('isDuplicate', 1);
1200 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1201 // add a session message for no matching contacts
1202 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1208 * Use the form name to create the tpl file name.
1212 public function getTemplateFileName() {
1213 if ($this->_contactSubType
) {
1214 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1215 $template = CRM_Core_Form
::getTemplate();
1216 if ($template->template_exists($templateFile)) {
1217 return $templateFile;
1220 return parent
::getTemplateFileName();
1224 * Parse all address blocks present in given params
1225 * and return parse result for all address blocks,
1226 * This function either parse street address in to child
1227 * elements or build street address from child elements.
1229 * @param array $params
1230 * of key value consist of address blocks.
1233 * as array of success/fails for each address block
1235 public function parseAddress(&$params) {
1236 $parseSuccess = $parsedFields = [];
1237 if (!is_array($params['address']) ||
1238 CRM_Utils_System
::isNull($params['address'])
1240 return $parseSuccess;
1243 foreach ($params['address'] as $instance => & $address) {
1244 $buildStreetAddress = FALSE;
1245 $parseFieldName = 'street_address';
1251 if (!empty($address[$fld])) {
1252 $parseFieldName = 'street_number';
1253 $buildStreetAddress = TRUE;
1258 // main parse string.
1259 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1261 // parse address field.
1262 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1264 if ($buildStreetAddress) {
1265 //hack to ignore spaces between number and suffix.
1266 //here user gives input as street_number so it has to
1267 //be street_number and street_number_suffix, but
1268 //due to spaces though preg detect string as street_name
1269 //consider it as 'street_number_suffix'.
1270 $suffix = $parsedFields['street_number_suffix'];
1272 $suffix = $parsedFields['street_name'];
1274 $address['street_number_suffix'] = $suffix;
1275 $address['street_number'] = $parsedFields['street_number'];
1277 $streetAddress = NULL;
1280 'street_number_suffix',
1284 if (in_array($fld, [
1288 $streetAddress .= ' ';
1290 // CRM-17619 - if the street number suffix begins with a number, add a space
1291 $thesuffix = CRM_Utils_Array
::value('street_number_suffix', $address);
1292 if ($fld === 'street_number_suffix' && $thesuffix) {
1293 if (ctype_digit(substr($thesuffix, 0, 1))) {
1294 $streetAddress .= ' ';
1297 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1299 $address['street_address'] = trim($streetAddress);
1300 $parseSuccess[$instance] = TRUE;
1304 // consider address is automatically parseable,
1305 // when we should found street_number and street_name
1306 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
1310 // check for original street address string.
1311 if (empty($parseString)) {
1315 $parseSuccess[$instance] = $success;
1317 // we do not reset element values, but keep what we've parsed
1318 // in case of partial matches: CRM-8378
1320 // merge parse address in to main address block.
1321 $address = array_merge($address, $parsedFields);
1325 return $parseSuccess;
1329 * Check parse result and if some address block fails then this
1330 * function return the status message for all address blocks.
1332 * @param array $parseResult
1333 * An array of address blk instance and its status.
1335 * @return null|string
1336 * $statusMsg string status message for all address blocks.
1338 public static function parseAddressStatusMsg($parseResult) {
1340 if (!is_array($parseResult) ||
empty($parseResult)) {
1345 foreach ($parseResult as $instance => $success) {
1347 $parseFails[] = self
::ordinalNumber($instance);
1351 if (!empty($parseFails)) {
1352 $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.",
1353 [1 => implode(', ', $parseFails)]
1361 * Convert normal number to ordinal number format.
1362 * like 1 => 1st, 2 => 2nd and so on...
1364 * @param int $number
1365 * number to convert in to ordinal number.
1368 * ordinal number for given number.
1370 public static function ordinalNumber($number) {
1371 if (empty($number)) {
1376 switch (floor($number / 10) %
10) {
1379 switch ($number %
10) {
1394 return "$number$str";
1398 * Update membership status to deceased.
1399 * function return the status message for updated membership.
1401 * @param array $deceasedParams
1402 * having contact id and deceased value.
1404 * @return null|string
1405 * $updateMembershipMsg string status message for updated membership.
1407 public function updateMembershipStatus($deceasedParams) {
1408 $updateMembershipMsg = NULL;
1409 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1410 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1412 // process to set membership status to deceased for both active/inactive membership
1414 $this->_contactType
== 'Individual' && !empty($deceasedParams['is_deceased'])
1417 $session = CRM_Core_Session
::singleton();
1418 $userId = $session->get('userID');
1420 $userId = $contactId;
1423 // get deceased status id
1424 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1425 $deceasedStatusId = array_search('Deceased', $allStatus);
1426 if (!$deceasedStatusId) {
1427 return $updateMembershipMsg;
1431 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1432 return $updateMembershipMsg;
1435 // get non deceased membership
1436 $dao = new CRM_Member_DAO_Membership();
1437 $dao->contact_id
= $contactId;
1438 $dao->whereAdd("status_id != $deceasedStatusId");
1440 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1441 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1443 while ($dao->fetch()) {
1444 // update status to deceased (for both active/inactive membership )
1445 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1446 'status_id', $deceasedStatusId
1449 // add membership log
1451 'membership_id' => $dao->id
,
1452 'status_id' => $deceasedStatusId,
1453 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1454 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1455 'modified_id' => $userId,
1456 'modified_date' => date('Ymd'),
1457 'membership_type_id' => $dao->membership_type_id
,
1458 'max_related' => $dao->max_related
,
1461 CRM_Member_BAO_MembershipLog
::add($membershipLog);
1463 //create activity when membership status is changed
1465 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1466 'source_contact_id' => $userId,
1467 'target_contact_id' => $dao->contact_id
,
1468 'source_record_id' => $dao->id
,
1469 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1473 'activity_date_time' => date('Y-m-d H:i:s'),
1475 'is_current_revision' => 1,
1478 $activityResult = civicrm_api('activity', 'create', $activityParam);
1485 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1491 return $updateMembershipMsg;