3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 (!CRM_Utils_Array
::value('id', $defaults)) {
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 ($session->get('userID') != $this->_contactId
&&
210 !CRM_Contact_BAO_Contact_Permission
::allow($this->_contactId
, CRM_Core_Permission
::EDIT
)
212 CRM_Core_Error
::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
215 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactId
);
216 $displayName = ts('Edit %1', array(1 => $displayName));
218 // Check if this is default domain contact CRM-10482
219 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
220 $displayName .= ' (' . ts('default organization') . ')';
223 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
224 CRM_Utils_System
::setTitle($displayName);
225 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
226 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
228 $urlParams = 'reset=1&cid=' . $this->_contactId
;
230 $urlParams .= "&context=$context";
233 if (CRM_Utils_Rule
::qfKey($qfKey)) {
235 $urlParams .= "&key=$qfKey";
238 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
240 $values = $this->get('values');
241 // get contact values.
242 if (!empty($values)) {
243 $this->_values
= $values;
247 'id' => $this->_contactId
,
248 'contact_id' => $this->_contactId
,
249 'noRelationships' => TRUE,
254 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
255 $this->set('values', $this->_values
);
259 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
263 // parse street address, CRM-5450
264 $this->_parseStreetAddress
= $this->get('parseStreetAddress');
265 if (!isset($this->_parseStreetAddress
)) {
266 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
269 $this->_parseStreetAddress
= FALSE;
270 if (CRM_Utils_Array
::value('street_address', $addressOptions) &&
271 CRM_Utils_Array
::value('street_address_parsing', $addressOptions)
273 $this->_parseStreetAddress
= TRUE;
275 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
277 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
279 $this->_editOptions
= $this->get('contactEditOptions');
280 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
281 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
282 'contact_edit_options', TRUE, NULL,
283 FALSE, 'name', TRUE, 'AND v.filter = 0'
285 $this->set('contactEditOptions', $this->_editOptions
);
288 // build demographics only for Individual contact type
289 if ($this->_contactType
!= 'Individual' &&
290 array_key_exists('Demographics', $this->_editOptions
)
292 unset($this->_editOptions
['Demographics']);
295 // in update mode don't show notes
296 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
297 unset($this->_editOptions
['Notes']);
300 $this->assign('editOptions', $this->_editOptions
);
301 $this->assign('contactType', $this->_contactType
);
302 $this->assign('contactSubType', $this->_contactSubType
);
304 //build contact subtype form element, CRM-6864
305 $buildContactSubType = TRUE;
306 if ($this->_contactSubType
&& ($this->_action
& CRM_Core_Action
::ADD
)) {
307 $buildContactSubType = FALSE;
309 $this->assign('buildContactSubType', $buildContactSubType);
311 // get the location blocks.
312 $this->_blocks
= $this->get('blocks');
313 if (CRM_Utils_System
::isNull($this->_blocks
)) {
314 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
315 'contact_edit_options', TRUE, NULL,
316 FALSE, 'name', TRUE, 'AND v.filter = 1'
318 $this->set('blocks', $this->_blocks
);
320 $this->assign('blocks', $this->_blocks
);
322 // this is needed for custom data.
323 $this->assign('entityID', $this->_contactId
);
325 // also keep the convention.
326 $this->assign('contactId', $this->_contactId
);
329 CRM_Contact_Form_Location
::preProcess($this);
331 // retain the multiple count custom fields value
332 if(CRM_Utils_Array
::value('hidden_custom', $_POST)) {
333 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
335 if ($contactSubType = CRM_Utils_Array
::value( 'contact_sub_type', $_POST)) {
336 $paramSubType = implode(',', $contactSubType);
339 $this->_getCachedTree
= FALSE;
340 unset($customGroupCount[0]);
341 foreach ($customGroupCount as $groupID => $groupCount) {
342 if ($groupCount > 1) {
343 $this->set('groupID', $groupID);
345 for ($i = 0; $i <= $groupCount; $i++
) {
346 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
347 $i, $this->_contactType
349 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
354 //reset all the ajax stuff, for normal processing
355 if (isset($this->_groupTree
)) {
356 $this->_groupTree
= NULL;
358 $this->set('groupID', NULL);
359 $this->_getCachedTree
= TRUE;
362 // execute preProcess dynamically by js else execute normal preProcess
363 if (array_key_exists('CustomData', $this->_editOptions
)) {
364 //assign a parameter to pass for sub type multivalue
365 //custom field to load
366 if ($this->_contactSubType ||
isset($paramSubType)) {
367 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
368 str_replace( CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
370 $this->assign('paramSubType', $paramSubType);
373 if (CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject)) {
374 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
377 $contactSubType = $this->_contactSubType
;
378 // need contact sub type to build related grouptree array during post process
379 if (CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
380 $contactSubType = $_POST['contact_sub_type'];
382 //only custom data has preprocess hence directly call it
383 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
384 1, $this->_contactType
, $this->_contactId
386 $this->assign('customValueCount', $this->_customValueCount
);
392 * This function sets the default values for the form. Note that in edit/view mode
393 * the default values are retrieved from the database
399 function setDefaultValues() {
400 $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 $currentEmployer = CRM_Contact_BAO_Relationship
::getCurrentEmployer(array($this->_contactId
));
419 $defaults['current_employer_id'] = CRM_Utils_Array
::value('org_id', $currentEmployer[$this->_contactId
]);
421 foreach ($defaults['email'] as $dontCare => & $val) {
422 if (isset($val['signature_text'])) {
423 $val['signature_text_hidden'] = $val['signature_text'];
425 if (isset($val['signature_html'])) {
426 $val['signature_html_hidden'] = $val['signature_html'];
430 if (CRM_Utils_Array
::value('contact_sub_type', $defaults)) {
431 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
434 $this->assign('currentEmployer', CRM_Utils_Array
::value('current_employer_id', $defaults));
436 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
437 foreach ($this->_editOptions
as $name => $label) {
438 if (!in_array($name, array('Address', 'Notes'))) {
439 $className = 'CRM_Contact_Form_Edit_' . $name;
440 $className::setDefaultValues($this, $defaults);
444 //set address block defaults
445 CRM_Contact_Form_Edit_Address
::setDefaultValues( $defaults, $this );
447 if (CRM_Utils_Array
::value('image_URL', $defaults)) {
448 list($imageWidth, $imageHeight) = getimagesize($defaults['image_URL']);
449 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
450 $this->assign('imageWidth', $imageWidth);
451 $this->assign('imageHeight', $imageHeight);
452 $this->assign('imageThumbWidth', $imageThumbWidth);
453 $this->assign('imageThumbHeight', $imageThumbHeight);
454 $this->assign('imageURL', $defaults['image_URL']);
457 //set location type and country to default for each block
458 $this->blockSetDefaults($defaults);
460 $this->_preEditValues
= $defaults;
465 * do the set default related to location type id,
466 * primary location, default country
469 function blockSetDefaults(&$defaults) {
470 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
471 sort($locationTypeKeys);
473 // get the default location type
474 $locationType = CRM_Core_BAO_LocationType
::getDefault();
476 // unset primary location type
477 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
478 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
480 // reset the array sequence
481 $locationTypeKeys = array_values($locationTypeKeys);
483 // get default phone and im provider id.
484 $defPhoneTypeId = key(CRM_Core_OptionGroup
::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
485 $defIMProviderId = key(CRM_Core_OptionGroup
::values('instant_messenger_service',
486 FALSE, FALSE, FALSE, ' AND is_default = 1'
489 $allBlocks = $this->_blocks
;
490 if (array_key_exists('Address', $this->_editOptions
)) {
491 $allBlocks['Address'] = $this->_editOptions
['Address'];
494 $config = CRM_Core_Config
::singleton();
495 foreach ($allBlocks as $blockName => $label) {
496 $name = strtolower($blockName);
497 $hasPrimary = $updateMode = FALSE;
499 // user is in update mode.
500 if (array_key_exists($name, $defaults) &&
501 !CRM_Utils_System
::isNull($defaults[$name])
506 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
507 // make we require one primary block, CRM-5505
511 CRM_Utils_Array
::value(
513 CRM_Utils_Array
::value($instance, $defaults[$name])
519 //set location to primary for first one.
520 if ($instance == 1) {
522 $defaults[$name][$instance]['is_primary'] = TRUE;
523 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
526 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
527 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
530 //set default country
531 if ($name == 'address' && $config->defaultContactCountry
) {
532 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
535 //set default state/province
536 if ($name == 'address' && $config->defaultContactStateProvince
) {
537 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
540 //set default phone type.
541 if ($name == 'phone' && $defPhoneTypeId) {
542 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
545 //set default im provider.
546 if ($name == 'im' && $defIMProviderId) {
547 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
552 $defaults[$name][1]['is_primary'] = TRUE;
556 // set defaults for country-state widget
557 if (CRM_Utils_Array
::value('address', $defaults) && is_array($defaults['address'])) {
558 foreach ($defaults['address'] as $blockId => $values) {
559 CRM_Contact_Form_Edit_Address
::fixStateSelect($this,
560 "address[$blockId][country_id]",
561 "address[$blockId][state_province_id]",
562 "address[$blockId][county_id]",
563 CRM_Utils_Array
::value('country_id',
564 $values, $config->defaultContactCountry
566 CRM_Utils_Array
::value('state_province_id',
567 $values, $config->defaultContactStateProvince
575 * This function is used to add the rules (mainly global rules) for form.
576 * All local rules are added near the element
582 function addRules() {
583 // skip adding formRules when custom data is build
584 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
588 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
590 // Call Locking check if editing existing contact
591 if ($this->_contactId
) {
592 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
595 if (array_key_exists('Address', $this->_editOptions
)) {
596 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'));
599 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
600 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
605 * global validation rules for the form
607 * @param array $fields posted values of the form
608 * @param array $errors list of errors to be posted back to the form
609 * @param int $contactId contact id if doing update.
611 * @return $primaryID email/openId
615 static function formRule($fields, &$errors, $contactId = NULL) {
616 $config = CRM_Core_Config
::singleton();
619 //1. for each block only single value can be marked as is_primary = true.
620 //2. location type id should be present if block data present.
621 //3. check open id across db and other each block for duplicate.
622 //4. at least one location should be primary.
623 //5. also get primaryID from email or open id block.
625 // take the location blocks.
626 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
627 'contact_edit_options', TRUE, NULL,
628 FALSE, 'name', TRUE, 'AND v.filter = 1'
631 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
632 'contact_edit_options', TRUE, NULL,
633 FALSE, 'name', TRUE, 'AND v.filter = 0'
635 //get address block inside.
636 if (array_key_exists('Address', $otherEditOptions)) {
637 $blocks['Address'] = $otherEditOptions['Address'];
642 foreach ($blocks as $name => $label) {
643 $hasData = $hasPrimary = array();
644 $name = strtolower($name);
645 if (CRM_Utils_Array
::value($name, $fields) && is_array($fields[$name])) {
646 foreach ($fields[$name] as $instance => $blockValues) {
647 $dataExists = self
::blockDataExists($blockValues);
649 if (!$dataExists && $name == 'address') {
650 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
654 // skip remaining checks for website
655 if ($name == 'website') {
659 $hasData[] = $instance;
660 if (CRM_Utils_Array
::value('is_primary', $blockValues)) {
661 $hasPrimary[] = $instance;
663 in_array($name, array(
664 'email', 'openid')) &&
665 CRM_Utils_Array
::value($name, $blockValues)
667 $primaryID = $blockValues[$name];
671 if (!CRM_Utils_Array
::value('location_type_id', $blockValues)) {
672 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
676 if ($name == 'openid' && CRM_Utils_Array
::value($name, $blockValues)) {
677 $oid = new CRM_Core_DAO_OpenID();
678 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
679 $cid = isset($contactId) ?
$contactId : 0;
680 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
681 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
686 if (empty($hasPrimary) && !empty($hasData)) {
687 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
690 if (count($hasPrimary) > 1) {
691 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
698 //do validations for all opend ids they should be distinct.
699 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
700 foreach ($openIds as $instance => $value) {
701 if (!array_key_exists($instance, array_unique($openIds))) {
702 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
707 // street number should be digit + suffix, CRM-5450
708 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
709 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
713 if ($parseStreetAddress) {
714 if (isset($fields['address']) &&
715 is_array($fields['address'])
717 $invalidStreetNumbers = array();
718 foreach ($fields['address'] as $cnt => $address) {
719 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
720 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
721 if (!CRM_Utils_Array
::value('street_number', $parsedAddress)) {
722 $invalidStreetNumbers[] = $cnt;
727 if (!empty($invalidStreetNumbers)) {
728 $first = $invalidStreetNumbers[0];
729 foreach ($invalidStreetNumbers as & $num) $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
730 $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)));
739 * Function to actually build the form
744 public function buildQuickForm() {
745 //load form for child blocks
746 if ($this->_addBlockName
) {
747 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
748 return $className::buildQuickForm($this);
751 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
752 $deleteExtra = ts('Are you sure you want to delete contact image.');
754 CRM_Core_Action
::DELETE
=>
756 'name' => ts('Delete Contact Image'),
757 'url' => 'civicrm/contact/image',
758 'qs' => 'reset=1&cid=%%id%%&action=delete',
760 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
763 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
764 CRM_Core_Action
::DELETE
,
766 'id' => $this->_contactId
,
769 $this->assign('deleteURL', $deleteURL);
772 //build contact type specific fields
773 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
774 $className::buildQuickForm($this);
776 // build Custom data if Custom data present in edit option
777 $buildCustomData = 'noCustomDataPresent';
778 if (array_key_exists('CustomData', $this->_editOptions
)) {
779 $buildCustomData = "customDataPresent";
782 // subtype is a common field. lets keep it here
783 $subtypes = CRM_Contact_BAO_ContactType
::subTypePairs($this->_contactType
);
784 if (!empty($subtypes)) {
785 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
788 'id' => 'contact_sub_type',
789 'multiple' => 'multiple',
790 'title' => '- ' . ts('select') . ' -',
791 'class' => $buildCustomData,
796 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
797 foreach ($this->_editOptions
as $name => $label) {
798 if ($name == 'Address') {
799 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
802 if ($name == 'TagsAndGroups') {
805 $className = 'CRM_Contact_Form_Edit_' . $name;
806 $className::buildQuickForm($this);
809 // build tags and groups
810 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
811 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'crmasmSelect');
813 // build location blocks.
814 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
815 CRM_Contact_Form_Location
::buildQuickForm($this);
818 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
819 $this->addUploadElement('image_URL');
821 // add the dedupe button
822 $this->addElement('submit',
823 $this->_dedupeButtonName
,
824 ts('Check for Matching Contact(s)')
826 $this->addElement('submit',
827 $this->_duplicateButtonName
,
828 ts('Save Matching Contact')
830 $this->addElement('submit',
831 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
832 ts('Save With Duplicate Household')
838 'name' => ts('Save'),
844 'name' => ts('Save and New'),
845 'spacing' => ' ',
850 'name' => ts('Cancel'),
854 if (CRM_Utils_Array
::value('contact_sub_type', $this->_values
)) {
855 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
856 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
859 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
861 $this->addButtons($buttons);
865 * Form submission of new/edit contact is processed.
871 public function postProcess() {
872 // check if dedupe button, if so return.
873 $buttonName = $this->controller
->getButtonName();
874 if ($buttonName == $this->_dedupeButtonName
) {
878 //get the submitted values in an array
879 $params = $this->controller
->exportValues($this->_name
);
881 $group = CRM_Utils_Array
::value('group', $params);
882 if ($group && is_array($group)) {
883 unset($params['group']);
884 foreach ($group as $key => $value) {
885 $params['group'][$value] = 1;
889 CRM_Contact_BAO_Contact_Optimizer
::edit( $params, $this->_preEditValues
);
891 if (CRM_Utils_Array
::value('image_URL', $params)) {
892 CRM_Contact_BAO_Contact
::processImageParams($params);
895 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params))
896 && CRM_Utils_Array
::value('current_employer', $params)
898 $params['current_employer'] = $params['current_employer_id'];
901 // don't carry current_employer_id field,
902 // since we don't want to directly update DAO object without
903 // handling related business logic ( eg related membership )
904 if (isset($params['current_employer_id'])) {
905 unset($params['current_employer_id']);
908 $params['contact_type'] = $this->_contactType
;
909 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
910 $params['contact_sub_type'] = array($this->_contactSubType
);
913 if ($this->_contactId
) {
914 $params['contact_id'] = $this->_contactId
;
917 //make deceased date null when is_deceased = false
918 if ($this->_contactType
== 'Individual' &&
919 CRM_Utils_Array
::value('Demographics', $this->_editOptions
) &&
920 !CRM_Utils_Array
::value('is_deceased', $params)
922 $params['is_deceased'] = FALSE;
923 $params['deceased_date'] = NULL;
926 if (isset($params['contact_id'])) {
927 // process membership status for deceased contact
928 $deceasedParams = array('contact_id' => CRM_Utils_Array
::value('contact_id', $params),
929 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
930 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
932 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
935 // action is taken depending upon the mode
936 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
937 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
940 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
943 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
946 //if subtype is set, send subtype as extend to validate subtype customfield
947 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
949 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
955 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
956 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
957 $params['contact_type'],
959 $params['contact_sub_type']
963 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
964 // this is a chekbox, so mark false if we dont get a POST value
965 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
968 // process shared contact address.
969 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
971 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
972 unset($params['group']);
975 if (CRM_Utils_Array
::value('contact_id', $params) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
976 // figure out which all groups are intended to be removed
977 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
978 if (is_array($contactGroupList)) {
979 foreach ($contactGroupList as $key) {
980 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1)
981 && !CRM_Utils_Array
::value('is_hidden', $key)
983 $params['group'][$key['group_id']] = -1;
989 // parse street address, CRM-5450
990 $parseStatusMsg = NULL;
991 if ($this->_parseStreetAddress
) {
992 $parseResult = self
::parseAddress($params);
993 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
996 // Allow un-setting of location info, CRM-5969
997 $params['updateBlankLocInfo'] = TRUE;
999 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
1002 if ($this->_contactId
) {
1003 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
1006 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
1009 // set the contact ID
1010 $this->_contactId
= $contact->id
;
1012 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
1013 //add contact to tags
1014 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1017 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1018 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1022 if (!empty($parseStatusMsg)) {
1023 $message .= "<br />$parseStatusMsg";
1025 if (!empty($updateMembershipMsg)) {
1026 $message .= "<br />$updateMembershipMsg";
1029 $session = CRM_Core_Session
::singleton();
1030 $session->setStatus($message, ts('Contact Saved'), 'success');
1032 // add the recently viewed contact
1033 $recentOther = array();
1034 if (($session->get('userID') == $contact->id
) ||
1035 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1037 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1040 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1041 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1044 CRM_Utils_Recent
::add($contact->display_name
,
1045 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1047 $this->_contactType
,
1049 $contact->display_name
,
1053 // here we replace the user context with the url to view this contact
1054 $buttonName = $this->controller
->getButtonName();
1055 if ($buttonName == $this->getButtonName('upload', 'new')) {
1056 $resetStr = "reset=1&ct={$contact->contact_type}";
1057 $resetStr .= $this->_contactSubType ?
"&cst={$this->_contactSubType}" : '';
1058 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1061 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1062 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1063 //validate the qfKey
1064 $urlParams = 'reset=1&cid=' . $contact->id
;
1066 $urlParams .= "&context=$context";
1068 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1069 $urlParams .= "&key=$qfKey";
1072 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1075 // now invoke the post hook
1076 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1077 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1080 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1085 * is there any real significant data in the hierarchical location array
1087 * @param array $fields the hierarchical value representation of this location
1089 * @return boolean true if data exists, false otherwise
1093 static function blockDataExists(&$fields) {
1094 if (!is_array($fields)) {
1098 static $skipFields = array('location_type_id', 'is_primary', 'phone_type_id', 'provider_id', 'country_id', 'website_type_id', 'master_id');
1099 foreach ($fields as $name => $value) {
1101 foreach ($skipFields as $skip) {
1102 if (strpos("[$skip]", $name) !== FALSE) {
1103 if ($name == 'phone') {
1113 if (is_array($value)) {
1114 if (self
::blockDataExists($value)) {
1119 if (!empty($value)) {
1129 * Function to that checks for duplicate contacts
1131 * @param array $fields fields array which are submitted
1132 * @param array $error error message array
1133 * @param int $contactID contact id
1134 * @param string $contactType contact type
1136 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1137 // if this is a forced save, ignore find duplicate rule
1138 if (!CRM_Utils_Array
::value('_qf_Contact_upload_duplicate', $fields)) {
1140 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1141 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1144 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1146 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1147 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
1148 if ($contactLinks['msg'] == 'view') {
1149 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
1152 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), '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;
1185 // let smarty know that there are duplicates
1186 $template = CRM_Core_Smarty
::singleton();
1187 $template->assign('isDuplicate', 1);
1189 elseif (CRM_Utils_Array
::value('_qf_Contact_refresh_dedupe', $fields)) {
1190 // add a session message for no matching contacts
1191 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1196 function getTemplateFileName() {
1197 if ($this->_contactSubType
) {
1198 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1199 $template = CRM_Core_Form
::getTemplate();
1200 if ($template->template_exists($templateFile)) {
1201 return $templateFile;
1204 return parent
::getTemplateFileName();
1208 * Parse all address blocks present in given params
1209 * and return parse result for all address blocks,
1210 * This function either parse street address in to child
1211 * elements or build street address from child elements.
1213 * @params $params an array of key value consist of address blocks.
1215 * @return $parseSuccess as array of sucess/fails for each address block
1218 function parseAddress(&$params) {
1219 $parseSuccess = $parsedFields = array();
1220 if (!is_array($params['address']) ||
1221 CRM_Utils_System
::isNull($params['address'])
1223 return $parseSuccess;
1226 foreach ($params['address'] as $instance => & $address) {
1227 $buildStreetAddress = FALSE;
1228 $parseFieldName = 'street_address';
1230 'street_number', 'street_name', 'street_unit') as $fld) {
1231 if (CRM_Utils_Array
::value($fld, $address)) {
1232 $parseFieldName = 'street_number';
1233 $buildStreetAddress = TRUE;
1238 // main parse string.
1239 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1241 // parse address field.
1242 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1244 if ($buildStreetAddress) {
1245 //hack to ignore spaces between number and suffix.
1246 //here user gives input as street_number so it has to
1247 //be street_number and street_number_suffix, but
1248 //due to spaces though preg detect string as street_name
1249 //consider it as 'street_number_suffix'.
1250 $suffix = $parsedFields['street_number_suffix'];
1252 $suffix = $parsedFields['street_name'];
1254 $address['street_number_suffix'] = $suffix;
1255 $address['street_number'] = $parsedFields['street_number'];
1257 $streetAddress = NULL;
1259 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
1260 if (in_array($fld, array(
1261 'street_name', 'street_unit'))) {
1262 $streetAddress .= ' ';
1264 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1266 $address['street_address'] = trim($streetAddress);
1267 $parseSuccess[$instance] = TRUE;
1271 // consider address is automatically parseable,
1272 // when we should found street_number and street_name
1273 if (!CRM_Utils_Array
::value('street_name', $parsedFields) ||
1274 !CRM_Utils_Array
::value('street_number', $parsedFields)
1279 // check for original street address string.
1280 if (empty($parseString)) {
1284 $parseSuccess[$instance] = $success;
1286 // we do not reset element values, but keep what we've parsed
1287 // in case of partial matches: CRM-8378
1289 // merge parse address in to main address block.
1290 $address = array_merge($address, $parsedFields);
1294 return $parseSuccess;
1298 * check parse result and if some address block fails then this
1299 * function return the status message for all address blocks.
1301 * @param $parseResult an array of address blk instance and its status.
1303 * @return $statusMsg string status message for all address blocks.
1306 static function parseAddressStatusMsg($parseResult) {
1308 if (!is_array($parseResult) ||
empty($parseResult)) {
1312 $parseFails = array();
1313 foreach ($parseResult as $instance => $success) {
1315 $parseFails[] = self
::ordinalNumber($instance);
1319 if (!empty($parseFails)) {
1320 $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.",
1321 array(1 => implode(', ', $parseFails))
1329 * Convert normal number to ordinal number format.
1330 * like 1 => 1st, 2 => 2nd and so on...
1332 * @param $number int number to convert in to ordinal number.
1334 * @return ordinal number for given number.
1337 static function ordinalNumber($number) {
1338 if (empty($number)) {
1343 switch (floor($number / 10) %
10) {
1346 switch ($number %
10) {
1361 return "$number$str";
1365 * Update membership status to deceased
1366 * function return the status message for updated membership.
1368 * @param $deceasedParams array having contact id and deceased value.
1370 * @return $updateMembershipMsg string status message for updated membership.
1372 function updateMembershipStatus($deceasedParams) {
1373 $updateMembershipMsg = NULL;
1374 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1375 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1377 // process to set membership status to deceased for both active/inactive membership
1379 $this->_contactType
== 'Individual' &&
1380 CRM_Utils_Array
::value('is_deceased', $deceasedParams)
1383 $session = CRM_Core_Session
::singleton();
1384 $userId = $session->get('userID');
1386 $userId = $contactId;
1390 // get deceased status id
1391 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1392 $deceasedStatusId = array_search('Deceased', $allStatus);
1393 if (!$deceasedStatusId) {
1394 return $updateMembershipMsg;
1398 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1399 return $updateMembershipMsg;
1402 // get non deceased membership
1403 $dao = new CRM_Member_DAO_Membership();
1404 $dao->contact_id
= $contactId;
1405 $dao->whereAdd("status_id != $deceasedStatusId");
1407 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1408 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1410 while ($dao->fetch()) {
1411 // update status to deceased (for both active/inactive membership )
1412 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1413 'status_id', $deceasedStatusId
1416 // add membership log
1417 $membershipLog = array(
1418 'membership_id' => $dao->id
,
1419 'status_id' => $deceasedStatusId,
1420 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1421 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1422 'modified_id' => $userId,
1423 'modified_date' => date('Ymd'),
1424 'membership_type_id' => $dao->membership_type_id
,
1425 'max_related' => $dao->max_related
,
1429 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1431 //create activity when membership status is changed
1432 $activityParam = array(
1433 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1434 'source_contact_id' => $userId,
1435 'target_contact_id' => $dao->contact_id
,
1436 'source_record_id' => $dao->id
,
1437 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1441 'activity_date_time' => date('Y-m-d H:i:s'),
1443 'is_current_revision' => 1,
1446 $activityResult = civicrm_api('activity', 'create', $activityParam);
1453 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1454 array(1 => $memCount)
1459 return $updateMembershipMsg;