3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
87 protected $_dedupeButtonName;
90 * name of optional save duplicate button
95 protected $_duplicateButtonName;
97 protected $_editOptions = array();
99 protected $_oldSubtypes = array();
103 public $_values = array();
107 public $_customValueCount;
109 * The array of greetings with option group and filed names
116 * Do we want to parse street address.
118 public $_parseStreetAddress;
121 * check contact has a subtype or not
123 public $_isContactSubType;
126 * Lets keep a cache of all the values that we retrieved.
127 * THis is an attempt to avoid the number of update statements
128 * during the write phase
130 public $_preEditValues;
133 * build all the data structures needed to build the form
138 function preProcess() {
139 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
141 $this->_dedupeButtonName
= $this->getButtonName('refresh', 'dedupe');
142 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
144 $session = CRM_Core_Session
::singleton();
145 if ($this->_action
== CRM_Core_Action
::ADD
) {
146 // check for add contacts permissions
147 if (!CRM_Core_Permission
::check('add contacts')) {
148 CRM_Utils_System
::permissionDenied();
149 CRM_Utils_System
::civiExit();
151 $this->_contactType
= CRM_Utils_Request
::retrieve('ct', 'String',
152 $this, TRUE, NULL, 'REQUEST'
154 if (!in_array($this->_contactType
,
155 array('Individual', 'Household', 'Organization')
157 CRM_Core_Error
::statusBounce(ts('Could not get a contact id and/or contact type'));
160 $this->_isContactSubType
= FALSE;
161 if ($this->_contactSubType
= CRM_Utils_Request
::retrieve('cst', 'String', $this)) {
162 $this->_isContactSubType
= TRUE;
166 $this->_contactSubType
&&
167 !(CRM_Contact_BAO_ContactType
::isExtendsContactType($this->_contactSubType
, $this->_contactType
, TRUE))) {
168 CRM_Core_Error
::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType
)));
171 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Integer',
172 CRM_Core_DAO
::$_nullObject,
175 $this->_tid
= CRM_Utils_Request
::retrieve('tid', 'Integer',
176 CRM_Core_DAO
::$_nullObject,
179 $typeLabel = CRM_Contact_BAO_ContactType
::contactTypePairs(TRUE, $this->_contactSubType ?
180 $this->_contactSubType
: $this->_contactType
182 $typeLabel = implode(' / ', $typeLabel);
184 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $typeLabel)));
185 $session->pushUserContext(CRM_Utils_System
::url('civicrm/dashboard', 'reset=1'));
186 $this->_contactId
= NULL;
190 if (!$this->_contactId
) {
191 $this->_contactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
194 if ($this->_contactId
) {
196 $params = array('id' => $this->_contactId
);
197 $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date');
198 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
200 if (empty($defaults['id'])) {
201 CRM_Core_Error
::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId
)));
204 $this->_contactType
= CRM_Utils_Array
::value('contact_type', $defaults);
205 $this->_contactSubType
= CRM_Utils_Array
::value('contact_sub_type', $defaults);
207 // check for permissions
208 $session = CRM_Core_Session
::singleton();
209 if (!CRM_Contact_BAO_Contact_Permission
::allow($this->_contactId
, CRM_Core_Permission
::EDIT
)) {
210 CRM_Core_Error
::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
213 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactId
);
214 $displayName = ts('Edit %1', array(1 => $displayName));
216 // Check if this is default domain contact CRM-10482
217 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
218 $displayName .= ' (' . ts('default organization') . ')';
221 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
222 CRM_Utils_System
::setTitle($displayName);
223 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
224 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
226 $urlParams = 'reset=1&cid=' . $this->_contactId
;
228 $urlParams .= "&context=$context";
231 if (CRM_Utils_Rule
::qfKey($qfKey)) {
233 $urlParams .= "&key=$qfKey";
236 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
238 $values = $this->get('values');
239 // get contact values.
240 if (!empty($values)) {
241 $this->_values
= $values;
245 'id' => $this->_contactId
,
246 'contact_id' => $this->_contactId
,
247 'noRelationships' => TRUE,
252 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
253 $this->set('values', $this->_values
);
257 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
261 // parse street address, CRM-5450
262 $this->_parseStreetAddress
= $this->get('parseStreetAddress');
263 if (!isset($this->_parseStreetAddress
)) {
264 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
267 $this->_parseStreetAddress
= FALSE;
268 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
269 $this->_parseStreetAddress
= TRUE;
271 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
273 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
275 $this->_editOptions
= $this->get('contactEditOptions');
276 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
277 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
278 'contact_edit_options', TRUE, NULL,
279 FALSE, 'name', TRUE, 'AND v.filter = 0'
281 $this->set('contactEditOptions', $this->_editOptions
);
284 // build demographics only for Individual contact type
285 if ($this->_contactType
!= 'Individual' &&
286 array_key_exists('Demographics', $this->_editOptions
)
288 unset($this->_editOptions
['Demographics']);
291 // in update mode don't show notes
292 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
293 unset($this->_editOptions
['Notes']);
296 $this->assign('editOptions', $this->_editOptions
);
297 $this->assign('contactType', $this->_contactType
);
298 $this->assign('contactSubType', $this->_contactSubType
);
300 //build contact subtype form element, CRM-6864
301 $buildContactSubType = TRUE;
302 if ($this->_contactSubType
&& ($this->_action
& CRM_Core_Action
::ADD
)) {
303 $buildContactSubType = FALSE;
305 $this->assign('buildContactSubType', $buildContactSubType);
307 // get the location blocks.
308 $this->_blocks
= $this->get('blocks');
309 if (CRM_Utils_System
::isNull($this->_blocks
)) {
310 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
311 'contact_edit_options', TRUE, NULL,
312 FALSE, 'name', TRUE, 'AND v.filter = 1'
314 $this->set('blocks', $this->_blocks
);
316 $this->assign('blocks', $this->_blocks
);
318 // this is needed for custom data.
319 $this->assign('entityID', $this->_contactId
);
321 // also keep the convention.
322 $this->assign('contactId', $this->_contactId
);
325 CRM_Contact_Form_Location
::preProcess($this);
327 // retain the multiple count custom fields value
328 if (!empty($_POST['hidden_custom'])) {
329 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
331 if ($contactSubType = CRM_Utils_Array
::value( 'contact_sub_type', $_POST)) {
332 $paramSubType = implode(',', $contactSubType);
335 $this->_getCachedTree
= FALSE;
336 unset($customGroupCount[0]);
337 foreach ($customGroupCount as $groupID => $groupCount) {
338 if ($groupCount > 1) {
339 $this->set('groupID', $groupID);
341 for ($i = 0; $i <= $groupCount; $i++
) {
342 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
343 $i, $this->_contactType
345 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
350 //reset all the ajax stuff, for normal processing
351 if (isset($this->_groupTree
)) {
352 $this->_groupTree
= NULL;
354 $this->set('groupID', NULL);
355 $this->_getCachedTree
= TRUE;
358 // execute preProcess dynamically by js else execute normal preProcess
359 if (array_key_exists('CustomData', $this->_editOptions
)) {
360 //assign a parameter to pass for sub type multivalue
361 //custom field to load
362 if ($this->_contactSubType ||
isset($paramSubType)) {
363 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
364 str_replace( CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
366 $this->assign('paramSubType', $paramSubType);
369 if (CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject)) {
370 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
373 $contactSubType = $this->_contactSubType
;
374 // need contact sub type to build related grouptree array during post process
375 if (!empty($_POST['contact_sub_type'])) {
376 $contactSubType = $_POST['contact_sub_type'];
378 //only custom data has preprocess hence directly call it
379 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
380 1, $this->_contactType
, $this->_contactId
382 $this->assign('customValueCount', $this->_customValueCount
);
388 * This function sets the default values for the form. Note that in edit/view mode
389 * the default values are retrieved from the database
395 function setDefaultValues() {
396 $defaults = $this->_values
;
399 if ($this->_action
& CRM_Core_Action
::ADD
) {
400 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
401 // set group and tag defaults if any
403 $defaults['group'][] = $this->_gid
;
406 $defaults['tag'][$this->_tid
] = 1;
409 if ($this->_contactSubType
) {
410 $defaults['contact_sub_type'] = $this->_contactSubType
;
414 foreach ($defaults['email'] as $dontCare => & $val) {
415 if (isset($val['signature_text'])) {
416 $val['signature_text_hidden'] = $val['signature_text'];
418 if (isset($val['signature_html'])) {
419 $val['signature_html_hidden'] = $val['signature_html'];
423 if (!empty($defaults['contact_sub_type'])) {
424 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
427 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
428 foreach ($this->_editOptions
as $name => $label) {
429 if (!in_array($name, array('Address', 'Notes'))) {
430 $className = 'CRM_Contact_Form_Edit_' . $name;
431 $className::setDefaultValues($this, $defaults);
435 //set address block defaults
436 CRM_Contact_Form_Edit_Address
::setDefaultValues( $defaults, $this );
438 if (!empty($defaults['image_URL'])) {
439 list($imageWidth, $imageHeight) = getimagesize($defaults['image_URL']);
440 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
441 $this->assign('imageWidth', $imageWidth);
442 $this->assign('imageHeight', $imageHeight);
443 $this->assign('imageThumbWidth', $imageThumbWidth);
444 $this->assign('imageThumbHeight', $imageThumbHeight);
445 $this->assign('imageURL', $defaults['image_URL']);
448 //set location type and country to default for each block
449 $this->blockSetDefaults($defaults);
451 $this->_preEditValues
= $defaults;
456 * do the set default related to location type id,
457 * primary location, default country
460 function blockSetDefaults(&$defaults) {
461 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
462 sort($locationTypeKeys);
464 // get the default location type
465 $locationType = CRM_Core_BAO_LocationType
::getDefault();
467 // unset primary location type
468 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
469 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
471 // reset the array sequence
472 $locationTypeKeys = array_values($locationTypeKeys);
474 // get default phone and im provider id.
475 $defPhoneTypeId = key(CRM_Core_OptionGroup
::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
476 $defIMProviderId = key(CRM_Core_OptionGroup
::values('instant_messenger_service',
477 FALSE, FALSE, FALSE, ' AND is_default = 1'
480 $allBlocks = $this->_blocks
;
481 if (array_key_exists('Address', $this->_editOptions
)) {
482 $allBlocks['Address'] = $this->_editOptions
['Address'];
485 $config = CRM_Core_Config
::singleton();
486 foreach ($allBlocks as $blockName => $label) {
487 $name = strtolower($blockName);
488 $hasPrimary = $updateMode = FALSE;
490 // user is in update mode.
491 if (array_key_exists($name, $defaults) &&
492 !CRM_Utils_System
::isNull($defaults[$name])
497 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
498 // make we require one primary block, CRM-5505
502 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;
536 //set default im provider.
537 if ($name == 'im' && $defIMProviderId) {
538 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
543 $defaults[$name][1]['is_primary'] = TRUE;
547 // set defaults for country-state widget
548 if (!empty($defaults['address']) && is_array($defaults['address'])) {
549 foreach ($defaults['address'] as $blockId => $values) {
550 CRM_Contact_Form_Edit_Address
::fixStateSelect($this,
551 "address[$blockId][country_id]",
552 "address[$blockId][state_province_id]",
553 "address[$blockId][county_id]",
554 CRM_Utils_Array
::value('country_id',
555 $values, $config->defaultContactCountry
557 CRM_Utils_Array
::value('state_province_id',
558 $values, $config->defaultContactStateProvince
566 * This function is used to add the rules (mainly global rules) for form.
567 * All local rules are added near the element
573 function addRules() {
574 // skip adding formRules when custom data is build
575 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
579 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
581 // Call Locking check if editing existing contact
582 if ($this->_contactId
) {
583 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
586 if (array_key_exists('Address', $this->_editOptions
)) {
587 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
590 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
591 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
596 * global validation rules for the form
598 * @param array $fields posted values of the form
599 * @param array $errors list of errors to be posted back to the form
600 * @param int $contactId contact id if doing update.
602 * @return $primaryID email/openId
606 static function formRule($fields, &$errors, $contactId = NULL) {
607 $config = CRM_Core_Config
::singleton();
610 //1. for each block only single value can be marked as is_primary = true.
611 //2. location type id should be present if block data present.
612 //3. check open id across db and other each block for duplicate.
613 //4. at least one location should be primary.
614 //5. also get primaryID from email or open id block.
616 // take the location blocks.
617 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
618 'contact_edit_options', TRUE, NULL,
619 FALSE, 'name', TRUE, 'AND v.filter = 1'
622 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
623 'contact_edit_options', TRUE, NULL,
624 FALSE, 'name', TRUE, 'AND v.filter = 0'
626 //get address block inside.
627 if (array_key_exists('Address', $otherEditOptions)) {
628 $blocks['Address'] = $otherEditOptions['Address'];
633 foreach ($blocks as $name => $label) {
634 $hasData = $hasPrimary = array();
635 $name = strtolower($name);
636 if (!empty($fields[$name]) && is_array($fields[$name])) {
637 foreach ($fields[$name] as $instance => $blockValues) {
638 $dataExists = self
::blockDataExists($blockValues);
640 if (!$dataExists && $name == 'address') {
641 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
645 // skip remaining checks for website
646 if ($name == 'website') {
650 $hasData[] = $instance;
651 if (!empty($blockValues['is_primary'])) {
652 $hasPrimary[] = $instance;
654 in_array($name, array(
655 'email', 'openid')) && !empty($blockValues[$name])) {
656 $primaryID = $blockValues[$name];
660 if (empty($blockValues['location_type_id'])) {
661 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
665 if ($name == 'openid' && !empty($blockValues[$name])) {
666 $oid = new CRM_Core_DAO_OpenID();
667 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
668 $cid = isset($contactId) ?
$contactId : 0;
669 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
670 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
675 if (empty($hasPrimary) && !empty($hasData)) {
676 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
679 if (count($hasPrimary) > 1) {
680 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
687 //do validations for all opend ids they should be distinct.
688 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
689 foreach ($openIds as $instance => $value) {
690 if (!array_key_exists($instance, array_unique($openIds))) {
691 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
696 // street number should be digit + suffix, CRM-5450
697 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
698 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
702 if ($parseStreetAddress) {
703 if (isset($fields['address']) &&
704 is_array($fields['address'])
706 $invalidStreetNumbers = array();
707 foreach ($fields['address'] as $cnt => $address) {
708 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
709 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
710 if (empty($parsedAddress['street_number'])) {
711 $invalidStreetNumbers[] = $cnt;
716 if (!empty($invalidStreetNumbers)) {
717 $first = $invalidStreetNumbers[0];
718 foreach ($invalidStreetNumbers as & $num) $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
719 $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)));
728 * Function to actually build the form
733 public function buildQuickForm() {
734 //load form for child blocks
735 if ($this->_addBlockName
) {
736 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
737 return $className::buildQuickForm($this);
740 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
741 $deleteExtra = ts('Are you sure you want to delete contact image.');
743 CRM_Core_Action
::DELETE
=>
745 'name' => ts('Delete Contact Image'),
746 'url' => 'civicrm/contact/image',
747 'qs' => 'reset=1&cid=%%id%%&action=delete',
749 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
752 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
753 CRM_Core_Action
::DELETE
,
755 'id' => $this->_contactId
,
759 'contact.image.delete',
763 $this->assign('deleteURL', $deleteURL);
766 //build contact type specific fields
767 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
768 $className::buildQuickForm($this);
770 // build Custom data if Custom data present in edit option
771 $buildCustomData = 'noCustomDataPresent';
772 if (array_key_exists('CustomData', $this->_editOptions
)) {
773 $buildCustomData = "customDataPresent";
776 // subtype is a common field. lets keep it here
777 $subtypes = CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType
));
778 if (!empty($subtypes)) {
779 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
782 'id' => 'contact_sub_type',
783 'multiple' => 'multiple',
784 'class' => $buildCustomData . ' crm-select2',
789 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
790 foreach ($this->_editOptions
as $name => $label) {
791 if ($name == 'Address') {
792 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
795 if ($name == 'TagsAndGroups') {
798 $className = 'CRM_Contact_Form_Edit_' . $name;
799 $className::buildQuickForm($this);
802 // build tags and groups
803 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
804 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
806 // build location blocks.
807 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
808 CRM_Contact_Form_Location
::buildQuickForm($this);
811 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
812 $this->addUploadElement('image_URL');
814 // add the dedupe button
815 $this->addElement('submit',
816 $this->_dedupeButtonName
,
817 ts('Check for Matching Contact(s)')
819 $this->addElement('submit',
820 $this->_duplicateButtonName
,
821 ts('Save Matching Contact')
823 $this->addElement('submit',
824 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
825 ts('Save With Duplicate Household')
831 'name' => ts('Save'),
837 'name' => ts('Save and New'),
838 'spacing' => ' ',
843 'name' => ts('Cancel'),
847 if (!empty($this->_values
['contact_sub_type'])) {
848 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
849 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
852 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
854 $this->addButtons($buttons);
858 * Form submission of new/edit contact is processed.
864 public function postProcess() {
865 // check if dedupe button, if so return.
866 $buttonName = $this->controller
->getButtonName();
867 if ($buttonName == $this->_dedupeButtonName
) {
871 //get the submitted values in an array
872 $params = $this->controller
->exportValues($this->_name
);
874 $group = CRM_Utils_Array
::value('group', $params);
875 if ($group && is_array($group)) {
876 unset($params['group']);
877 foreach ($group as $key => $value) {
878 $params['group'][$value] = 1;
882 CRM_Contact_BAO_Contact_Optimizer
::edit( $params, $this->_preEditValues
);
884 if (!empty($params['image_URL'])) {
885 CRM_Contact_BAO_Contact
::processImageParams($params);
888 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
889 $params['current_employer'] = $params['current_employer_id'];
892 // don't carry current_employer_id field,
893 // since we don't want to directly update DAO object without
894 // handling related business logic ( eg related membership )
895 if (isset($params['current_employer_id'])) {
896 unset($params['current_employer_id']);
899 $params['contact_type'] = $this->_contactType
;
900 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
901 $params['contact_sub_type'] = array($this->_contactSubType
);
904 if ($this->_contactId
) {
905 $params['contact_id'] = $this->_contactId
;
908 //make deceased date null when is_deceased = false
909 if ($this->_contactType
== 'Individual' && !empty($this->_editOptions
['Demographics']) && empty($params['is_deceased'])) {
910 $params['is_deceased'] = FALSE;
911 $params['deceased_date'] = NULL;
914 if (isset($params['contact_id'])) {
915 // process membership status for deceased contact
916 $deceasedParams = array('contact_id' => CRM_Utils_Array
::value('contact_id', $params),
917 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
918 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
920 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
923 // action is taken depending upon the mode
924 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
925 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
928 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
931 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
934 //if subtype is set, send subtype as extend to validate subtype customfield
935 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
937 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
943 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
944 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
945 $params['contact_type'],
947 $params['contact_sub_type']
951 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
952 // this is a chekbox, so mark false if we dont get a POST value
953 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
956 // process shared contact address.
957 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
959 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
960 unset($params['group']);
963 if (!empty($params['contact_id']) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
964 // figure out which all groups are intended to be removed
965 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
966 if (is_array($contactGroupList)) {
967 foreach ($contactGroupList as $key) {
968 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
969 $params['group'][$key['group_id']] = -1;
975 // parse street address, CRM-5450
976 $parseStatusMsg = NULL;
977 if ($this->_parseStreetAddress
) {
978 $parseResult = self
::parseAddress($params);
979 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
982 // Allow un-setting of location info, CRM-5969
983 $params['updateBlankLocInfo'] = TRUE;
985 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
988 if ($this->_contactId
) {
989 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
992 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
995 // set the contact ID
996 $this->_contactId
= $contact->id
;
998 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
999 //add contact to tags
1000 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1003 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1004 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1008 if (!empty($parseStatusMsg)) {
1009 $message .= "<br />$parseStatusMsg";
1011 if (!empty($updateMembershipMsg)) {
1012 $message .= "<br />$updateMembershipMsg";
1015 $session = CRM_Core_Session
::singleton();
1016 $session->setStatus($message, ts('Contact Saved'), 'success');
1018 // add the recently viewed contact
1019 $recentOther = array();
1020 if (($session->get('userID') == $contact->id
) ||
1021 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1023 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1026 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1027 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1030 CRM_Utils_Recent
::add($contact->display_name
,
1031 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1033 $this->_contactType
,
1035 $contact->display_name
,
1039 // here we replace the user context with the url to view this contact
1040 $buttonName = $this->controller
->getButtonName();
1041 if ($buttonName == $this->getButtonName('upload', 'new')) {
1042 $resetStr = "reset=1&ct={$contact->contact_type}";
1043 $resetStr .= $this->_contactSubType ?
"&cst={$this->_contactSubType}" : '';
1044 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1047 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1048 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1049 //validate the qfKey
1050 $urlParams = 'reset=1&cid=' . $contact->id
;
1052 $urlParams .= "&context=$context";
1054 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1055 $urlParams .= "&key=$qfKey";
1058 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1061 // now invoke the post hook
1062 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1063 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1066 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1071 * is there any real significant data in the hierarchical location array
1073 * @param array $fields the hierarchical value representation of this location
1075 * @return boolean true if data exists, false otherwise
1079 static function blockDataExists(&$fields) {
1080 if (!is_array($fields)) {
1084 static $skipFields = array('location_type_id', 'is_primary', 'phone_type_id', 'provider_id', 'country_id', 'website_type_id', 'master_id');
1085 foreach ($fields as $name => $value) {
1087 foreach ($skipFields as $skip) {
1088 if (strpos("[$skip]", $name) !== FALSE) {
1089 if ($name == 'phone') {
1099 if (is_array($value)) {
1100 if (self
::blockDataExists($value)) {
1105 if (!empty($value)) {
1115 * Function to that checks for duplicate contacts
1117 * @param array $fields fields array which are submitted
1118 * @param array $error error message array
1119 * @param int $contactID contact id
1120 * @param string $contactType contact type
1122 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1123 // if this is a forced save, ignore find duplicate rule
1124 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1126 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1127 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1130 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1132 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1133 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
1134 if ($contactLinks['msg'] == 'view') {
1135 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
1138 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts'));
1140 if ($contactLinks['msg'] == 'merge') {
1141 // We should also get a merge link if this is for an existing contact
1142 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1144 $duplicateContactsLinks .= '.';
1145 $duplicateContactsLinks .= '</div>';
1146 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1148 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1150 $row .= ' <td class="matching-contacts-name"> ';
1151 $row .= $contactLinks['rows'][$i]['display_name'];
1153 $row .= ' <td class="matching-contacts-email"> ';
1154 $row .= $contactLinks['rows'][$i]['primary_email'];
1156 $row .= ' <td class="action-items"> ';
1157 $row .= $contactLinks['rows'][$i]['view'];
1158 $row .= $contactLinks['rows'][$i]['edit'];
1159 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1164 $duplicateContactsLinks .= $row . '</table>';
1165 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1167 $errors['_qf_default'] = $duplicateContactsLinks;
1171 // let smarty know that there are duplicates
1172 $template = CRM_Core_Smarty
::singleton();
1173 $template->assign('isDuplicate', 1);
1175 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1176 // add a session message for no matching contacts
1177 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1182 function getTemplateFileName() {
1183 if ($this->_contactSubType
) {
1184 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1185 $template = CRM_Core_Form
::getTemplate();
1186 if ($template->template_exists($templateFile)) {
1187 return $templateFile;
1190 return parent
::getTemplateFileName();
1194 * Parse all address blocks present in given params
1195 * and return parse result for all address blocks,
1196 * This function either parse street address in to child
1197 * elements or build street address from child elements.
1199 * @params $params an array of key value consist of address blocks.
1201 * @return $parseSuccess as array of sucess/fails for each address block
1204 function parseAddress(&$params) {
1205 $parseSuccess = $parsedFields = array();
1206 if (!is_array($params['address']) ||
1207 CRM_Utils_System
::isNull($params['address'])
1209 return $parseSuccess;
1212 foreach ($params['address'] as $instance => & $address) {
1213 $buildStreetAddress = FALSE;
1214 $parseFieldName = 'street_address';
1216 'street_number', 'street_name', 'street_unit') as $fld) {
1217 if (!empty($address[$fld])) {
1218 $parseFieldName = 'street_number';
1219 $buildStreetAddress = TRUE;
1224 // main parse string.
1225 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1227 // parse address field.
1228 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1230 if ($buildStreetAddress) {
1231 //hack to ignore spaces between number and suffix.
1232 //here user gives input as street_number so it has to
1233 //be street_number and street_number_suffix, but
1234 //due to spaces though preg detect string as street_name
1235 //consider it as 'street_number_suffix'.
1236 $suffix = $parsedFields['street_number_suffix'];
1238 $suffix = $parsedFields['street_name'];
1240 $address['street_number_suffix'] = $suffix;
1241 $address['street_number'] = $parsedFields['street_number'];
1243 $streetAddress = NULL;
1245 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
1246 if (in_array($fld, array(
1247 'street_name', 'street_unit'))) {
1248 $streetAddress .= ' ';
1250 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1252 $address['street_address'] = trim($streetAddress);
1253 $parseSuccess[$instance] = TRUE;
1257 // consider address is automatically parseable,
1258 // when we should found street_number and street_name
1259 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
1263 // check for original street address string.
1264 if (empty($parseString)) {
1268 $parseSuccess[$instance] = $success;
1270 // we do not reset element values, but keep what we've parsed
1271 // in case of partial matches: CRM-8378
1273 // merge parse address in to main address block.
1274 $address = array_merge($address, $parsedFields);
1278 return $parseSuccess;
1282 * check parse result and if some address block fails then this
1283 * function return the status message for all address blocks.
1285 * @param $parseResult an array of address blk instance and its status.
1287 * @return $statusMsg string status message for all address blocks.
1290 static function parseAddressStatusMsg($parseResult) {
1292 if (!is_array($parseResult) ||
empty($parseResult)) {
1296 $parseFails = array();
1297 foreach ($parseResult as $instance => $success) {
1299 $parseFails[] = self
::ordinalNumber($instance);
1303 if (!empty($parseFails)) {
1304 $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.",
1305 array(1 => implode(', ', $parseFails))
1313 * Convert normal number to ordinal number format.
1314 * like 1 => 1st, 2 => 2nd and so on...
1316 * @param $number int number to convert in to ordinal number.
1318 * @return ordinal number for given number.
1321 static function ordinalNumber($number) {
1322 if (empty($number)) {
1327 switch (floor($number / 10) %
10) {
1330 switch ($number %
10) {
1345 return "$number$str";
1349 * Update membership status to deceased
1350 * function return the status message for updated membership.
1352 * @param $deceasedParams array having contact id and deceased value.
1354 * @return $updateMembershipMsg string status message for updated membership.
1356 function updateMembershipStatus($deceasedParams) {
1357 $updateMembershipMsg = NULL;
1358 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1359 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1361 // process to set membership status to deceased for both active/inactive membership
1363 $this->_contactType
== 'Individual' && !empty($deceasedParams['is_deceased'])) {
1365 $session = CRM_Core_Session
::singleton();
1366 $userId = $session->get('userID');
1368 $userId = $contactId;
1372 // get deceased status id
1373 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1374 $deceasedStatusId = array_search('Deceased', $allStatus);
1375 if (!$deceasedStatusId) {
1376 return $updateMembershipMsg;
1380 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1381 return $updateMembershipMsg;
1384 // get non deceased membership
1385 $dao = new CRM_Member_DAO_Membership();
1386 $dao->contact_id
= $contactId;
1387 $dao->whereAdd("status_id != $deceasedStatusId");
1389 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1390 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1392 while ($dao->fetch()) {
1393 // update status to deceased (for both active/inactive membership )
1394 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1395 'status_id', $deceasedStatusId
1398 // add membership log
1399 $membershipLog = array(
1400 'membership_id' => $dao->id
,
1401 'status_id' => $deceasedStatusId,
1402 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1403 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1404 'modified_id' => $userId,
1405 'modified_date' => date('Ymd'),
1406 'membership_type_id' => $dao->membership_type_id
,
1407 'max_related' => $dao->max_related
,
1411 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1413 //create activity when membership status is changed
1414 $activityParam = array(
1415 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1416 'source_contact_id' => $userId,
1417 'target_contact_id' => $dao->contact_id
,
1418 'source_record_id' => $dao->id
,
1419 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1423 'activity_date_time' => date('Y-m-d H:i:s'),
1425 'is_current_revision' => 1,
1428 $activityResult = civicrm_api('activity', 'create', $activityParam);
1435 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1436 array(1 => $memCount)
1441 return $updateMembershipMsg;