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 (!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 (!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 (CRM_Utils_Array
::value('street_address', $addressOptions) &&
269 CRM_Utils_Array
::value('street_address_parsing', $addressOptions)
271 $this->_parseStreetAddress
= TRUE;
273 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
275 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
277 $this->_editOptions
= $this->get('contactEditOptions');
278 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
279 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
280 'contact_edit_options', TRUE, NULL,
281 FALSE, 'name', TRUE, 'AND v.filter = 0'
283 $this->set('contactEditOptions', $this->_editOptions
);
286 // build demographics only for Individual contact type
287 if ($this->_contactType
!= 'Individual' &&
288 array_key_exists('Demographics', $this->_editOptions
)
290 unset($this->_editOptions
['Demographics']);
293 // in update mode don't show notes
294 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
295 unset($this->_editOptions
['Notes']);
298 $this->assign('editOptions', $this->_editOptions
);
299 $this->assign('contactType', $this->_contactType
);
300 $this->assign('contactSubType', $this->_contactSubType
);
302 //build contact subtype form element, CRM-6864
303 $buildContactSubType = TRUE;
304 if ($this->_contactSubType
&& ($this->_action
& CRM_Core_Action
::ADD
)) {
305 $buildContactSubType = FALSE;
307 $this->assign('buildContactSubType', $buildContactSubType);
309 // get the location blocks.
310 $this->_blocks
= $this->get('blocks');
311 if (CRM_Utils_System
::isNull($this->_blocks
)) {
312 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
313 'contact_edit_options', TRUE, NULL,
314 FALSE, 'name', TRUE, 'AND v.filter = 1'
316 $this->set('blocks', $this->_blocks
);
318 $this->assign('blocks', $this->_blocks
);
320 // this is needed for custom data.
321 $this->assign('entityID', $this->_contactId
);
323 // also keep the convention.
324 $this->assign('contactId', $this->_contactId
);
327 CRM_Contact_Form_Location
::preProcess($this);
329 // retain the multiple count custom fields value
330 if(CRM_Utils_Array
::value('hidden_custom', $_POST)) {
331 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
333 if ($contactSubType = CRM_Utils_Array
::value( 'contact_sub_type', $_POST)) {
334 $paramSubType = implode(',', $contactSubType);
337 $this->_getCachedTree
= FALSE;
338 unset($customGroupCount[0]);
339 foreach ($customGroupCount as $groupID => $groupCount) {
340 if ($groupCount > 1) {
341 $this->set('groupID', $groupID);
343 for ($i = 0; $i <= $groupCount; $i++
) {
344 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
345 $i, $this->_contactType
347 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
352 //reset all the ajax stuff, for normal processing
353 if (isset($this->_groupTree
)) {
354 $this->_groupTree
= NULL;
356 $this->set('groupID', NULL);
357 $this->_getCachedTree
= TRUE;
360 // execute preProcess dynamically by js else execute normal preProcess
361 if (array_key_exists('CustomData', $this->_editOptions
)) {
362 //assign a parameter to pass for sub type multivalue
363 //custom field to load
364 if ($this->_contactSubType ||
isset($paramSubType)) {
365 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
366 str_replace( CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
368 $this->assign('paramSubType', $paramSubType);
371 if (CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject)) {
372 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
375 $contactSubType = $this->_contactSubType
;
376 // need contact sub type to build related grouptree array during post process
377 if (CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
378 $contactSubType = $_POST['contact_sub_type'];
380 //only custom data has preprocess hence directly call it
381 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
382 1, $this->_contactType
, $this->_contactId
384 $this->assign('customValueCount', $this->_customValueCount
);
390 * This function sets the default values for the form. Note that in edit/view mode
391 * the default values are retrieved from the database
397 function setDefaultValues() {
398 $defaults = $this->_values
;
401 if ($this->_action
& CRM_Core_Action
::ADD
) {
402 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
403 // set group and tag defaults if any
405 $defaults['group'][] = $this->_gid
;
408 $defaults['tag'][$this->_tid
] = 1;
411 if ($this->_contactSubType
) {
412 $defaults['contact_sub_type'] = $this->_contactSubType
;
416 $currentEmployer = CRM_Contact_BAO_Relationship
::getCurrentEmployer(array($this->_contactId
));
417 $defaults['current_employer_id'] = CRM_Utils_Array
::value('org_id', $currentEmployer[$this->_contactId
]);
419 foreach ($defaults['email'] as $dontCare => & $val) {
420 if (isset($val['signature_text'])) {
421 $val['signature_text_hidden'] = $val['signature_text'];
423 if (isset($val['signature_html'])) {
424 $val['signature_html_hidden'] = $val['signature_html'];
428 if (CRM_Utils_Array
::value('contact_sub_type', $defaults)) {
429 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
432 $this->assign('currentEmployer', CRM_Utils_Array
::value('current_employer_id', $defaults));
434 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
435 foreach ($this->_editOptions
as $name => $label) {
436 if (!in_array($name, array('Address', 'Notes'))) {
437 $className = 'CRM_Contact_Form_Edit_' . $name;
438 $className::setDefaultValues($this, $defaults);
442 //set address block defaults
443 CRM_Contact_Form_Edit_Address
::setDefaultValues( $defaults, $this );
445 if (CRM_Utils_Array
::value('image_URL', $defaults)) {
446 list($imageWidth, $imageHeight) = getimagesize($defaults['image_URL']);
447 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
448 $this->assign('imageWidth', $imageWidth);
449 $this->assign('imageHeight', $imageHeight);
450 $this->assign('imageThumbWidth', $imageThumbWidth);
451 $this->assign('imageThumbHeight', $imageThumbHeight);
452 $this->assign('imageURL', $defaults['image_URL']);
455 //set location type and country to default for each block
456 $this->blockSetDefaults($defaults);
458 $this->_preEditValues
= $defaults;
463 * do the set default related to location type id,
464 * primary location, default country
467 function blockSetDefaults(&$defaults) {
468 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
469 sort($locationTypeKeys);
471 // get the default location type
472 $locationType = CRM_Core_BAO_LocationType
::getDefault();
474 // unset primary location type
475 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
476 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
478 // reset the array sequence
479 $locationTypeKeys = array_values($locationTypeKeys);
481 // get default phone and im provider id.
482 $defPhoneTypeId = key(CRM_Core_OptionGroup
::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
483 $defIMProviderId = key(CRM_Core_OptionGroup
::values('instant_messenger_service',
484 FALSE, FALSE, FALSE, ' AND is_default = 1'
487 $allBlocks = $this->_blocks
;
488 if (array_key_exists('Address', $this->_editOptions
)) {
489 $allBlocks['Address'] = $this->_editOptions
['Address'];
492 $config = CRM_Core_Config
::singleton();
493 foreach ($allBlocks as $blockName => $label) {
494 $name = strtolower($blockName);
495 $hasPrimary = $updateMode = FALSE;
497 // user is in update mode.
498 if (array_key_exists($name, $defaults) &&
499 !CRM_Utils_System
::isNull($defaults[$name])
504 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
505 // make we require one primary block, CRM-5505
509 CRM_Utils_Array
::value(
511 CRM_Utils_Array
::value($instance, $defaults[$name])
517 //set location to primary for first one.
518 if ($instance == 1) {
520 $defaults[$name][$instance]['is_primary'] = TRUE;
521 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
524 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
525 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
528 //set default country
529 if ($name == 'address' && $config->defaultContactCountry
) {
530 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
533 //set default state/province
534 if ($name == 'address' && $config->defaultContactStateProvince
) {
535 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
538 //set default phone type.
539 if ($name == 'phone' && $defPhoneTypeId) {
540 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
543 //set default im provider.
544 if ($name == 'im' && $defIMProviderId) {
545 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
550 $defaults[$name][1]['is_primary'] = TRUE;
554 // set defaults for country-state widget
555 if (CRM_Utils_Array
::value('address', $defaults) && is_array($defaults['address'])) {
556 foreach ($defaults['address'] as $blockId => $values) {
557 CRM_Contact_Form_Edit_Address
::fixStateSelect($this,
558 "address[$blockId][country_id]",
559 "address[$blockId][state_province_id]",
560 "address[$blockId][county_id]",
561 CRM_Utils_Array
::value('country_id',
562 $values, $config->defaultContactCountry
564 CRM_Utils_Array
::value('state_province_id',
565 $values, $config->defaultContactStateProvince
573 * This function is used to add the rules (mainly global rules) for form.
574 * All local rules are added near the element
580 function addRules() {
581 // skip adding formRules when custom data is build
582 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
586 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
588 // Call Locking check if editing existing contact
589 if ($this->_contactId
) {
590 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
593 if (array_key_exists('Address', $this->_editOptions
)) {
594 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
597 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
598 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
603 * global validation rules for the form
605 * @param array $fields posted values of the form
606 * @param array $errors list of errors to be posted back to the form
607 * @param int $contactId contact id if doing update.
609 * @return $primaryID email/openId
613 static function formRule($fields, &$errors, $contactId = NULL) {
614 $config = CRM_Core_Config
::singleton();
617 //1. for each block only single value can be marked as is_primary = true.
618 //2. location type id should be present if block data present.
619 //3. check open id across db and other each block for duplicate.
620 //4. at least one location should be primary.
621 //5. also get primaryID from email or open id block.
623 // take the location blocks.
624 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
625 'contact_edit_options', TRUE, NULL,
626 FALSE, 'name', TRUE, 'AND v.filter = 1'
629 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
630 'contact_edit_options', TRUE, NULL,
631 FALSE, 'name', TRUE, 'AND v.filter = 0'
633 //get address block inside.
634 if (array_key_exists('Address', $otherEditOptions)) {
635 $blocks['Address'] = $otherEditOptions['Address'];
640 foreach ($blocks as $name => $label) {
641 $hasData = $hasPrimary = array();
642 $name = strtolower($name);
643 if (CRM_Utils_Array
::value($name, $fields) && is_array($fields[$name])) {
644 foreach ($fields[$name] as $instance => $blockValues) {
645 $dataExists = self
::blockDataExists($blockValues);
647 if (!$dataExists && $name == 'address') {
648 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
652 // skip remaining checks for website
653 if ($name == 'website') {
657 $hasData[] = $instance;
658 if (CRM_Utils_Array
::value('is_primary', $blockValues)) {
659 $hasPrimary[] = $instance;
661 in_array($name, array(
662 'email', 'openid')) &&
663 CRM_Utils_Array
::value($name, $blockValues)
665 $primaryID = $blockValues[$name];
669 if (!CRM_Utils_Array
::value('location_type_id', $blockValues)) {
670 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
674 if ($name == 'openid' && CRM_Utils_Array
::value($name, $blockValues)) {
675 $oid = new CRM_Core_DAO_OpenID();
676 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
677 $cid = isset($contactId) ?
$contactId : 0;
678 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
679 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
684 if (empty($hasPrimary) && !empty($hasData)) {
685 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
688 if (count($hasPrimary) > 1) {
689 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
696 //do validations for all opend ids they should be distinct.
697 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
698 foreach ($openIds as $instance => $value) {
699 if (!array_key_exists($instance, array_unique($openIds))) {
700 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
705 // street number should be digit + suffix, CRM-5450
706 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
707 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
711 if ($parseStreetAddress) {
712 if (isset($fields['address']) &&
713 is_array($fields['address'])
715 $invalidStreetNumbers = array();
716 foreach ($fields['address'] as $cnt => $address) {
717 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
718 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
719 if (!CRM_Utils_Array
::value('street_number', $parsedAddress)) {
720 $invalidStreetNumbers[] = $cnt;
725 if (!empty($invalidStreetNumbers)) {
726 $first = $invalidStreetNumbers[0];
727 foreach ($invalidStreetNumbers as & $num) $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
728 $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)));
737 * Function to actually build the form
742 public function buildQuickForm() {
743 //load form for child blocks
744 if ($this->_addBlockName
) {
745 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
746 return $className::buildQuickForm($this);
749 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
750 $deleteExtra = ts('Are you sure you want to delete contact image.');
752 CRM_Core_Action
::DELETE
=>
754 'name' => ts('Delete Contact Image'),
755 'url' => 'civicrm/contact/image',
756 'qs' => 'reset=1&cid=%%id%%&action=delete',
758 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
761 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
762 CRM_Core_Action
::DELETE
,
764 'id' => $this->_contactId
,
768 'contact.image.delete',
772 $this->assign('deleteURL', $deleteURL);
775 //build contact type specific fields
776 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
777 $className::buildQuickForm($this);
779 // build Custom data if Custom data present in edit option
780 $buildCustomData = 'noCustomDataPresent';
781 if (array_key_exists('CustomData', $this->_editOptions
)) {
782 $buildCustomData = "customDataPresent";
785 // subtype is a common field. lets keep it here
786 $subtypes = CRM_Contact_BAO_ContactType
::subTypePairs($this->_contactType
);
787 if (!empty($subtypes)) {
788 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
791 'id' => 'contact_sub_type',
792 'multiple' => 'multiple',
793 'title' => '- ' . ts('select') . ' -',
794 'class' => $buildCustomData,
799 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
800 foreach ($this->_editOptions
as $name => $label) {
801 if ($name == 'Address') {
802 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
805 if ($name == 'TagsAndGroups') {
808 $className = 'CRM_Contact_Form_Edit_' . $name;
809 $className::buildQuickForm($this);
812 // build tags and groups
813 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
814 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'crmasmSelect');
816 // build location blocks.
817 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
818 CRM_Contact_Form_Location
::buildQuickForm($this);
821 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
822 $this->addUploadElement('image_URL');
824 // add the dedupe button
825 $this->addElement('submit',
826 $this->_dedupeButtonName
,
827 ts('Check for Matching Contact(s)')
829 $this->addElement('submit',
830 $this->_duplicateButtonName
,
831 ts('Save Matching Contact')
833 $this->addElement('submit',
834 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
835 ts('Save With Duplicate Household')
841 'name' => ts('Save'),
847 'name' => ts('Save and New'),
848 'spacing' => ' ',
853 'name' => ts('Cancel'),
857 if (CRM_Utils_Array
::value('contact_sub_type', $this->_values
)) {
858 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
859 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
862 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
864 $this->addButtons($buttons);
868 * Form submission of new/edit contact is processed.
874 public function postProcess() {
875 // check if dedupe button, if so return.
876 $buttonName = $this->controller
->getButtonName();
877 if ($buttonName == $this->_dedupeButtonName
) {
881 //get the submitted values in an array
882 $params = $this->controller
->exportValues($this->_name
);
884 $group = CRM_Utils_Array
::value('group', $params);
885 if ($group && is_array($group)) {
886 unset($params['group']);
887 foreach ($group as $key => $value) {
888 $params['group'][$value] = 1;
892 CRM_Contact_BAO_Contact_Optimizer
::edit( $params, $this->_preEditValues
);
894 if (CRM_Utils_Array
::value('image_URL', $params)) {
895 CRM_Contact_BAO_Contact
::processImageParams($params);
898 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params))
899 && CRM_Utils_Array
::value('current_employer', $params)
901 $params['current_employer'] = $params['current_employer_id'];
904 // don't carry current_employer_id field,
905 // since we don't want to directly update DAO object without
906 // handling related business logic ( eg related membership )
907 if (isset($params['current_employer_id'])) {
908 unset($params['current_employer_id']);
911 $params['contact_type'] = $this->_contactType
;
912 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
913 $params['contact_sub_type'] = array($this->_contactSubType
);
916 if ($this->_contactId
) {
917 $params['contact_id'] = $this->_contactId
;
920 //make deceased date null when is_deceased = false
921 if ($this->_contactType
== 'Individual' &&
922 CRM_Utils_Array
::value('Demographics', $this->_editOptions
) &&
923 !CRM_Utils_Array
::value('is_deceased', $params)
925 $params['is_deceased'] = FALSE;
926 $params['deceased_date'] = NULL;
929 if (isset($params['contact_id'])) {
930 // process membership status for deceased contact
931 $deceasedParams = array('contact_id' => CRM_Utils_Array
::value('contact_id', $params),
932 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
933 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
935 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
938 // action is taken depending upon the mode
939 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
940 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
943 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
946 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
949 //if subtype is set, send subtype as extend to validate subtype customfield
950 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
952 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
958 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
959 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
960 $params['contact_type'],
962 $params['contact_sub_type']
966 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
967 // this is a chekbox, so mark false if we dont get a POST value
968 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
971 // process shared contact address.
972 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
974 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
975 unset($params['group']);
978 if (CRM_Utils_Array
::value('contact_id', $params) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
979 // figure out which all groups are intended to be removed
980 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
981 if (is_array($contactGroupList)) {
982 foreach ($contactGroupList as $key) {
983 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1)
984 && !CRM_Utils_Array
::value('is_hidden', $key)
986 $params['group'][$key['group_id']] = -1;
992 // parse street address, CRM-5450
993 $parseStatusMsg = NULL;
994 if ($this->_parseStreetAddress
) {
995 $parseResult = self
::parseAddress($params);
996 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
999 // Allow un-setting of location info, CRM-5969
1000 $params['updateBlankLocInfo'] = TRUE;
1002 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
1005 if ($this->_contactId
) {
1006 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
1009 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
1012 // set the contact ID
1013 $this->_contactId
= $contact->id
;
1015 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
1016 //add contact to tags
1017 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1020 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1021 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1025 if (!empty($parseStatusMsg)) {
1026 $message .= "<br />$parseStatusMsg";
1028 if (!empty($updateMembershipMsg)) {
1029 $message .= "<br />$updateMembershipMsg";
1032 $session = CRM_Core_Session
::singleton();
1033 $session->setStatus($message, ts('Contact Saved'), 'success');
1035 // add the recently viewed contact
1036 $recentOther = array();
1037 if (($session->get('userID') == $contact->id
) ||
1038 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1040 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1043 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1044 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1047 CRM_Utils_Recent
::add($contact->display_name
,
1048 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1050 $this->_contactType
,
1052 $contact->display_name
,
1056 // here we replace the user context with the url to view this contact
1057 $buttonName = $this->controller
->getButtonName();
1058 if ($buttonName == $this->getButtonName('upload', 'new')) {
1059 $resetStr = "reset=1&ct={$contact->contact_type}";
1060 $resetStr .= $this->_contactSubType ?
"&cst={$this->_contactSubType}" : '';
1061 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1064 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1065 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1066 //validate the qfKey
1067 $urlParams = 'reset=1&cid=' . $contact->id
;
1069 $urlParams .= "&context=$context";
1071 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1072 $urlParams .= "&key=$qfKey";
1075 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1078 // now invoke the post hook
1079 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1080 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1083 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1088 * is there any real significant data in the hierarchical location array
1090 * @param array $fields the hierarchical value representation of this location
1092 * @return boolean true if data exists, false otherwise
1096 static function blockDataExists(&$fields) {
1097 if (!is_array($fields)) {
1101 static $skipFields = array('location_type_id', 'is_primary', 'phone_type_id', 'provider_id', 'country_id', 'website_type_id', 'master_id');
1102 foreach ($fields as $name => $value) {
1104 foreach ($skipFields as $skip) {
1105 if (strpos("[$skip]", $name) !== FALSE) {
1106 if ($name == 'phone') {
1116 if (is_array($value)) {
1117 if (self
::blockDataExists($value)) {
1122 if (!empty($value)) {
1132 * Function to that checks for duplicate contacts
1134 * @param array $fields fields array which are submitted
1135 * @param array $error error message array
1136 * @param int $contactID contact id
1137 * @param string $contactType contact type
1139 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1140 // if this is a forced save, ignore find duplicate rule
1141 if (!CRM_Utils_Array
::value('_qf_Contact_upload_duplicate', $fields)) {
1143 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1144 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1147 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1149 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1150 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
1151 if ($contactLinks['msg'] == 'view') {
1152 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
1155 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts'));
1157 if ($contactLinks['msg'] == 'merge') {
1158 // We should also get a merge link if this is for an existing contact
1159 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1161 $duplicateContactsLinks .= '.';
1162 $duplicateContactsLinks .= '</div>';
1163 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1165 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1167 $row .= ' <td class="matching-contacts-name"> ';
1168 $row .= $contactLinks['rows'][$i]['display_name'];
1170 $row .= ' <td class="matching-contacts-email"> ';
1171 $row .= $contactLinks['rows'][$i]['primary_email'];
1173 $row .= ' <td class="action-items"> ';
1174 $row .= $contactLinks['rows'][$i]['view'];
1175 $row .= $contactLinks['rows'][$i]['edit'];
1176 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1181 $duplicateContactsLinks .= $row . '</table>';
1182 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1184 $errors['_qf_default'] = $duplicateContactsLinks;
1188 // let smarty know that there are duplicates
1189 $template = CRM_Core_Smarty
::singleton();
1190 $template->assign('isDuplicate', 1);
1192 elseif (CRM_Utils_Array
::value('_qf_Contact_refresh_dedupe', $fields)) {
1193 // add a session message for no matching contacts
1194 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1199 function getTemplateFileName() {
1200 if ($this->_contactSubType
) {
1201 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1202 $template = CRM_Core_Form
::getTemplate();
1203 if ($template->template_exists($templateFile)) {
1204 return $templateFile;
1207 return parent
::getTemplateFileName();
1211 * Parse all address blocks present in given params
1212 * and return parse result for all address blocks,
1213 * This function either parse street address in to child
1214 * elements or build street address from child elements.
1216 * @params $params an array of key value consist of address blocks.
1218 * @return $parseSuccess as array of sucess/fails for each address block
1221 function parseAddress(&$params) {
1222 $parseSuccess = $parsedFields = array();
1223 if (!is_array($params['address']) ||
1224 CRM_Utils_System
::isNull($params['address'])
1226 return $parseSuccess;
1229 foreach ($params['address'] as $instance => & $address) {
1230 $buildStreetAddress = FALSE;
1231 $parseFieldName = 'street_address';
1233 'street_number', 'street_name', 'street_unit') as $fld) {
1234 if (CRM_Utils_Array
::value($fld, $address)) {
1235 $parseFieldName = 'street_number';
1236 $buildStreetAddress = TRUE;
1241 // main parse string.
1242 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1244 // parse address field.
1245 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1247 if ($buildStreetAddress) {
1248 //hack to ignore spaces between number and suffix.
1249 //here user gives input as street_number so it has to
1250 //be street_number and street_number_suffix, but
1251 //due to spaces though preg detect string as street_name
1252 //consider it as 'street_number_suffix'.
1253 $suffix = $parsedFields['street_number_suffix'];
1255 $suffix = $parsedFields['street_name'];
1257 $address['street_number_suffix'] = $suffix;
1258 $address['street_number'] = $parsedFields['street_number'];
1260 $streetAddress = NULL;
1262 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
1263 if (in_array($fld, array(
1264 'street_name', 'street_unit'))) {
1265 $streetAddress .= ' ';
1267 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1269 $address['street_address'] = trim($streetAddress);
1270 $parseSuccess[$instance] = TRUE;
1274 // consider address is automatically parseable,
1275 // when we should found street_number and street_name
1276 if (!CRM_Utils_Array
::value('street_name', $parsedFields) ||
1277 !CRM_Utils_Array
::value('street_number', $parsedFields)
1282 // check for original street address string.
1283 if (empty($parseString)) {
1287 $parseSuccess[$instance] = $success;
1289 // we do not reset element values, but keep what we've parsed
1290 // in case of partial matches: CRM-8378
1292 // merge parse address in to main address block.
1293 $address = array_merge($address, $parsedFields);
1297 return $parseSuccess;
1301 * check parse result and if some address block fails then this
1302 * function return the status message for all address blocks.
1304 * @param $parseResult an array of address blk instance and its status.
1306 * @return $statusMsg string status message for all address blocks.
1309 static function parseAddressStatusMsg($parseResult) {
1311 if (!is_array($parseResult) ||
empty($parseResult)) {
1315 $parseFails = array();
1316 foreach ($parseResult as $instance => $success) {
1318 $parseFails[] = self
::ordinalNumber($instance);
1322 if (!empty($parseFails)) {
1323 $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.",
1324 array(1 => implode(', ', $parseFails))
1332 * Convert normal number to ordinal number format.
1333 * like 1 => 1st, 2 => 2nd and so on...
1335 * @param $number int number to convert in to ordinal number.
1337 * @return ordinal number for given number.
1340 static function ordinalNumber($number) {
1341 if (empty($number)) {
1346 switch (floor($number / 10) %
10) {
1349 switch ($number %
10) {
1364 return "$number$str";
1368 * Update membership status to deceased
1369 * function return the status message for updated membership.
1371 * @param $deceasedParams array having contact id and deceased value.
1373 * @return $updateMembershipMsg string status message for updated membership.
1375 function updateMembershipStatus($deceasedParams) {
1376 $updateMembershipMsg = NULL;
1377 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1378 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1380 // process to set membership status to deceased for both active/inactive membership
1382 $this->_contactType
== 'Individual' &&
1383 CRM_Utils_Array
::value('is_deceased', $deceasedParams)
1386 $session = CRM_Core_Session
::singleton();
1387 $userId = $session->get('userID');
1389 $userId = $contactId;
1393 // get deceased status id
1394 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1395 $deceasedStatusId = array_search('Deceased', $allStatus);
1396 if (!$deceasedStatusId) {
1397 return $updateMembershipMsg;
1401 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1402 return $updateMembershipMsg;
1405 // get non deceased membership
1406 $dao = new CRM_Member_DAO_Membership();
1407 $dao->contact_id
= $contactId;
1408 $dao->whereAdd("status_id != $deceasedStatusId");
1410 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1411 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1413 while ($dao->fetch()) {
1414 // update status to deceased (for both active/inactive membership )
1415 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1416 'status_id', $deceasedStatusId
1419 // add membership log
1420 $membershipLog = array(
1421 'membership_id' => $dao->id
,
1422 'status_id' => $deceasedStatusId,
1423 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1424 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1425 'modified_id' => $userId,
1426 'modified_date' => date('Ymd'),
1427 'membership_type_id' => $dao->membership_type_id
,
1428 'max_related' => $dao->max_related
,
1432 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1434 //create activity when membership status is changed
1435 $activityParam = array(
1436 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1437 'source_contact_id' => $userId,
1438 'target_contact_id' => $dao->contact_id
,
1439 'source_record_id' => $dao->id
,
1440 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1444 'activity_date_time' => date('Y-m-d H:i:s'),
1446 'is_current_revision' => 1,
1449 $activityResult = civicrm_api('activity', 'create', $activityParam);
1456 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1457 array(1 => $memCount)
1462 return $updateMembershipMsg;