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
,
767 $this->assign('deleteURL', $deleteURL);
770 //build contact type specific fields
771 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
772 $className::buildQuickForm($this);
774 // build Custom data if Custom data present in edit option
775 $buildCustomData = 'noCustomDataPresent';
776 if (array_key_exists('CustomData', $this->_editOptions
)) {
777 $buildCustomData = "customDataPresent";
780 // subtype is a common field. lets keep it here
781 $subtypes = CRM_Contact_BAO_ContactType
::subTypePairs($this->_contactType
);
782 if (!empty($subtypes)) {
783 $sel = $this->add('select', 'contact_sub_type', ts('Contact Type'),
786 'id' => 'contact_sub_type',
787 'multiple' => 'multiple',
788 'title' => '- ' . ts('select') . ' -',
789 'class' => $buildCustomData,
794 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
795 foreach ($this->_editOptions
as $name => $label) {
796 if ($name == 'Address') {
797 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
800 if ($name == 'TagsAndGroups') {
803 $className = 'CRM_Contact_Form_Edit_' . $name;
804 $className::buildQuickForm($this);
807 // build tags and groups
808 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
809 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'crmasmSelect');
811 // build location blocks.
812 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
813 CRM_Contact_Form_Location
::buildQuickForm($this);
816 $this->addElement('file', 'image_URL', ts('Browse/Upload Image'), 'size=30 maxlength=60');
817 $this->addUploadElement('image_URL');
819 // add the dedupe button
820 $this->addElement('submit',
821 $this->_dedupeButtonName
,
822 ts('Check for Matching Contact(s)')
824 $this->addElement('submit',
825 $this->_duplicateButtonName
,
826 ts('Save Matching Contact')
828 $this->addElement('submit',
829 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
830 ts('Save With Duplicate Household')
836 'name' => ts('Save'),
842 'name' => ts('Save and New'),
843 'spacing' => ' ',
848 'name' => ts('Cancel'),
852 if (CRM_Utils_Array
::value('contact_sub_type', $this->_values
)) {
853 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
854 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
857 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
859 $this->addButtons($buttons);
863 * Form submission of new/edit contact is processed.
869 public function postProcess() {
870 // check if dedupe button, if so return.
871 $buttonName = $this->controller
->getButtonName();
872 if ($buttonName == $this->_dedupeButtonName
) {
876 //get the submitted values in an array
877 $params = $this->controller
->exportValues($this->_name
);
879 $group = CRM_Utils_Array
::value('group', $params);
880 if ($group && is_array($group)) {
881 unset($params['group']);
882 foreach ($group as $key => $value) {
883 $params['group'][$value] = 1;
887 CRM_Contact_BAO_Contact_Optimizer
::edit( $params, $this->_preEditValues
);
889 if (CRM_Utils_Array
::value('image_URL', $params)) {
890 CRM_Contact_BAO_Contact
::processImageParams($params);
893 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params))
894 && CRM_Utils_Array
::value('current_employer', $params)
896 $params['current_employer'] = $params['current_employer_id'];
899 // don't carry current_employer_id field,
900 // since we don't want to directly update DAO object without
901 // handling related business logic ( eg related membership )
902 if (isset($params['current_employer_id'])) {
903 unset($params['current_employer_id']);
906 $params['contact_type'] = $this->_contactType
;
907 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
908 $params['contact_sub_type'] = array($this->_contactSubType
);
911 if ($this->_contactId
) {
912 $params['contact_id'] = $this->_contactId
;
915 //make deceased date null when is_deceased = false
916 if ($this->_contactType
== 'Individual' &&
917 CRM_Utils_Array
::value('Demographics', $this->_editOptions
) &&
918 !CRM_Utils_Array
::value('is_deceased', $params)
920 $params['is_deceased'] = FALSE;
921 $params['deceased_date'] = NULL;
924 if (isset($params['contact_id'])) {
925 // process membership status for deceased contact
926 $deceasedParams = array('contact_id' => CRM_Utils_Array
::value('contact_id', $params),
927 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
928 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
930 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
933 // action is taken depending upon the mode
934 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
935 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
938 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
941 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
944 //if subtype is set, send subtype as extend to validate subtype customfield
945 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
947 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
953 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
954 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
955 $params['contact_type'],
957 $params['contact_sub_type']
961 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
962 // this is a chekbox, so mark false if we dont get a POST value
963 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
966 // process shared contact address.
967 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
969 if (!array_key_exists('TagsAndGroups', $this->_editOptions
)) {
970 unset($params['group']);
973 if (CRM_Utils_Array
::value('contact_id', $params) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
974 // figure out which all groups are intended to be removed
975 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
976 if (is_array($contactGroupList)) {
977 foreach ($contactGroupList as $key) {
978 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1)
979 && !CRM_Utils_Array
::value('is_hidden', $key)
981 $params['group'][$key['group_id']] = -1;
987 // parse street address, CRM-5450
988 $parseStatusMsg = NULL;
989 if ($this->_parseStreetAddress
) {
990 $parseResult = self
::parseAddress($params);
991 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
994 // Allow un-setting of location info, CRM-5969
995 $params['updateBlankLocInfo'] = TRUE;
997 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
1000 if ($this->_contactId
) {
1001 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
1004 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
1007 // set the contact ID
1008 $this->_contactId
= $contact->id
;
1010 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
1011 //add contact to tags
1012 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1015 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1016 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1020 if (!empty($parseStatusMsg)) {
1021 $message .= "<br />$parseStatusMsg";
1023 if (!empty($updateMembershipMsg)) {
1024 $message .= "<br />$updateMembershipMsg";
1027 $session = CRM_Core_Session
::singleton();
1028 $session->setStatus($message, ts('Contact Saved'), 'success');
1030 // add the recently viewed contact
1031 $recentOther = array();
1032 if (($session->get('userID') == $contact->id
) ||
1033 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1035 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1038 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1039 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1042 CRM_Utils_Recent
::add($contact->display_name
,
1043 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1045 $this->_contactType
,
1047 $contact->display_name
,
1051 // here we replace the user context with the url to view this contact
1052 $buttonName = $this->controller
->getButtonName();
1053 if ($buttonName == $this->getButtonName('upload', 'new')) {
1054 $resetStr = "reset=1&ct={$contact->contact_type}";
1055 $resetStr .= $this->_contactSubType ?
"&cst={$this->_contactSubType}" : '';
1056 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1059 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1060 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1061 //validate the qfKey
1062 $urlParams = 'reset=1&cid=' . $contact->id
;
1064 $urlParams .= "&context=$context";
1066 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1067 $urlParams .= "&key=$qfKey";
1070 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1073 // now invoke the post hook
1074 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1075 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1078 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1083 * is there any real significant data in the hierarchical location array
1085 * @param array $fields the hierarchical value representation of this location
1087 * @return boolean true if data exists, false otherwise
1091 static function blockDataExists(&$fields) {
1092 if (!is_array($fields)) {
1096 static $skipFields = array('location_type_id', 'is_primary', 'phone_type_id', 'provider_id', 'country_id', 'website_type_id', 'master_id');
1097 foreach ($fields as $name => $value) {
1099 foreach ($skipFields as $skip) {
1100 if (strpos("[$skip]", $name) !== FALSE) {
1101 if ($name == 'phone') {
1111 if (is_array($value)) {
1112 if (self
::blockDataExists($value)) {
1117 if (!empty($value)) {
1127 * Function to that checks for duplicate contacts
1129 * @param array $fields fields array which are submitted
1130 * @param array $error error message array
1131 * @param int $contactID contact id
1132 * @param string $contactType contact type
1134 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1135 // if this is a forced save, ignore find duplicate rule
1136 if (!CRM_Utils_Array
::value('_qf_Contact_upload_duplicate', $fields)) {
1138 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1139 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1142 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1144 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1145 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
1146 if ($contactLinks['msg'] == 'view') {
1147 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
1150 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts'));
1152 if ($contactLinks['msg'] == 'merge') {
1153 // We should also get a merge link if this is for an existing contact
1154 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1156 $duplicateContactsLinks .= '.';
1157 $duplicateContactsLinks .= '</div>';
1158 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1160 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1162 $row .= ' <td class="matching-contacts-name"> ';
1163 $row .= $contactLinks['rows'][$i]['display_name'];
1165 $row .= ' <td class="matching-contacts-email"> ';
1166 $row .= $contactLinks['rows'][$i]['primary_email'];
1168 $row .= ' <td class="action-items"> ';
1169 $row .= $contactLinks['rows'][$i]['view'];
1170 $row .= $contactLinks['rows'][$i]['edit'];
1171 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1176 $duplicateContactsLinks .= $row . '</table>';
1177 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1179 $errors['_qf_default'] = $duplicateContactsLinks;
1183 // let smarty know that there are duplicates
1184 $template = CRM_Core_Smarty
::singleton();
1185 $template->assign('isDuplicate', 1);
1187 elseif (CRM_Utils_Array
::value('_qf_Contact_refresh_dedupe', $fields)) {
1188 // add a session message for no matching contacts
1189 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1194 function getTemplateFileName() {
1195 if ($this->_contactSubType
) {
1196 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1197 $template = CRM_Core_Form
::getTemplate();
1198 if ($template->template_exists($templateFile)) {
1199 return $templateFile;
1202 return parent
::getTemplateFileName();
1206 * Parse all address blocks present in given params
1207 * and return parse result for all address blocks,
1208 * This function either parse street address in to child
1209 * elements or build street address from child elements.
1211 * @params $params an array of key value consist of address blocks.
1213 * @return $parseSuccess as array of sucess/fails for each address block
1216 function parseAddress(&$params) {
1217 $parseSuccess = $parsedFields = array();
1218 if (!is_array($params['address']) ||
1219 CRM_Utils_System
::isNull($params['address'])
1221 return $parseSuccess;
1224 foreach ($params['address'] as $instance => & $address) {
1225 $buildStreetAddress = FALSE;
1226 $parseFieldName = 'street_address';
1228 'street_number', 'street_name', 'street_unit') as $fld) {
1229 if (CRM_Utils_Array
::value($fld, $address)) {
1230 $parseFieldName = 'street_number';
1231 $buildStreetAddress = TRUE;
1236 // main parse string.
1237 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1239 // parse address field.
1240 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1242 if ($buildStreetAddress) {
1243 //hack to ignore spaces between number and suffix.
1244 //here user gives input as street_number so it has to
1245 //be street_number and street_number_suffix, but
1246 //due to spaces though preg detect string as street_name
1247 //consider it as 'street_number_suffix'.
1248 $suffix = $parsedFields['street_number_suffix'];
1250 $suffix = $parsedFields['street_name'];
1252 $address['street_number_suffix'] = $suffix;
1253 $address['street_number'] = $parsedFields['street_number'];
1255 $streetAddress = NULL;
1257 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
1258 if (in_array($fld, array(
1259 'street_name', 'street_unit'))) {
1260 $streetAddress .= ' ';
1262 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1264 $address['street_address'] = trim($streetAddress);
1265 $parseSuccess[$instance] = TRUE;
1269 // consider address is automatically parseable,
1270 // when we should found street_number and street_name
1271 if (!CRM_Utils_Array
::value('street_name', $parsedFields) ||
1272 !CRM_Utils_Array
::value('street_number', $parsedFields)
1277 // check for original street address string.
1278 if (empty($parseString)) {
1282 $parseSuccess[$instance] = $success;
1284 // we do not reset element values, but keep what we've parsed
1285 // in case of partial matches: CRM-8378
1287 // merge parse address in to main address block.
1288 $address = array_merge($address, $parsedFields);
1292 return $parseSuccess;
1296 * check parse result and if some address block fails then this
1297 * function return the status message for all address blocks.
1299 * @param $parseResult an array of address blk instance and its status.
1301 * @return $statusMsg string status message for all address blocks.
1304 static function parseAddressStatusMsg($parseResult) {
1306 if (!is_array($parseResult) ||
empty($parseResult)) {
1310 $parseFails = array();
1311 foreach ($parseResult as $instance => $success) {
1313 $parseFails[] = self
::ordinalNumber($instance);
1317 if (!empty($parseFails)) {
1318 $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.",
1319 array(1 => implode(', ', $parseFails))
1327 * Convert normal number to ordinal number format.
1328 * like 1 => 1st, 2 => 2nd and so on...
1330 * @param $number int number to convert in to ordinal number.
1332 * @return ordinal number for given number.
1335 static function ordinalNumber($number) {
1336 if (empty($number)) {
1341 switch (floor($number / 10) %
10) {
1344 switch ($number %
10) {
1359 return "$number$str";
1363 * Update membership status to deceased
1364 * function return the status message for updated membership.
1366 * @param $deceasedParams array having contact id and deceased value.
1368 * @return $updateMembershipMsg string status message for updated membership.
1370 function updateMembershipStatus($deceasedParams) {
1371 $updateMembershipMsg = NULL;
1372 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1373 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1375 // process to set membership status to deceased for both active/inactive membership
1377 $this->_contactType
== 'Individual' &&
1378 CRM_Utils_Array
::value('is_deceased', $deceasedParams)
1381 $session = CRM_Core_Session
::singleton();
1382 $userId = $session->get('userID');
1384 $userId = $contactId;
1388 // get deceased status id
1389 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1390 $deceasedStatusId = array_search('Deceased', $allStatus);
1391 if (!$deceasedStatusId) {
1392 return $updateMembershipMsg;
1396 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1397 return $updateMembershipMsg;
1400 // get non deceased membership
1401 $dao = new CRM_Member_DAO_Membership();
1402 $dao->contact_id
= $contactId;
1403 $dao->whereAdd("status_id != $deceasedStatusId");
1405 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1406 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1408 while ($dao->fetch()) {
1409 // update status to deceased (for both active/inactive membership )
1410 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1411 'status_id', $deceasedStatusId
1414 // add membership log
1415 $membershipLog = array(
1416 'membership_id' => $dao->id
,
1417 'status_id' => $deceasedStatusId,
1418 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1419 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1420 'modified_id' => $userId,
1421 'modified_date' => date('Ymd'),
1422 'membership_type_id' => $dao->membership_type_id
,
1423 'max_related' => $dao->max_related
,
1427 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1429 //create activity when membership status is changed
1430 $activityParam = array(
1431 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1432 'source_contact_id' => $userId,
1433 'target_contact_id' => $dao->contact_id
,
1434 'source_record_id' => $dao->id
,
1435 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1439 'activity_date_time' => date('Y-m-d H:i:s'),
1441 'is_current_revision' => 1,
1444 $activityResult = civicrm_api('activity', 'create', $activityParam);
1451 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1452 array(1 => $memCount)
1457 return $updateMembershipMsg;