3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class generates form components generic to all the contact types.
39 * It delegates the work to lower level subclasses and integrates the changes
40 * back in. It also uses a lot of functionality with the CRM API's, so any change
41 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
44 class CRM_Contact_Form_Contact
extends CRM_Core_Form
{
47 * The contact type of the form
54 * The contact type of the form
58 public $_contactSubType;
61 * The contact id, used when editing the form
68 * The default group id passed in via the url
75 * The default tag id passed in via the url
82 * Name of de-dupe button
86 protected $_dedupeButtonName;
89 * Name of optional save duplicate button
93 protected $_duplicateButtonName;
95 protected $_editOptions = array();
97 protected $_oldSubtypes = array();
101 public $_values = array();
105 public $_customValueCount;
107 * The array of greetings with option group and filed names
114 * Do we want to parse street address.
116 public $_parseStreetAddress;
119 * Check contact has a subtype or not
121 public $_isContactSubType;
124 * Lets keep a cache of all the values that we retrieved.
125 * THis is an attempt to avoid the number of update statements
126 * during the write phase
128 public $_preEditValues;
131 * Build all the data structures needed to build the form
135 public function preProcess() {
136 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
138 $this->_dedupeButtonName
= $this->getButtonName('refresh', 'dedupe');
139 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
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 array('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'", array(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', array(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 = array('id' => $this->_contactId
);
196 $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date');
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', array(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 $displayName = ts('Edit %1', array(1 => $displayName));
215 // Check if this is default domain contact CRM-10482
216 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
217 $displayName .= ' (' . ts('default organization') . ')';
220 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
221 CRM_Utils_System
::setTitle($displayName);
222 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
223 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
225 $urlParams = 'reset=1&cid=' . $this->_contactId
;
227 $urlParams .= "&context=$context";
230 if (CRM_Utils_Rule
::qfKey($qfKey)) {
232 $urlParams .= "&key=$qfKey";
235 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
237 $values = $this->get('values');
238 // get contact values.
239 if (!empty($values)) {
240 $this->_values
= $values;
244 'id' => $this->_contactId
,
245 'contact_id' => $this->_contactId
,
246 'noRelationships' => TRUE,
251 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
252 $this->set('values', $this->_values
);
256 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
260 // parse street address, CRM-5450
261 $this->_parseStreetAddress
= $this->get('parseStreetAddress');
262 if (!isset($this->_parseStreetAddress
)) {
263 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
266 $this->_parseStreetAddress
= FALSE;
267 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
268 $this->_parseStreetAddress
= TRUE;
270 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
272 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
274 $this->_editOptions
= $this->get('contactEditOptions');
275 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
276 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
277 'contact_edit_options', TRUE, NULL,
278 FALSE, 'name', TRUE, 'AND v.filter = 0'
280 $this->set('contactEditOptions', $this->_editOptions
);
283 // build demographics only for Individual contact type
284 if ($this->_contactType
!= 'Individual' &&
285 array_key_exists('Demographics', $this->_editOptions
)
287 unset($this->_editOptions
['Demographics']);
290 // in update mode don't show notes
291 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
292 unset($this->_editOptions
['Notes']);
295 $this->assign('editOptions', $this->_editOptions
);
296 $this->assign('contactType', $this->_contactType
);
297 $this->assign('contactSubType', $this->_contactSubType
);
299 //build contact subtype form element, CRM-6864
300 $buildContactSubType = TRUE;
301 if ($this->_contactSubType
&& ($this->_action
& CRM_Core_Action
::ADD
)) {
302 $buildContactSubType = FALSE;
304 $this->assign('buildContactSubType', $buildContactSubType);
306 // get the location blocks.
307 $this->_blocks
= $this->get('blocks');
308 if (CRM_Utils_System
::isNull($this->_blocks
)) {
309 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
310 'contact_edit_options', TRUE, NULL,
311 FALSE, 'name', TRUE, 'AND v.filter = 1'
313 $this->set('blocks', $this->_blocks
);
315 $this->assign('blocks', $this->_blocks
);
317 // this is needed for custom data.
318 $this->assign('entityID', $this->_contactId
);
320 // also keep the convention.
321 $this->assign('contactId', $this->_contactId
);
324 CRM_Contact_Form_Location
::preProcess($this);
326 // retain the multiple count custom fields value
327 if (!empty($_POST['hidden_custom'])) {
328 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
330 if ($contactSubType = CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
331 $paramSubType = implode(',', $contactSubType);
334 $this->_getCachedTree
= FALSE;
335 unset($customGroupCount[0]);
336 foreach ($customGroupCount as $groupID => $groupCount) {
337 if ($groupCount > 1) {
338 $this->set('groupID', $groupID);
340 for ($i = 0; $i <= $groupCount; $i++
) {
341 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
342 $i, $this->_contactType
344 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
349 //reset all the ajax stuff, for normal processing
350 if (isset($this->_groupTree
)) {
351 $this->_groupTree
= NULL;
353 $this->set('groupID', NULL);
354 $this->_getCachedTree
= TRUE;
357 // execute preProcess dynamically by js else execute normal preProcess
358 if (array_key_exists('CustomData', $this->_editOptions
)) {
359 //assign a parameter to pass for sub type multivalue
360 //custom field to load
361 if ($this->_contactSubType ||
isset($paramSubType)) {
362 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
363 str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
365 $this->assign('paramSubType', $paramSubType);
368 if (CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject)) {
369 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
372 $contactSubType = $this->_contactSubType
;
373 // need contact sub type to build related grouptree array during post process
374 if (!empty($_POST['contact_sub_type'])) {
375 $contactSubType = $_POST['contact_sub_type'];
377 //only custom data has preprocess hence directly call it
378 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
379 1, $this->_contactType
, $this->_contactId
381 $this->assign('customValueCount', $this->_customValueCount
);
387 * Set default values for the form. Note that in edit/view mode
388 * the default values are retrieved from the database
393 public function setDefaultValues() {
394 $defaults = $this->_values
;
397 if ($this->_action
& CRM_Core_Action
::ADD
) {
398 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
399 // set group and tag defaults if any
401 $defaults['group'][] = $this->_gid
;
404 $defaults['tag'][$this->_tid
] = 1;
407 if ($this->_contactSubType
) {
408 $defaults['contact_sub_type'] = $this->_contactSubType
;
412 foreach ($defaults['email'] as $dontCare => & $val) {
413 if (isset($val['signature_text'])) {
414 $val['signature_text_hidden'] = $val['signature_text'];
416 if (isset($val['signature_html'])) {
417 $val['signature_html_hidden'] = $val['signature_html'];
421 if (!empty($defaults['contact_sub_type'])) {
422 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
425 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
426 foreach ($this->_editOptions
as $name => $label) {
427 if (!in_array($name, array('Address', 'Notes'))) {
428 $className = 'CRM_Contact_Form_Edit_' . $name;
429 $className::setDefaultValues($this, $defaults);
433 //set address block defaults
434 CRM_Contact_Form_Edit_Address
::setDefaultValues($defaults, $this);
437 if (!empty($defaults['image_URL'])) {
438 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String
::unstupifyUrl($defaults['image_URL']));
439 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
440 $this->assign('imageWidth', $imageWidth);
441 $this->assign('imageHeight', $imageHeight);
442 $this->assign('imageThumbWidth', $imageThumbWidth);
443 $this->assign('imageThumbHeight', $imageThumbHeight);
444 $this->assign('imageURL', $defaults['image_URL']);
447 //set location type and country to default for each block
448 $this->blockSetDefaults($defaults);
450 $this->_preEditValues
= $defaults;
455 * Do the set default related to location type id,
456 * primary location, default country
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
503 CRM_Utils_Array
::value(
505 CRM_Utils_Array
::value($instance, $defaults[$name])
511 //set location to primary for first one.
512 if ($instance == 1) {
514 $defaults[$name][$instance]['is_primary'] = TRUE;
515 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
518 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
519 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
522 //set default country
523 if ($name == 'address' && $config->defaultContactCountry
) {
524 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
527 //set default state/province
528 if ($name == 'address' && $config->defaultContactStateProvince
) {
529 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
532 //set default phone type.
533 if ($name == 'phone' && $defPhoneTypeId) {
534 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
536 //set default website type.
537 if ($name == 'website' && $defWebsiteTypeId) {
538 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
541 //set default im provider.
542 if ($name == 'im' && $defIMProviderId) {
543 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
548 $defaults[$name][1]['is_primary'] = TRUE;
554 * add the rules (mainly global rules) for form.
555 * All local rules are added near the element
560 public function addRules() {
561 // skip adding formRules when custom data is build
562 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
566 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
568 // Call Locking check if editing existing contact
569 if ($this->_contactId
) {
570 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
573 if (array_key_exists('Address', $this->_editOptions
)) {
574 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
577 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
578 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
583 * Global validation rules for the form
585 * @param array $fields
586 * Posted values of the form.
587 * @param array $errors
588 * List of errors to be posted back to the form.
589 * @param int $contactId
590 * Contact id if doing update.
595 public static function formRule($fields, &$errors, $contactId = NULL) {
596 $config = CRM_Core_Config
::singleton();
599 //1. for each block only single value can be marked as is_primary = true.
600 //2. location type id should be present if block data present.
601 //3. check open id across db and other each block for duplicate.
602 //4. at least one location should be primary.
603 //5. also get primaryID from email or open id block.
605 // take the location blocks.
606 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
607 'contact_edit_options', TRUE, NULL,
608 FALSE, 'name', TRUE, 'AND v.filter = 1'
611 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
612 'contact_edit_options', TRUE, NULL,
613 FALSE, 'name', TRUE, 'AND v.filter = 0'
615 //get address block inside.
616 if (array_key_exists('Address', $otherEditOptions)) {
617 $blocks['Address'] = $otherEditOptions['Address'];
622 foreach ($blocks as $name => $label) {
623 $hasData = $hasPrimary = array();
624 $name = strtolower($name);
625 if (!empty($fields[$name]) && is_array($fields[$name])) {
626 foreach ($fields[$name] as $instance => $blockValues) {
627 $dataExists = self
::blockDataExists($blockValues);
629 if (!$dataExists && $name == 'address') {
630 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
634 // skip remaining checks for website
635 if ($name == 'website') {
639 $hasData[] = $instance;
640 if (!empty($blockValues['is_primary'])) {
641 $hasPrimary[] = $instance;
643 in_array($name, array(
646 )) && !empty($blockValues[$name])
648 $primaryID = $blockValues[$name];
652 if (empty($blockValues['location_type_id'])) {
653 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
657 if ($name == 'openid' && !empty($blockValues[$name])) {
658 $oid = new CRM_Core_DAO_OpenID();
659 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
660 $cid = isset($contactId) ?
$contactId : 0;
661 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
662 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
667 if (empty($hasPrimary) && !empty($hasData)) {
668 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
671 if (count($hasPrimary) > 1) {
672 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
679 //do validations for all opend ids they should be distinct.
680 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
681 foreach ($openIds as $instance => $value) {
682 if (!array_key_exists($instance, array_unique($openIds))) {
683 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
688 // street number should be digit + suffix, CRM-5450
689 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
690 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
694 if ($parseStreetAddress) {
695 if (isset($fields['address']) &&
696 is_array($fields['address'])
698 $invalidStreetNumbers = array();
699 foreach ($fields['address'] as $cnt => $address) {
700 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
701 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
702 if (empty($parsedAddress['street_number'])) {
703 $invalidStreetNumbers[] = $cnt;
708 if (!empty($invalidStreetNumbers)) {
709 $first = $invalidStreetNumbers[0];
710 foreach ($invalidStreetNumbers as & $num) {
711 $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
713 $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)));
722 * Build the form object
726 public function buildQuickForm() {
727 //load form for child blocks
728 if ($this->_addBlockName
) {
729 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
730 return $className::buildQuickForm($this);
733 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
734 $deleteExtra = ts('Are you sure you want to delete contact image.');
736 CRM_Core_Action
::DELETE
=> array(
737 'name' => ts('Delete Contact Image'),
738 'url' => 'civicrm/contact/image',
739 'qs' => 'reset=1&cid=%%id%%&action=delete',
741 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
744 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
745 CRM_Core_Action
::DELETE
,
747 'id' => $this->_contactId
,
751 'contact.image.delete',
755 $this->assign('deleteURL', $deleteURL);
758 //build contact type specific fields
759 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
760 $className::buildQuickForm($this);
762 // build Custom data if Custom data present in edit option
763 $buildCustomData = 'noCustomDataPresent';
764 if (array_key_exists('CustomData', $this->_editOptions
)) {
765 $buildCustomData = "customDataPresent";
768 // subtype is a common field. lets keep it here
769 $subtypes = CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType
));
770 if (!empty($subtypes)) {
771 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
774 'id' => 'contact_sub_type',
775 'multiple' => 'multiple',
776 'class' => $buildCustomData . ' crm-select2',
781 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
782 foreach ($this->_editOptions
as $name => $label) {
783 if ($name == 'Address') {
784 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
787 if ($name == 'TagsAndGroups') {
790 $className = 'CRM_Contact_Form_Edit_' . $name;
791 $className::buildQuickForm($this);
794 // build tags and groups
795 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
796 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
798 // build location blocks.
799 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
800 CRM_Contact_Form_Location
::buildQuickForm($this);
803 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
804 $this->addUploadElement('image_URL');
806 // add the dedupe button
807 $this->addElement('submit',
808 $this->_dedupeButtonName
,
809 ts('Check for Matching Contact(s)')
811 $this->addElement('submit',
812 $this->_duplicateButtonName
,
813 ts('Save Matching Contact')
815 $this->addElement('submit',
816 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
817 ts('Save With Duplicate Household')
823 'name' => ts('Save'),
828 if (CRM_Core_Permission
::check('add contacts')) {
831 'name' => ts('Save and New'),
832 'spacing' => ' ',
838 'name' => ts('Cancel'),
841 if (!empty($this->_values
['contact_sub_type'])) {
842 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
843 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
846 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
848 $this->addButtons($buttons);
852 * Form submission of new/edit contact is processed.
857 public function postProcess() {
858 // check if dedupe button, if so return.
859 $buttonName = $this->controller
->getButtonName();
860 if ($buttonName == $this->_dedupeButtonName
) {
864 //get the submitted values in an array
865 $params = $this->controller
->exportValues($this->_name
);
867 $group = CRM_Utils_Array
::value('group', $params);
868 if (!empty($group) && is_array($group)) {
869 unset($params['group']);
870 foreach ($group as $key => $value) {
871 $params['group'][$value] = 1;
875 CRM_Contact_BAO_Contact_Optimizer
::edit($params, $this->_preEditValues
);
877 if (!empty($params['image_URL'])) {
878 CRM_Contact_BAO_Contact
::processImageParams($params);
881 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
882 $params['current_employer'] = $params['current_employer_id'];
885 // don't carry current_employer_id field,
886 // since we don't want to directly update DAO object without
887 // handling related business logic ( eg related membership )
888 if (isset($params['current_employer_id'])) {
889 unset($params['current_employer_id']);
892 $params['contact_type'] = $this->_contactType
;
893 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
894 $params['contact_sub_type'] = array($this->_contactSubType
);
897 if ($this->_contactId
) {
898 $params['contact_id'] = $this->_contactId
;
901 //make deceased date null when is_deceased = false
902 if ($this->_contactType
== 'Individual' && !empty($this->_editOptions
['Demographics']) && empty($params['is_deceased'])) {
903 $params['is_deceased'] = FALSE;
904 $params['deceased_date'] = NULL;
907 if (isset($params['contact_id'])) {
908 // process membership status for deceased contact
909 $deceasedParams = array(
910 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
911 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
912 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
914 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
917 // action is taken depending upon the mode
918 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
919 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
922 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
925 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
928 //if subtype is set, send subtype as extend to validate subtype customfield
929 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
931 $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
) && !empty($params['group'])) {
954 unset($params['group']);
957 if (!empty($params['contact_id']) && ($this->_action
& CRM_Core_Action
::UPDATE
) && !empty($params['group'])) {
958 // figure out which all groups are intended to be removed
959 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
960 if (is_array($contactGroupList)) {
961 foreach ($contactGroupList as $key) {
962 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
963 $params['group'][$key['group_id']] = -1;
969 // parse street address, CRM-5450
970 $parseStatusMsg = NULL;
971 if ($this->_parseStreetAddress
) {
972 $parseResult = self
::parseAddress($params);
973 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
976 // Allow un-setting of location info, CRM-5969
977 $params['updateBlankLocInfo'] = TRUE;
979 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
982 if ($this->_contactId
) {
983 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
986 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
989 // set the contact ID
990 $this->_contactId
= $contact->id
;
992 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
993 //add contact to tags
994 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
997 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
998 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1002 if (!empty($parseStatusMsg)) {
1003 $message .= "<br />$parseStatusMsg";
1005 if (!empty($updateMembershipMsg)) {
1006 $message .= "<br />$updateMembershipMsg";
1009 $session = CRM_Core_Session
::singleton();
1010 $session->setStatus($message, ts('Contact Saved'), 'success');
1012 // add the recently viewed contact
1013 $recentOther = array();
1014 if (($session->get('userID') == $contact->id
) ||
1015 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1017 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1020 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1021 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1024 CRM_Utils_Recent
::add($contact->display_name
,
1025 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1027 $this->_contactType
,
1029 $contact->display_name
,
1033 // here we replace the user context with the url to view this contact
1034 $buttonName = $this->controller
->getButtonName();
1035 if ($buttonName == $this->getButtonName('upload', 'new')) {
1036 $resetStr = "reset=1&ct={$contact->contact_type}";
1037 $resetStr .= $this->_contactSubType ?
"&cst={$this->_contactSubType}" : '';
1038 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1041 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1042 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1043 //validate the qfKey
1044 $urlParams = 'reset=1&cid=' . $contact->id
;
1046 $urlParams .= "&context=$context";
1048 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1049 $urlParams .= "&key=$qfKey";
1052 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1055 // now invoke the post hook
1056 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1057 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1060 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1065 * Is there any real significant data in the hierarchical location array
1067 * @param array $fields
1068 * The hierarchical value representation of this location.
1071 * true if data exists, false otherwise
1073 public static function blockDataExists(&$fields) {
1074 if (!is_array($fields)) {
1078 static $skipFields = array(
1087 foreach ($fields as $name => $value) {
1089 foreach ($skipFields as $skip) {
1090 if (strpos("[$skip]", $name) !== FALSE) {
1091 if ($name == 'phone') {
1101 if (is_array($value)) {
1102 if (self
::blockDataExists($value)) {
1107 if (!empty($value)) {
1117 * That checks for duplicate contacts
1119 * @param array $fields
1120 * Fields array which are submitted.
1122 * @param int $contactID
1124 * @param string $contactType
1127 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1128 // if this is a forced save, ignore find duplicate rule
1129 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1131 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1132 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1135 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1137 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1138 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
1139 'count' => count($contactLinks['rows']),
1140 'plural' => '%count matching contacts were found.<br />',
1142 if ($contactLinks['msg'] == 'view') {
1143 $duplicateContactsLinks .= ts('You can View the existing contact', array(
1144 'count' => count($contactLinks['rows']),
1145 'plural' => 'You can View the existing contacts',
1149 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array(
1150 'count' => count($contactLinks['rows']),
1151 'plural' => 'You can View or Edit the existing contacts',
1154 if ($contactLinks['msg'] == 'merge') {
1155 // We should also get a merge link if this is for an existing contact
1156 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1158 $duplicateContactsLinks .= '.';
1159 $duplicateContactsLinks .= '</div>';
1160 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1162 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1164 $row .= ' <td class="matching-contacts-name"> ';
1165 $row .= $contactLinks['rows'][$i]['display_name'];
1167 $row .= ' <td class="matching-contacts-email"> ';
1168 $row .= $contactLinks['rows'][$i]['primary_email'];
1170 $row .= ' <td class="action-items"> ';
1171 $row .= $contactLinks['rows'][$i]['view'];
1172 $row .= $contactLinks['rows'][$i]['edit'];
1173 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1178 $duplicateContactsLinks .= $row . '</table>';
1179 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1181 $errors['_qf_default'] = $duplicateContactsLinks;
1184 // let smarty know that there are duplicates
1185 $template = CRM_Core_Smarty
::singleton();
1186 $template->assign('isDuplicate', 1);
1188 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1189 // add a session message for no matching contacts
1190 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1196 * Use the form name to create the tpl file name
1200 public function getTemplateFileName() {
1201 if ($this->_contactSubType
) {
1202 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1203 $template = CRM_Core_Form
::getTemplate();
1204 if ($template->template_exists($templateFile)) {
1205 return $templateFile;
1208 return parent
::getTemplateFileName();
1212 * Parse all address blocks present in given params
1213 * and return parse result for all address blocks,
1214 * This function either parse street address in to child
1215 * elements or build street address from child elements.
1217 * @param array $params
1218 * of key value consist of address blocks.
1221 * as array of sucess/fails for each address block
1223 public function parseAddress(&$params) {
1224 $parseSuccess = $parsedFields = array();
1225 if (!is_array($params['address']) ||
1226 CRM_Utils_System
::isNull($params['address'])
1228 return $parseSuccess;
1231 foreach ($params['address'] as $instance => & $address) {
1232 $buildStreetAddress = FALSE;
1233 $parseFieldName = 'street_address';
1239 if (!empty($address[$fld])) {
1240 $parseFieldName = 'street_number';
1241 $buildStreetAddress = TRUE;
1246 // main parse string.
1247 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1249 // parse address field.
1250 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1252 if ($buildStreetAddress) {
1253 //hack to ignore spaces between number and suffix.
1254 //here user gives input as street_number so it has to
1255 //be street_number and street_number_suffix, but
1256 //due to spaces though preg detect string as street_name
1257 //consider it as 'street_number_suffix'.
1258 $suffix = $parsedFields['street_number_suffix'];
1260 $suffix = $parsedFields['street_name'];
1262 $address['street_number_suffix'] = $suffix;
1263 $address['street_number'] = $parsedFields['street_number'];
1265 $streetAddress = NULL;
1268 'street_number_suffix',
1272 if (in_array($fld, array(
1276 $streetAddress .= ' ';
1278 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1280 $address['street_address'] = trim($streetAddress);
1281 $parseSuccess[$instance] = TRUE;
1285 // consider address is automatically parseable,
1286 // when we should found street_number and street_name
1287 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
1291 // check for original street address string.
1292 if (empty($parseString)) {
1296 $parseSuccess[$instance] = $success;
1298 // we do not reset element values, but keep what we've parsed
1299 // in case of partial matches: CRM-8378
1301 // merge parse address in to main address block.
1302 $address = array_merge($address, $parsedFields);
1306 return $parseSuccess;
1310 * Check parse result and if some address block fails then this
1311 * function return the status message for all address blocks.
1313 * @param array $parseResult
1314 * An array of address blk instance and its status.
1316 * @return null|string
1317 * $statusMsg string status message for all address blocks.
1319 public static function parseAddressStatusMsg($parseResult) {
1321 if (!is_array($parseResult) ||
empty($parseResult)) {
1325 $parseFails = array();
1326 foreach ($parseResult as $instance => $success) {
1328 $parseFails[] = self
::ordinalNumber($instance);
1332 if (!empty($parseFails)) {
1333 $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.",
1334 array(1 => implode(', ', $parseFails))
1342 * Convert normal number to ordinal number format.
1343 * like 1 => 1st, 2 => 2nd and so on...
1345 * @param int $number
1346 * number to convert in to ordinal number.
1349 * ordinal number for given number.
1351 public static function ordinalNumber($number) {
1352 if (empty($number)) {
1357 switch (floor($number / 10) %
10) {
1360 switch ($number %
10) {
1375 return "$number$str";
1379 * Update membership status to deceased
1380 * function return the status message for updated membership.
1382 * @param array $deceasedParams
1383 * having contact id and deceased value.
1385 * @return null|string
1386 * $updateMembershipMsg string status message for updated membership.
1388 public function updateMembershipStatus($deceasedParams) {
1389 $updateMembershipMsg = NULL;
1390 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1391 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1393 // process to set membership status to deceased for both active/inactive membership
1395 $this->_contactType
== 'Individual' && !empty($deceasedParams['is_deceased'])
1398 $session = CRM_Core_Session
::singleton();
1399 $userId = $session->get('userID');
1401 $userId = $contactId;
1405 // get deceased status id
1406 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1407 $deceasedStatusId = array_search('Deceased', $allStatus);
1408 if (!$deceasedStatusId) {
1409 return $updateMembershipMsg;
1413 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1414 return $updateMembershipMsg;
1417 // get non deceased membership
1418 $dao = new CRM_Member_DAO_Membership();
1419 $dao->contact_id
= $contactId;
1420 $dao->whereAdd("status_id != $deceasedStatusId");
1422 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1423 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1425 while ($dao->fetch()) {
1426 // update status to deceased (for both active/inactive membership )
1427 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1428 'status_id', $deceasedStatusId
1431 // add membership log
1432 $membershipLog = array(
1433 'membership_id' => $dao->id
,
1434 'status_id' => $deceasedStatusId,
1435 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1436 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1437 'modified_id' => $userId,
1438 'modified_date' => date('Ymd'),
1439 'membership_type_id' => $dao->membership_type_id
,
1440 'max_related' => $dao->max_related
,
1444 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1446 //create activity when membership status is changed
1447 $activityParam = array(
1448 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1449 'source_contact_id' => $userId,
1450 'target_contact_id' => $dao->contact_id
,
1451 'source_record_id' => $dao->id
,
1452 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1456 'activity_date_time' => date('Y-m-d H:i:s'),
1458 'is_current_revision' => 1,
1461 $activityResult = civicrm_api('activity', 'create', $activityParam);
1468 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1469 array(1 => $memCount)
1474 return $updateMembershipMsg;