3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * This class generates form components generic to all the contact types.
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.
42 class CRM_Contact_Form_Contact
extends CRM_Core_Form
{
45 * The contact type of the form.
52 * The contact type of the form.
56 public $_contactSubType;
59 * The contact id, used when editing the form
66 * The default group id passed in via the url.
73 * The default tag id passed in via the url.
80 * Name of de-dupe button
84 protected $_dedupeButtonName;
87 * Name of optional save duplicate button.
91 protected $_duplicateButtonName;
93 protected $_editOptions = array();
95 protected $_oldSubtypes = array();
99 public $_values = array();
103 public $_customValueCount;
105 * The array of greetings with option group and filed names.
112 * Do we want to parse street address.
114 public $_parseStreetAddress;
117 * Check contact has a subtype or not.
119 public $_isContactSubType;
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
126 public $_preEditValues;
129 * Explicitly declare the entity api name.
131 public function getDefaultEntity() {
136 * Explicitly declare the form context.
138 public function getDefaultContext() {
143 * Build all the data structures needed to build the form.
145 public function preProcess() {
146 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
148 $this->_dedupeButtonName
= $this->getButtonName('refresh', 'dedupe');
149 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
151 CRM_Core_Resources
::singleton()
152 ->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
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();
161 $this->_contactType
= CRM_Utils_Request
::retrieve('ct', 'String',
162 $this, TRUE, NULL, 'REQUEST'
164 if (!in_array($this->_contactType
,
165 array('Individual', 'Household', 'Organization')
168 CRM_Core_Error
::statusBounce(ts('Could not get a contact id and/or contact type'));
171 $this->_isContactSubType
= FALSE;
172 if ($this->_contactSubType
= CRM_Utils_Request
::retrieve('cst', 'String', $this)) {
173 $this->_isContactSubType
= TRUE;
177 $this->_contactSubType
&&
178 !(CRM_Contact_BAO_ContactType
::isExtendsContactType($this->_contactSubType
, $this->_contactType
, TRUE))
180 CRM_Core_Error
::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType
)));
183 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Integer',
184 CRM_Core_DAO
::$_nullObject,
187 $this->_tid
= CRM_Utils_Request
::retrieve('tid', 'Integer',
188 CRM_Core_DAO
::$_nullObject,
191 $typeLabel = CRM_Contact_BAO_ContactType
::contactTypePairs(TRUE, $this->_contactSubType ?
192 $this->_contactSubType
: $this->_contactType
194 $typeLabel = implode(' / ', $typeLabel);
196 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $typeLabel)));
197 $session->pushUserContext(CRM_Utils_System
::url('civicrm/dashboard', 'reset=1'));
198 $this->_contactId
= NULL;
202 if (!$this->_contactId
) {
203 $this->_contactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
206 if ($this->_contactId
) {
208 $params = array('id' => $this->_contactId
);
209 $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased');
210 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
212 if (empty($defaults['id'])) {
213 CRM_Core_Error
::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId
)));
216 $this->_contactType
= CRM_Utils_Array
::value('contact_type', $defaults);
217 $this->_contactSubType
= CRM_Utils_Array
::value('contact_sub_type', $defaults);
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.'));
225 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactId
);
226 if ($defaults['is_deceased']) {
227 $displayName .= ' <span class="crm-contact-deceased">(deceased)</span>';
229 $displayName = ts('Edit %1', array(1 => $displayName));
231 // Check if this is default domain contact CRM-10482
232 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
233 $displayName .= ' (' . ts('default organization') . ')';
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', 'String', $this);
239 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
241 $urlParams = 'reset=1&cid=' . $this->_contactId
;
243 $urlParams .= "&context=$context";
246 if (CRM_Utils_Rule
::qfKey($qfKey)) {
248 $urlParams .= "&key=$qfKey";
251 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
253 $values = $this->get('values');
254 // get contact values.
255 if (!empty($values)) {
256 $this->_values
= $values;
260 'id' => $this->_contactId
,
261 'contact_id' => $this->_contactId
,
262 'noRelationships' => TRUE,
267 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
268 $this->set('values', $this->_values
);
272 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
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
,
282 $this->_parseStreetAddress
= FALSE;
283 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
284 $this->_parseStreetAddress
= TRUE;
286 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
288 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
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'
296 $this->set('contactEditOptions', $this->_editOptions
);
299 // build demographics only for Individual contact type
300 if ($this->_contactType
!= 'Individual' &&
301 array_key_exists('Demographics', $this->_editOptions
)
303 unset($this->_editOptions
['Demographics']);
306 // in update mode don't show notes
307 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
308 unset($this->_editOptions
['Notes']);
311 $this->assign('editOptions', $this->_editOptions
);
312 $this->assign('contactType', $this->_contactType
);
313 $this->assign('contactSubType', $this->_contactSubType
);
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'
322 $this->set('blocks', $this->_blocks
);
324 $this->assign('blocks', $this->_blocks
);
326 // this is needed for custom data.
327 $this->assign('entityID', $this->_contactId
);
329 // also keep the convention.
330 $this->assign('contactId', $this->_contactId
);
333 CRM_Contact_Form_Location
::preProcess($this);
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);
339 if ($contactSubType = CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
340 $paramSubType = implode(',', $contactSubType);
343 $this->_getCachedTree
= FALSE;
344 unset($customGroupCount[0]);
345 foreach ($customGroupCount as $groupID => $groupCount) {
346 if ($groupCount > 1) {
347 $this->set('groupID', $groupID);
349 for ($i = 0; $i <= $groupCount; $i++
) {
350 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
351 $i, $this->_contactType
, $this->_contactId
353 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
358 //reset all the ajax stuff, for normal processing
359 if (isset($this->_groupTree
)) {
360 $this->_groupTree
= NULL;
362 $this->set('groupID', NULL);
363 $this->_getCachedTree
= TRUE;
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
));
374 $this->assign('paramSubType', $paramSubType);
377 if (CRM_Utils_Request
::retrieve('type', 'String')) {
378 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
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'];
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
390 $this->assign('customValueCount', $this->_customValueCount
);
396 * Set default values for the form.
398 * Note that in edit/view mode the default values are retrieved from the database
400 public function setDefaultValues() {
401 $defaults = $this->_values
;
403 if ($this->_action
& CRM_Core_Action
::ADD
) {
404 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
405 // set group and tag defaults if any
407 $defaults['group'][] = $this->_gid
;
410 $defaults['tag'][$this->_tid
] = 1;
413 if ($this->_contactSubType
) {
414 $defaults['contact_sub_type'] = $this->_contactSubType
;
418 foreach ($defaults['email'] as $dontCare => & $val) {
419 if (isset($val['signature_text'])) {
420 $val['signature_text_hidden'] = $val['signature_text'];
422 if (isset($val['signature_html'])) {
423 $val['signature_html_hidden'] = $val['signature_html'];
427 if (!empty($defaults['contact_sub_type'])) {
428 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
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, array('Address', 'Notes'))) {
434 $className = 'CRM_Contact_Form_Edit_' . $name;
435 $className::setDefaultValues($this, $defaults);
439 //set address block defaults
440 CRM_Contact_Form_Edit_Address
::setDefaultValues($defaults, $this);
442 if (!empty($defaults['image_URL'])) {
443 $this->assign("imageURL", CRM_Utils_File
::getImageURL($defaults['image_URL']));
446 //set location type and country to default for each block
447 $this->blockSetDefaults($defaults);
449 $this->_preEditValues
= $defaults;
454 * Do the set default related to location type id, primary location, default country.
456 * @param array $defaults
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);
462 // get the default location type
463 $locationType = CRM_Core_BAO_LocationType
::getDefault();
465 // unset primary location type
466 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
467 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
469 // reset the array sequence
470 $locationTypeKeys = array_values($locationTypeKeys);
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'
477 $defWebsiteTypeId = key(CRM_Core_OptionGroup
::values('website_type',
478 FALSE, FALSE, FALSE, ' AND is_default = 1'
481 $allBlocks = $this->_blocks
;
482 if (array_key_exists('Address', $this->_editOptions
)) {
483 $allBlocks['Address'] = $this->_editOptions
['Address'];
486 $config = CRM_Core_Config
::singleton();
487 foreach ($allBlocks as $blockName => $label) {
488 $name = strtolower($blockName);
489 $hasPrimary = $updateMode = FALSE;
491 // user is in update mode.
492 if (array_key_exists($name, $defaults) &&
493 !CRM_Utils_System
::isNull($defaults[$name])
498 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
499 // make we require one primary block, CRM-5505
502 $hasPrimary = CRM_Utils_Array
::value(
504 CRM_Utils_Array
::value($instance, $defaults[$name])
510 //set location to primary for first one.
511 if ($instance == 1) {
513 $defaults[$name][$instance]['is_primary'] = TRUE;
514 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
517 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
518 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
521 //set default country
522 if ($name == 'address' && $config->defaultContactCountry
) {
523 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
526 //set default state/province
527 if ($name == 'address' && $config->defaultContactStateProvince
) {
528 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
531 //set default phone type.
532 if ($name == 'phone' && $defPhoneTypeId) {
533 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
535 //set default website type.
536 if ($name == 'website' && $defWebsiteTypeId) {
537 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
540 //set default im provider.
541 if ($name == 'im' && $defIMProviderId) {
542 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
547 $defaults[$name][1]['is_primary'] = TRUE;
553 * add the rules (mainly global rules) for form.
554 * All local rules are added near the element
558 public function addRules() {
559 // skip adding formRules when custom data is build
560 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
564 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
566 // Call Locking check if editing existing contact
567 if ($this->_contactId
) {
568 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
571 if (array_key_exists('Address', $this->_editOptions
)) {
572 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
575 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
576 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
581 * Global validation rules for the form.
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.
593 public static function formRule($fields, &$errors, $contactId = NULL) {
594 $config = CRM_Core_Config
::singleton();
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.
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'
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'
613 //get address block inside.
614 if (array_key_exists('Address', $otherEditOptions)) {
615 $blocks['Address'] = $otherEditOptions['Address'];
620 foreach ($blocks as $name => $label) {
621 $hasData = $hasPrimary = array();
622 $name = strtolower($name);
623 if (!empty($fields[$name]) && is_array($fields[$name])) {
624 foreach ($fields[$name] as $instance => $blockValues) {
625 $dataExists = self
::blockDataExists($blockValues);
627 if (!$dataExists && $name == 'address') {
628 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
632 // skip remaining checks for website
633 if ($name == 'website') {
637 $hasData[] = $instance;
638 if (!empty($blockValues['is_primary'])) {
639 $hasPrimary[] = $instance;
641 in_array($name, array(
644 )) && !empty($blockValues[$name])
646 $primaryID = $blockValues[$name];
650 if (empty($blockValues['location_type_id'])) {
651 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
655 if ($name == 'openid' && !empty($blockValues[$name])) {
656 $oid = new CRM_Core_DAO_OpenID();
657 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
658 $cid = isset($contactId) ?
$contactId : 0;
659 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
660 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
665 if (empty($hasPrimary) && !empty($hasData)) {
666 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
669 if (count($hasPrimary) > 1) {
670 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
677 //do validations for all opend ids they should be distinct.
678 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
679 foreach ($openIds as $instance => $value) {
680 if (!array_key_exists($instance, array_unique($openIds))) {
681 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
686 // street number should be digit + suffix, CRM-5450
687 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
688 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
692 if ($parseStreetAddress) {
693 if (isset($fields['address']) &&
694 is_array($fields['address'])
696 $invalidStreetNumbers = array();
697 foreach ($fields['address'] as $cnt => $address) {
698 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
699 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
700 if (empty($parsedAddress['street_number'])) {
701 $invalidStreetNumbers[] = $cnt;
706 if (!empty($invalidStreetNumbers)) {
707 $first = $invalidStreetNumbers[0];
708 foreach ($invalidStreetNumbers as & $num) {
709 $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
711 $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".', array(1 => implode(', ', $invalidStreetNumbers)));
720 * Build the form object.
722 public function buildQuickForm() {
723 //load form for child blocks
724 if ($this->_addBlockName
) {
725 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
726 return $className::buildQuickForm($this);
729 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
730 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
732 CRM_Core_Action
::DELETE
=> array(
733 'name' => ts('Delete Contact Image'),
734 'url' => 'civicrm/contact/image',
735 'qs' => 'reset=1&cid=%%id%%&action=delete',
736 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
739 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
740 CRM_Core_Action
::DELETE
,
742 'id' => $this->_contactId
,
746 'contact.image.delete',
750 $this->assign('deleteURL', $deleteURL);
753 //build contact type specific fields
754 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
755 $className::buildQuickForm($this);
757 // build Custom data if Custom data present in edit option
758 $buildCustomData = 'noCustomDataPresent';
759 if (array_key_exists('CustomData', $this->_editOptions
)) {
760 $buildCustomData = "customDataPresent";
763 // subtype is a common field. lets keep it here
764 $subtypes = CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType
));
765 if (!empty($subtypes)) {
766 $this->addField('contact_sub_type', array(
767 'label' => ts('Contact Type'),
768 'options' => $subtypes,
769 'class' => $buildCustomData,
770 'multiple' => 'multiple',
771 'option_url' => NULL,
775 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
776 foreach ($this->_editOptions
as $name => $label) {
777 if ($name == 'Address') {
778 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
781 if ($name == 'TagsAndGroups') {
784 $className = 'CRM_Contact_Form_Edit_' . $name;
785 $className::buildQuickForm($this);
788 // build tags and groups
789 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
790 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
792 // build location blocks.
793 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
794 CRM_Contact_Form_Location
::buildQuickForm($this);
797 $this->addField('image_URL', array('maxlength' => '255', 'label' => ts('Browse/Upload Image')));
799 // add the dedupe button
800 $this->addElement('submit',
801 $this->_dedupeButtonName
,
802 ts('Check for Matching Contact(s)')
804 $this->addElement('submit',
805 $this->_duplicateButtonName
,
806 ts('Save Matching Contact')
808 $this->addElement('submit',
809 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
810 ts('Save With Duplicate Household')
816 'name' => ts('Save'),
821 if (CRM_Core_Permission
::check('add contacts')) {
824 'name' => ts('Save and New'),
825 'spacing' => ' ',
831 'name' => ts('Cancel'),
834 if (!empty($this->_values
['contact_sub_type'])) {
835 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
836 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
839 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
841 $this->addButtons($buttons);
845 * Form submission of new/edit contact is processed.
847 public function postProcess() {
848 // check if dedupe button, if so return.
849 $buttonName = $this->controller
->getButtonName();
850 if ($buttonName == $this->_dedupeButtonName
) {
854 //get the submitted values in an array
855 $params = $this->controller
->exportValues($this->_name
);
856 if (!isset($params['preferred_communication_method'])) {
857 // If this field is empty QF will trim it so we have to add it in.
858 $params['preferred_communication_method'] = 'null';
861 $group = CRM_Utils_Array
::value('group', $params);
862 if (!empty($group) && is_array($group)) {
863 unset($params['group']);
864 foreach ($group as $key => $value) {
865 $params['group'][$value] = 1;
869 CRM_Contact_BAO_Contact_Optimizer
::edit($params, $this->_preEditValues
);
871 if (!empty($params['image_URL'])) {
872 CRM_Contact_BAO_Contact
::processImageParams($params);
875 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
876 $params['current_employer'] = $params['current_employer_id'];
879 // don't carry current_employer_id field,
880 // since we don't want to directly update DAO object without
881 // handling related business logic ( eg related membership )
882 if (isset($params['current_employer_id'])) {
883 unset($params['current_employer_id']);
886 $params['contact_type'] = $this->_contactType
;
887 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
888 $params['contact_sub_type'] = array($this->_contactSubType
);
891 if ($this->_contactId
) {
892 $params['contact_id'] = $this->_contactId
;
895 //make deceased date null when is_deceased = false
896 if ($this->_contactType
== 'Individual' && !empty($this->_editOptions
['Demographics']) && empty($params['is_deceased'])) {
897 $params['is_deceased'] = FALSE;
898 $params['deceased_date'] = NULL;
901 if (isset($params['contact_id'])) {
902 // process membership status for deceased contact
903 $deceasedParams = array(
904 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
905 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
906 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
908 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
911 // action is taken depending upon the mode
912 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
913 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
916 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
919 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
922 //if subtype is set, send subtype as extend to validate subtype customfield
923 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
925 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
930 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
931 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
932 $params['contact_type'],
934 $params['contact_sub_type']
938 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
939 // this is a chekbox, so mark false if we dont get a POST value
940 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
943 // process shared contact address.
944 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
946 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
947 unset($params['group']);
949 elseif (!empty($params['contact_id']) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
950 // figure out which all groups are intended to be removed
951 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
952 if (is_array($contactGroupList)) {
953 foreach ($contactGroupList as $key) {
954 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
955 $params['group'][$key['group_id']] = -1;
961 // parse street address, CRM-5450
962 $parseStatusMsg = NULL;
963 if ($this->_parseStreetAddress
) {
964 $parseResult = self
::parseAddress($params);
965 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
968 $blocks = array('email', 'phone', 'im', 'openid', 'address', 'website');
969 foreach ($blocks as $block) {
970 if (!empty($this->_preEditValues
[$block]) && is_array($this->_preEditValues
[$block])) {
971 foreach ($this->_preEditValues
[$block] as $count => $value) {
972 if (!empty($value['id'])) {
973 $params[$block][$count]['id'] = $value['id'];
974 $params[$block]['isIdSet'] = TRUE;
980 // Allow un-setting of location info, CRM-5969
981 $params['updateBlankLocInfo'] = TRUE;
983 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
986 if ($this->_contactId
) {
987 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
990 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
993 // set the contact ID
994 $this->_contactId
= $contact->id
;
996 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
997 //add contact to tags
998 if (isset($params['tag']) && !empty($params['tag'])) {
999 $params['tag'] = array_flip(explode(',', $params['tag']));
1000 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1004 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1005 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1009 if (!empty($parseStatusMsg)) {
1010 $message .= "<br />$parseStatusMsg";
1012 if (!empty($updateMembershipMsg)) {
1013 $message .= "<br />$updateMembershipMsg";
1016 $session = CRM_Core_Session
::singleton();
1017 $session->setStatus($message, ts('Contact Saved'), 'success');
1019 // add the recently viewed contact
1020 $recentOther = array();
1021 if (($session->get('userID') == $contact->id
) ||
1022 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1024 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1027 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1028 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1031 CRM_Utils_Recent
::add($contact->display_name
,
1032 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1034 $this->_contactType
,
1036 $contact->display_name
,
1040 // here we replace the user context with the url to view this contact
1041 $buttonName = $this->controller
->getButtonName();
1042 if ($buttonName == $this->getButtonName('upload', 'new')) {
1043 $contactSubTypes = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_contactSubType
));
1044 $resetStr = "reset=1&ct={$contact->contact_type}";
1045 $resetStr .= (count($contactSubTypes) == 1) ?
"&cst=" . array_pop($contactSubTypes) : '';
1046 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1049 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1050 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1051 //validate the qfKey
1052 $urlParams = 'reset=1&cid=' . $contact->id
;
1054 $urlParams .= "&context=$context";
1056 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1057 $urlParams .= "&key=$qfKey";
1060 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1063 // now invoke the post hook
1064 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1065 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1068 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1073 * Is there any real significant data in the hierarchical location array.
1075 * @param array $fields
1076 * The hierarchical value representation of this location.
1079 * true if data exists, false otherwise
1081 public static function blockDataExists(&$fields) {
1082 if (!is_array($fields)) {
1086 static $skipFields = array(
1095 foreach ($fields as $name => $value) {
1097 foreach ($skipFields as $skip) {
1098 if (strpos("[$skip]", $name) !== FALSE) {
1099 if ($name == 'phone') {
1109 if (is_array($value)) {
1110 if (self
::blockDataExists($value)) {
1115 if (!empty($value)) {
1125 * That checks for duplicate contacts.
1127 * @param array $fields
1128 * Fields array which are submitted.
1130 * @param int $contactID
1132 * @param string $contactType
1135 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1136 // if this is a forced save, ignore find duplicate rule
1137 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1139 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts($fields, $contactType, 'Supervised', array($contactID));
1142 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1144 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1145 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
1146 'count' => count($contactLinks['rows']),
1147 'plural' => '%count matching contacts were found.<br />',
1149 if ($contactLinks['msg'] == 'view') {
1150 $duplicateContactsLinks .= ts('You can View the existing contact', array(
1151 'count' => count($contactLinks['rows']),
1152 'plural' => 'You can View the existing contacts',
1156 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array(
1157 'count' => count($contactLinks['rows']),
1158 'plural' => 'You can View or Edit the existing contacts',
1161 if ($contactLinks['msg'] == 'merge') {
1162 // We should also get a merge link if this is for an existing contact
1163 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1165 $duplicateContactsLinks .= '.';
1166 $duplicateContactsLinks .= '</div>';
1167 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1169 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1171 $row .= ' <td class="matching-contacts-name"> ';
1172 $row .= CRM_Utils_Array
::value('display_name', $contactLinks['rows'][$i]);
1174 $row .= ' <td class="matching-contacts-email"> ';
1175 $row .= CRM_Utils_Array
::value('primary_email', $contactLinks['rows'][$i]);
1177 $row .= ' <td class="action-items"> ';
1178 $row .= CRM_Utils_Array
::value('view', $contactLinks['rows'][$i]);
1179 $row .= CRM_Utils_Array
::value('edit', $contactLinks['rows'][$i]);
1180 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1185 $duplicateContactsLinks .= $row . '</table>';
1186 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1188 $errors['_qf_default'] = $duplicateContactsLinks;
1190 // let smarty know that there are duplicates
1191 $template = CRM_Core_Smarty
::singleton();
1192 $template->assign('isDuplicate', 1);
1194 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1195 // add a session message for no matching contacts
1196 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1202 * Use the form name to create the tpl file name.
1206 public function getTemplateFileName() {
1207 if ($this->_contactSubType
) {
1208 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1209 $template = CRM_Core_Form
::getTemplate();
1210 if ($template->template_exists($templateFile)) {
1211 return $templateFile;
1214 return parent
::getTemplateFileName();
1218 * Parse all address blocks present in given params
1219 * and return parse result for all address blocks,
1220 * This function either parse street address in to child
1221 * elements or build street address from child elements.
1223 * @param array $params
1224 * of key value consist of address blocks.
1227 * as array of success/fails for each address block
1229 public function parseAddress(&$params) {
1230 $parseSuccess = $parsedFields = array();
1231 if (!is_array($params['address']) ||
1232 CRM_Utils_System
::isNull($params['address'])
1234 return $parseSuccess;
1237 foreach ($params['address'] as $instance => & $address) {
1238 $buildStreetAddress = FALSE;
1239 $parseFieldName = 'street_address';
1245 if (!empty($address[$fld])) {
1246 $parseFieldName = 'street_number';
1247 $buildStreetAddress = TRUE;
1252 // main parse string.
1253 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1255 // parse address field.
1256 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1258 if ($buildStreetAddress) {
1259 //hack to ignore spaces between number and suffix.
1260 //here user gives input as street_number so it has to
1261 //be street_number and street_number_suffix, but
1262 //due to spaces though preg detect string as street_name
1263 //consider it as 'street_number_suffix'.
1264 $suffix = $parsedFields['street_number_suffix'];
1266 $suffix = $parsedFields['street_name'];
1268 $address['street_number_suffix'] = $suffix;
1269 $address['street_number'] = $parsedFields['street_number'];
1271 $streetAddress = NULL;
1274 'street_number_suffix',
1278 if (in_array($fld, array(
1282 $streetAddress .= ' ';
1284 // CRM-17619 - if the street number suffix begins with a number, add a space
1285 $thesuffix = CRM_Utils_Array
::value('street_number_suffix', $address);
1286 if ($fld === 'street_number_suffix' && $thesuffix) {
1287 if (ctype_digit(substr($thesuffix, 0, 1))) {
1288 $streetAddress .= ' ';
1291 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1293 $address['street_address'] = trim($streetAddress);
1294 $parseSuccess[$instance] = TRUE;
1298 // consider address is automatically parseable,
1299 // when we should found street_number and street_name
1300 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
1304 // check for original street address string.
1305 if (empty($parseString)) {
1309 $parseSuccess[$instance] = $success;
1311 // we do not reset element values, but keep what we've parsed
1312 // in case of partial matches: CRM-8378
1314 // merge parse address in to main address block.
1315 $address = array_merge($address, $parsedFields);
1319 return $parseSuccess;
1323 * Check parse result and if some address block fails then this
1324 * function return the status message for all address blocks.
1326 * @param array $parseResult
1327 * An array of address blk instance and its status.
1329 * @return null|string
1330 * $statusMsg string status message for all address blocks.
1332 public static function parseAddressStatusMsg($parseResult) {
1334 if (!is_array($parseResult) ||
empty($parseResult)) {
1338 $parseFails = array();
1339 foreach ($parseResult as $instance => $success) {
1341 $parseFails[] = self
::ordinalNumber($instance);
1345 if (!empty($parseFails)) {
1346 $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.",
1347 array(1 => implode(', ', $parseFails))
1355 * Convert normal number to ordinal number format.
1356 * like 1 => 1st, 2 => 2nd and so on...
1358 * @param int $number
1359 * number to convert in to ordinal number.
1362 * ordinal number for given number.
1364 public static function ordinalNumber($number) {
1365 if (empty($number)) {
1370 switch (floor($number / 10) %
10) {
1373 switch ($number %
10) {
1388 return "$number$str";
1392 * Update membership status to deceased.
1393 * function return the status message for updated membership.
1395 * @param array $deceasedParams
1396 * having contact id and deceased value.
1398 * @return null|string
1399 * $updateMembershipMsg string status message for updated membership.
1401 public function updateMembershipStatus($deceasedParams) {
1402 $updateMembershipMsg = NULL;
1403 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1404 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1406 // process to set membership status to deceased for both active/inactive membership
1408 $this->_contactType
== 'Individual' && !empty($deceasedParams['is_deceased'])
1411 $session = CRM_Core_Session
::singleton();
1412 $userId = $session->get('userID');
1414 $userId = $contactId;
1417 // get deceased status id
1418 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1419 $deceasedStatusId = array_search('Deceased', $allStatus);
1420 if (!$deceasedStatusId) {
1421 return $updateMembershipMsg;
1425 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1426 return $updateMembershipMsg;
1429 // get non deceased membership
1430 $dao = new CRM_Member_DAO_Membership();
1431 $dao->contact_id
= $contactId;
1432 $dao->whereAdd("status_id != $deceasedStatusId");
1434 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1435 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1437 while ($dao->fetch()) {
1438 // update status to deceased (for both active/inactive membership )
1439 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1440 'status_id', $deceasedStatusId
1443 // add membership log
1444 $membershipLog = array(
1445 'membership_id' => $dao->id
,
1446 'status_id' => $deceasedStatusId,
1447 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1448 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1449 'modified_id' => $userId,
1450 'modified_date' => date('Ymd'),
1451 'membership_type_id' => $dao->membership_type_id
,
1452 'max_related' => $dao->max_related
,
1455 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1457 //create activity when membership status is changed
1458 $activityParam = array(
1459 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1460 'source_contact_id' => $userId,
1461 'target_contact_id' => $dao->contact_id
,
1462 'source_record_id' => $dao->id
,
1463 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1467 'activity_date_time' => date('Y-m-d H:i:s'),
1469 'is_current_revision' => 1,
1472 $activityResult = civicrm_api('activity', 'create', $activityParam);
1479 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1480 array(1 => $memCount)
1485 return $updateMembershipMsg;