3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 * This class generates form components generic to all the contact types.
37 * It delegates the work to lower level subclasses and integrates the changes
38 * back in. It also uses a lot of functionality with the CRM API's, so any change
39 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
42 class CRM_Contact_Form_Contact
extends CRM_Core_Form
{
45 * The contact type of the form.
52 * The contact type of the form.
56 public $_contactSubType;
59 * The contact id, used when editing the form
66 * The default group id passed in via the url.
73 * The default tag id passed in via the url.
80 * Name of de-dupe button
84 protected $_dedupeButtonName;
87 * Name of optional save duplicate button.
91 protected $_duplicateButtonName;
93 protected $_editOptions = array();
95 protected $_oldSubtypes = array();
99 public $_values = array();
103 public $_customValueCount;
105 * The array of greetings with option group and filed names.
112 * Do we want to parse street address.
114 public $_parseStreetAddress;
117 * Check contact has a subtype or not.
119 public $_isContactSubType;
122 * Lets keep a cache of all the values that we retrieved.
123 * THis is an attempt to avoid the number of update statements
124 * during the write phase
126 public $_preEditValues;
129 * Explicitly declare the entity api name.
131 public function getDefaultEntity() {
136 * Explicitly declare the form context.
138 public function getDefaultContext() {
143 * Build all the data structures needed to build the form.
145 public function preProcess() {
146 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
148 $this->_dedupeButtonName
= $this->getButtonName('refresh', 'dedupe');
149 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
151 CRM_Core_Resources
::singleton()
152 ->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
154 $session = CRM_Core_Session
::singleton();
155 if ($this->_action
== CRM_Core_Action
::ADD
) {
156 // check for add contacts permissions
157 if (!CRM_Core_Permission
::check('add contacts')) {
158 CRM_Utils_System
::permissionDenied();
159 CRM_Utils_System
::civiExit();
161 $this->_contactType
= CRM_Utils_Request
::retrieve('ct', 'String',
162 $this, TRUE, NULL, 'REQUEST'
164 if (!in_array($this->_contactType
,
165 array('Individual', 'Household', 'Organization')
168 CRM_Core_Error
::statusBounce(ts('Could not get a contact id and/or contact type'));
171 $this->_isContactSubType
= FALSE;
172 if ($this->_contactSubType
= CRM_Utils_Request
::retrieve('cst', 'String', $this)) {
173 $this->_isContactSubType
= TRUE;
177 $this->_contactSubType
&&
178 !(CRM_Contact_BAO_ContactType
::isExtendsContactType($this->_contactSubType
, $this->_contactType
, TRUE))
180 CRM_Core_Error
::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType
)));
183 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Integer',
184 CRM_Core_DAO
::$_nullObject,
187 $this->_tid
= CRM_Utils_Request
::retrieve('tid', 'Integer',
188 CRM_Core_DAO
::$_nullObject,
191 $typeLabel = CRM_Contact_BAO_ContactType
::contactTypePairs(TRUE, $this->_contactSubType ?
192 $this->_contactSubType
: $this->_contactType
194 $typeLabel = implode(' / ', $typeLabel);
196 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $typeLabel)));
197 $session->pushUserContext(CRM_Utils_System
::url('civicrm/dashboard', 'reset=1'));
198 $this->_contactId
= NULL;
202 if (!$this->_contactId
) {
203 $this->_contactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
206 if ($this->_contactId
) {
208 $params = array('id' => $this->_contactId
);
209 $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased');
210 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
212 if (empty($defaults['id'])) {
213 CRM_Core_Error
::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId
)));
216 $this->_contactType
= CRM_Utils_Array
::value('contact_type', $defaults);
217 $this->_contactSubType
= CRM_Utils_Array
::value('contact_sub_type', $defaults);
219 // check for permissions
220 $session = CRM_Core_Session
::singleton();
221 if (!CRM_Contact_BAO_Contact_Permission
::allow($this->_contactId
, CRM_Core_Permission
::EDIT
)) {
222 CRM_Core_Error
::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
225 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactId
);
226 if ($defaults['is_deceased']) {
227 $displayName .= ' <span class="crm-contact-deceased">(deceased)</span>';
229 $displayName = ts('Edit %1', array(1 => $displayName));
231 // Check if this is default domain contact CRM-10482
232 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactId
)) {
233 $displayName .= ' (' . ts('default organization') . ')';
236 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
237 CRM_Utils_System
::setTitle($displayName);
238 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
239 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
241 $urlParams = 'reset=1&cid=' . $this->_contactId
;
243 $urlParams .= "&context=$context";
246 if (CRM_Utils_Rule
::qfKey($qfKey)) {
248 $urlParams .= "&key=$qfKey";
251 $session->pushUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
253 $values = $this->get('values');
254 // get contact values.
255 if (!empty($values)) {
256 $this->_values
= $values;
260 'id' => $this->_contactId
,
261 'contact_id' => $this->_contactId
,
262 'noRelationships' => TRUE,
267 $contact = CRM_Contact_BAO_Contact
::retrieve($params, $this->_values
, TRUE);
268 $this->set('values', $this->_values
);
272 CRM_Core_Error
::statusBounce(ts('Could not get a contact_id and/or contact_type'));
276 // parse street address, CRM-5450
277 $this->_parseStreetAddress
= $this->get('parseStreetAddress');
278 if (!isset($this->_parseStreetAddress
)) {
279 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
282 $this->_parseStreetAddress
= FALSE;
283 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
284 $this->_parseStreetAddress
= TRUE;
286 $this->set('parseStreetAddress', $this->_parseStreetAddress
);
288 $this->assign('parseStreetAddress', $this->_parseStreetAddress
);
290 $this->_editOptions
= $this->get('contactEditOptions');
291 if (CRM_Utils_System
::isNull($this->_editOptions
)) {
292 $this->_editOptions
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
293 'contact_edit_options', TRUE, NULL,
294 FALSE, 'name', TRUE, 'AND v.filter = 0'
296 $this->set('contactEditOptions', $this->_editOptions
);
299 // build demographics only for Individual contact type
300 if ($this->_contactType
!= 'Individual' &&
301 array_key_exists('Demographics', $this->_editOptions
)
303 unset($this->_editOptions
['Demographics']);
306 // in update mode don't show notes
307 if ($this->_contactId
&& array_key_exists('Notes', $this->_editOptions
)) {
308 unset($this->_editOptions
['Notes']);
311 $this->assign('editOptions', $this->_editOptions
);
312 $this->assign('contactType', $this->_contactType
);
313 $this->assign('contactSubType', $this->_contactSubType
);
315 //build contact subtype form element, CRM-6864
316 $buildContactSubType = TRUE;
317 if ($this->_contactSubType
&& ($this->_action
& CRM_Core_Action
::ADD
)) {
318 $buildContactSubType = FALSE;
320 $this->assign('buildContactSubType', $buildContactSubType);
322 // get the location blocks.
323 $this->_blocks
= $this->get('blocks');
324 if (CRM_Utils_System
::isNull($this->_blocks
)) {
325 $this->_blocks
= CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
326 'contact_edit_options', TRUE, NULL,
327 FALSE, 'name', TRUE, 'AND v.filter = 1'
329 $this->set('blocks', $this->_blocks
);
331 $this->assign('blocks', $this->_blocks
);
333 // this is needed for custom data.
334 $this->assign('entityID', $this->_contactId
);
336 // also keep the convention.
337 $this->assign('contactId', $this->_contactId
);
340 CRM_Contact_Form_Location
::preProcess($this);
342 // retain the multiple count custom fields value
343 if (!empty($_POST['hidden_custom'])) {
344 $customGroupCount = CRM_Utils_Array
::value('hidden_custom_group_count', $_POST);
346 if ($contactSubType = CRM_Utils_Array
::value('contact_sub_type', $_POST)) {
347 $paramSubType = implode(',', $contactSubType);
350 $this->_getCachedTree
= FALSE;
351 unset($customGroupCount[0]);
352 foreach ($customGroupCount as $groupID => $groupCount) {
353 if ($groupCount > 1) {
354 $this->set('groupID', $groupID);
356 for ($i = 0; $i <= $groupCount; $i++
) {
357 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
358 $i, $this->_contactType
360 CRM_Contact_Form_Edit_CustomData
::buildQuickForm($this);
365 //reset all the ajax stuff, for normal processing
366 if (isset($this->_groupTree
)) {
367 $this->_groupTree
= NULL;
369 $this->set('groupID', NULL);
370 $this->_getCachedTree
= TRUE;
373 // execute preProcess dynamically by js else execute normal preProcess
374 if (array_key_exists('CustomData', $this->_editOptions
)) {
375 //assign a parameter to pass for sub type multivalue
376 //custom field to load
377 if ($this->_contactSubType ||
isset($paramSubType)) {
378 $paramSubType = (isset($paramSubType)) ?
$paramSubType :
379 str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, ',', trim($this->_contactSubType
, CRM_Core_DAO
::VALUE_SEPARATOR
));
381 $this->assign('paramSubType', $paramSubType);
384 if (CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject)) {
385 CRM_Contact_Form_Edit_CustomData
::preProcess($this);
388 $contactSubType = $this->_contactSubType
;
389 // need contact sub type to build related grouptree array during post process
390 if (!empty($_POST['contact_sub_type'])) {
391 $contactSubType = $_POST['contact_sub_type'];
393 //only custom data has preprocess hence directly call it
394 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $contactSubType,
395 1, $this->_contactType
, $this->_contactId
397 $this->assign('customValueCount', $this->_customValueCount
);
403 * Set default values for the form.
405 * Note that in edit/view mode the default values are retrieved from the database
407 public function setDefaultValues() {
408 $defaults = $this->_values
;
410 if ($this->_action
& CRM_Core_Action
::ADD
) {
411 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
412 // set group and tag defaults if any
414 $defaults['group'][] = $this->_gid
;
417 $defaults['tag'][$this->_tid
] = 1;
420 if ($this->_contactSubType
) {
421 $defaults['contact_sub_type'] = $this->_contactSubType
;
425 foreach ($defaults['email'] as $dontCare => & $val) {
426 if (isset($val['signature_text'])) {
427 $val['signature_text_hidden'] = $val['signature_text'];
429 if (isset($val['signature_html'])) {
430 $val['signature_html_hidden'] = $val['signature_html'];
434 if (!empty($defaults['contact_sub_type'])) {
435 $defaults['contact_sub_type'] = $this->_oldSubtypes
;
438 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
439 foreach ($this->_editOptions
as $name => $label) {
440 if (!in_array($name, array('Address', 'Notes'))) {
441 $className = 'CRM_Contact_Form_Edit_' . $name;
442 $className::setDefaultValues($this, $defaults);
446 //set address block defaults
447 CRM_Contact_Form_Edit_Address
::setDefaultValues($defaults, $this);
449 if (!empty($defaults['image_URL'])) {
450 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String
::unstupifyUrl($defaults['image_URL']));
451 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
452 $this->assign('imageWidth', $imageWidth);
453 $this->assign('imageHeight', $imageHeight);
454 $this->assign('imageThumbWidth', $imageThumbWidth);
455 $this->assign('imageThumbHeight', $imageThumbHeight);
456 $this->assign('imageURL', $defaults['image_URL']);
459 //set location type and country to default for each block
460 $this->blockSetDefaults($defaults);
462 $this->_preEditValues
= $defaults;
467 * Do the set default related to location type id,
468 * primary location, default country
470 public function blockSetDefaults(&$defaults) {
471 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
472 sort($locationTypeKeys);
474 // get the default location type
475 $locationType = CRM_Core_BAO_LocationType
::getDefault();
477 // unset primary location type
478 $primaryLocationTypeIdKey = CRM_Utils_Array
::key($locationType->id
, $locationTypeKeys);
479 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
481 // reset the array sequence
482 $locationTypeKeys = array_values($locationTypeKeys);
484 // get default phone and im provider id.
485 $defPhoneTypeId = key(CRM_Core_OptionGroup
::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
486 $defIMProviderId = key(CRM_Core_OptionGroup
::values('instant_messenger_service',
487 FALSE, FALSE, FALSE, ' AND is_default = 1'
489 $defWebsiteTypeId = key(CRM_Core_OptionGroup
::values('website_type',
490 FALSE, FALSE, FALSE, ' AND is_default = 1'
493 $allBlocks = $this->_blocks
;
494 if (array_key_exists('Address', $this->_editOptions
)) {
495 $allBlocks['Address'] = $this->_editOptions
['Address'];
498 $config = CRM_Core_Config
::singleton();
499 foreach ($allBlocks as $blockName => $label) {
500 $name = strtolower($blockName);
501 $hasPrimary = $updateMode = FALSE;
503 // user is in update mode.
504 if (array_key_exists($name, $defaults) &&
505 !CRM_Utils_System
::isNull($defaults[$name])
510 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++
) {
511 // make we require one primary block, CRM-5505
514 $hasPrimary = CRM_Utils_Array
::value(
516 CRM_Utils_Array
::value($instance, $defaults[$name])
522 //set location to primary for first one.
523 if ($instance == 1) {
525 $defaults[$name][$instance]['is_primary'] = TRUE;
526 $defaults[$name][$instance]['location_type_id'] = $locationType->id
;
529 $locTypeId = isset($locationTypeKeys[$instance - 1]) ?
$locationTypeKeys[$instance - 1] : $locationType->id
;
530 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
533 //set default country
534 if ($name == 'address' && $config->defaultContactCountry
) {
535 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry
;
538 //set default state/province
539 if ($name == 'address' && $config->defaultContactStateProvince
) {
540 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince
;
543 //set default phone type.
544 if ($name == 'phone' && $defPhoneTypeId) {
545 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
547 //set default website type.
548 if ($name == 'website' && $defWebsiteTypeId) {
549 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
552 //set default im provider.
553 if ($name == 'im' && $defIMProviderId) {
554 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
559 $defaults[$name][1]['is_primary'] = TRUE;
565 * add the rules (mainly global rules) for form.
566 * All local rules are added near the element
570 public function addRules() {
571 // skip adding formRules when custom data is build
572 if ($this->_addBlockName ||
($this->_action
& CRM_Core_Action
::DELETE
)) {
576 $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType
, 'formRule'), $this->_contactId
);
578 // Call Locking check if editing existing contact
579 if ($this->_contactId
) {
580 $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId
);
583 if (array_key_exists('Address', $this->_editOptions
)) {
584 $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
587 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
588 $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
593 * Global validation rules for the form.
595 * @param array $fields
596 * Posted values of the form.
597 * @param array $errors
598 * List of errors to be posted back to the form.
599 * @param int $contactId
600 * Contact id if doing update.
605 public static function formRule($fields, &$errors, $contactId = NULL) {
606 $config = CRM_Core_Config
::singleton();
609 //1. for each block only single value can be marked as is_primary = true.
610 //2. location type id should be present if block data present.
611 //3. check open id across db and other each block for duplicate.
612 //4. at least one location should be primary.
613 //5. also get primaryID from email or open id block.
615 // take the location blocks.
616 $blocks = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
617 'contact_edit_options', TRUE, NULL,
618 FALSE, 'name', TRUE, 'AND v.filter = 1'
621 $otherEditOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
622 'contact_edit_options', TRUE, NULL,
623 FALSE, 'name', TRUE, 'AND v.filter = 0'
625 //get address block inside.
626 if (array_key_exists('Address', $otherEditOptions)) {
627 $blocks['Address'] = $otherEditOptions['Address'];
632 foreach ($blocks as $name => $label) {
633 $hasData = $hasPrimary = array();
634 $name = strtolower($name);
635 if (!empty($fields[$name]) && is_array($fields[$name])) {
636 foreach ($fields[$name] as $instance => $blockValues) {
637 $dataExists = self
::blockDataExists($blockValues);
639 if (!$dataExists && $name == 'address') {
640 $dataExists = CRM_Utils_Array
::value('use_shared_address', $fields['address'][$instance]);
644 // skip remaining checks for website
645 if ($name == 'website') {
649 $hasData[] = $instance;
650 if (!empty($blockValues['is_primary'])) {
651 $hasPrimary[] = $instance;
653 in_array($name, array(
656 )) && !empty($blockValues[$name])
658 $primaryID = $blockValues[$name];
662 if (empty($blockValues['location_type_id'])) {
663 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
667 if ($name == 'openid' && !empty($blockValues[$name])) {
668 $oid = new CRM_Core_DAO_OpenID();
669 $oid->openid
= $openIds[$instance] = CRM_Utils_Array
::value($name, $blockValues);
670 $cid = isset($contactId) ?
$contactId : 0;
671 if ($oid->find(TRUE) && ($oid->contact_id
!= $cid)) {
672 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
677 if (empty($hasPrimary) && !empty($hasData)) {
678 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
681 if (count($hasPrimary) > 1) {
682 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
689 //do validations for all opend ids they should be distinct.
690 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
691 foreach ($openIds as $instance => $value) {
692 if (!array_key_exists($instance, array_unique($openIds))) {
693 $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
698 // street number should be digit + suffix, CRM-5450
699 $parseStreetAddress = CRM_Utils_Array
::value('street_address_parsing',
700 CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
704 if ($parseStreetAddress) {
705 if (isset($fields['address']) &&
706 is_array($fields['address'])
708 $invalidStreetNumbers = array();
709 foreach ($fields['address'] as $cnt => $address) {
710 if ($streetNumber = CRM_Utils_Array
::value('street_number', $address)) {
711 $parsedAddress = CRM_Core_BAO_Address
::parseStreetAddress($address['street_number']);
712 if (empty($parsedAddress['street_number'])) {
713 $invalidStreetNumbers[] = $cnt;
718 if (!empty($invalidStreetNumbers)) {
719 $first = $invalidStreetNumbers[0];
720 foreach ($invalidStreetNumbers as & $num) {
721 $num = CRM_Contact_Form_Contact
::ordinalNumber($num);
723 $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)));
732 * Build the form object.
734 public function buildQuickForm() {
735 //load form for child blocks
736 if ($this->_addBlockName
) {
737 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName
;
738 return $className::buildQuickForm($this);
741 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
742 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
744 CRM_Core_Action
::DELETE
=> array(
745 'name' => ts('Delete Contact Image'),
746 'url' => 'civicrm/contact/image',
747 'qs' => 'reset=1&cid=%%id%%&action=delete',
748 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
751 $deleteURL = CRM_Core_Action
::formLink($deleteURL,
752 CRM_Core_Action
::DELETE
,
754 'id' => $this->_contactId
,
758 'contact.image.delete',
762 $this->assign('deleteURL', $deleteURL);
765 //build contact type specific fields
766 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType
;
767 $className::buildQuickForm($this);
769 // build Custom data if Custom data present in edit option
770 $buildCustomData = 'noCustomDataPresent';
771 if (array_key_exists('CustomData', $this->_editOptions
)) {
772 $buildCustomData = "customDataPresent";
775 // subtype is a common field. lets keep it here
776 $subtypes = CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType
));
777 if (!empty($subtypes)) {
778 $this->addField('contact_sub_type', array(
779 'label' => ts('Contact Type'),
780 'options' => $subtypes,
781 'class' => $buildCustomData,
782 'multiple' => 'multiple',
783 'options-url' => FALSE,
788 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
789 foreach ($this->_editOptions
as $name => $label) {
790 if ($name == 'Address') {
791 $this->_blocks
['Address'] = $this->_editOptions
['Address'];
794 if ($name == 'TagsAndGroups') {
797 $className = 'CRM_Contact_Form_Edit_' . $name;
798 $className::buildQuickForm($this);
801 // build tags and groups
802 CRM_Contact_Form_Edit_TagsAndGroups
::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups
::ALL
,
803 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
805 // build location blocks.
806 CRM_Contact_Form_Edit_Lock
::buildQuickForm($this);
807 CRM_Contact_Form_Location
::buildQuickForm($this);
810 $this->addField('image_URL', array('maxlength' => '60', 'label' => ts('Browse/Upload Image')));
812 // add the dedupe button
813 $this->addElement('submit',
814 $this->_dedupeButtonName
,
815 ts('Check for Matching Contact(s)')
817 $this->addElement('submit',
818 $this->_duplicateButtonName
,
819 ts('Save Matching Contact')
821 $this->addElement('submit',
822 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
823 ts('Save With Duplicate Household')
829 'name' => ts('Save'),
834 if (CRM_Core_Permission
::check('add contacts')) {
837 'name' => ts('Save and New'),
838 'spacing' => ' ',
844 'name' => ts('Cancel'),
847 if (!empty($this->_values
['contact_sub_type'])) {
848 $this->_oldSubtypes
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
849 trim($this->_values
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
852 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes
));
854 $this->addButtons($buttons);
858 * Form submission of new/edit contact is processed.
860 public function postProcess() {
861 // check if dedupe button, if so return.
862 $buttonName = $this->controller
->getButtonName();
863 if ($buttonName == $this->_dedupeButtonName
) {
867 //get the submitted values in an array
868 $params = $this->controller
->exportValues($this->_name
);
870 $group = CRM_Utils_Array
::value('group', $params);
871 if (!empty($group) && is_array($group)) {
872 unset($params['group']);
873 foreach ($group as $key => $value) {
874 $params['group'][$value] = 1;
878 CRM_Contact_BAO_Contact_Optimizer
::edit($params, $this->_preEditValues
);
880 if (!empty($params['image_URL'])) {
881 CRM_Contact_BAO_Contact
::processImageParams($params);
884 if (is_numeric(CRM_Utils_Array
::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
885 $params['current_employer'] = $params['current_employer_id'];
888 // don't carry current_employer_id field,
889 // since we don't want to directly update DAO object without
890 // handling related business logic ( eg related membership )
891 if (isset($params['current_employer_id'])) {
892 unset($params['current_employer_id']);
895 $params['contact_type'] = $this->_contactType
;
896 if (empty($params['contact_sub_type']) && $this->_isContactSubType
) {
897 $params['contact_sub_type'] = array($this->_contactSubType
);
900 if ($this->_contactId
) {
901 $params['contact_id'] = $this->_contactId
;
904 //make deceased date null when is_deceased = false
905 if ($this->_contactType
== 'Individual' && !empty($this->_editOptions
['Demographics']) && empty($params['is_deceased'])) {
906 $params['is_deceased'] = FALSE;
907 $params['deceased_date'] = NULL;
910 if (isset($params['contact_id'])) {
911 // process membership status for deceased contact
912 $deceasedParams = array(
913 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
914 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
915 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
917 $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
920 // action is taken depending upon the mode
921 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
922 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
925 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
928 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, TRUE);
931 //if subtype is set, send subtype as extend to validate subtype customfield
932 $customFieldExtends = (CRM_Utils_Array
::value('contact_sub_type', $params)) ?
$params['contact_sub_type'] : $params['contact_type'];
934 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
939 if ($this->_contactId
&& !empty($this->_oldSubtypes
)) {
940 CRM_Contact_BAO_ContactType
::deleteCustomSetForSubtypeMigration($this->_contactId
,
941 $params['contact_type'],
943 $params['contact_sub_type']
947 if (array_key_exists('CommunicationPreferences', $this->_editOptions
)) {
948 // this is a chekbox, so mark false if we dont get a POST value
949 $params['is_opt_out'] = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
952 // process shared contact address.
953 CRM_Contact_BAO_Contact_Utils
::processSharedAddress($params['address']);
955 if (!array_key_exists('TagsAndGroups', $this->_editOptions
) && !empty($params['group'])) {
956 unset($params['group']);
959 if (!empty($params['contact_id']) && ($this->_action
& CRM_Core_Action
::UPDATE
) && !empty($params['group'])) {
960 // figure out which all groups are intended to be removed
961 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($params['contact_id'], 'Added');
962 if (is_array($contactGroupList)) {
963 foreach ($contactGroupList as $key) {
964 if ((!array_key_exists($key['group_id'], $params['group']) ||
$params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
965 $params['group'][$key['group_id']] = -1;
971 // parse street address, CRM-5450
972 $parseStatusMsg = NULL;
973 if ($this->_parseStreetAddress
) {
974 $parseResult = self
::parseAddress($params);
975 $parseStatusMsg = self
::parseAddressStatusMsg($parseResult);
978 $blocks = array('email', 'phone', 'im', 'openid', 'address', 'website');
979 foreach ($blocks as $block) {
980 if (!empty($this->_preEditValues
[$block]) && is_array($this->_preEditValues
[$block])) {
981 foreach ($this->_preEditValues
[$block] as $count => $value) {
982 if (!empty($value['id'])) {
983 $params[$block][$count]['id'] = $value['id'];
984 $params[$block]['isIdSet'] = TRUE;
990 // Allow un-setting of location info, CRM-5969
991 $params['updateBlankLocInfo'] = TRUE;
993 $contact = CRM_Contact_BAO_Contact
::create($params, TRUE, FALSE, TRUE);
996 if ($this->_contactId
) {
997 $message = ts('%1 has been updated.', array(1 => $contact->display_name
));
1000 $message = ts('%1 has been created.', array(1 => $contact->display_name
));
1003 // set the contact ID
1004 $this->_contactId
= $contact->id
;
1006 if (array_key_exists('TagsAndGroups', $this->_editOptions
)) {
1007 //add contact to tags
1008 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1011 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1012 CRM_Core_Form_Tag
::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1016 if (!empty($parseStatusMsg)) {
1017 $message .= "<br />$parseStatusMsg";
1019 if (!empty($updateMembershipMsg)) {
1020 $message .= "<br />$updateMembershipMsg";
1023 $session = CRM_Core_Session
::singleton();
1024 $session->setStatus($message, ts('Contact Saved'), 'success');
1026 // add the recently viewed contact
1027 $recentOther = array();
1028 if (($session->get('userID') == $contact->id
) ||
1029 CRM_Contact_BAO_Contact_Permission
::allow($contact->id
, CRM_Core_Permission
::EDIT
)
1031 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id
);
1034 if (($session->get('userID') != $this->_contactId
) && CRM_Core_Permission
::check('delete contacts')) {
1035 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id
);
1038 CRM_Utils_Recent
::add($contact->display_name
,
1039 CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id
),
1041 $this->_contactType
,
1043 $contact->display_name
,
1047 // here we replace the user context with the url to view this contact
1048 $buttonName = $this->controller
->getButtonName();
1049 if ($buttonName == $this->getButtonName('upload', 'new')) {
1050 $contactSubTypes = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_contactSubType
));
1051 $resetStr = "reset=1&ct={$contact->contact_type}";
1052 $resetStr .= (count($contactSubTypes) == 1) ?
"&cst=" . array_pop($contactSubTypes) : '';
1053 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/add', $resetStr));
1056 $context = CRM_Utils_Request
::retrieve('context', 'String', $this);
1057 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
1058 //validate the qfKey
1059 $urlParams = 'reset=1&cid=' . $contact->id
;
1061 $urlParams .= "&context=$context";
1063 if (CRM_Utils_Rule
::qfKey($qfKey)) {
1064 $urlParams .= "&key=$qfKey";
1067 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view', $urlParams));
1070 // now invoke the post hook
1071 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1072 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
1075 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
1080 * Is there any real significant data in the hierarchical location array.
1082 * @param array $fields
1083 * The hierarchical value representation of this location.
1086 * true if data exists, false otherwise
1088 public static function blockDataExists(&$fields) {
1089 if (!is_array($fields)) {
1093 static $skipFields = array(
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 * That checks for duplicate contacts.
1134 * @param array $fields
1135 * Fields array which are submitted.
1137 * @param int $contactID
1139 * @param string $contactType
1142 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
1143 // if this is a forced save, ignore find duplicate rule
1144 if (empty($fields['_qf_Contact_upload_duplicate'])) {
1146 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $contactType);
1147 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
1150 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1152 $duplicateContactsLinks = '<div class="matching-contacts-found">';
1153 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
1154 'count' => count($contactLinks['rows']),
1155 'plural' => '%count matching contacts were found.<br />',
1157 if ($contactLinks['msg'] == 'view') {
1158 $duplicateContactsLinks .= ts('You can View the existing contact', array(
1159 'count' => count($contactLinks['rows']),
1160 'plural' => 'You can View the existing contacts',
1164 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array(
1165 'count' => count($contactLinks['rows']),
1166 'plural' => 'You can View or Edit the existing contacts',
1169 if ($contactLinks['msg'] == 'merge') {
1170 // We should also get a merge link if this is for an existing contact
1171 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1173 $duplicateContactsLinks .= '.';
1174 $duplicateContactsLinks .= '</div>';
1175 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1177 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
1179 $row .= ' <td class="matching-contacts-name"> ';
1180 $row .= $contactLinks['rows'][$i]['display_name'];
1182 $row .= ' <td class="matching-contacts-email"> ';
1183 $row .= $contactLinks['rows'][$i]['primary_email'];
1185 $row .= ' <td class="action-items"> ';
1186 $row .= $contactLinks['rows'][$i]['view'];
1187 $row .= $contactLinks['rows'][$i]['edit'];
1188 $row .= CRM_Utils_Array
::value('merge', $contactLinks['rows'][$i]);
1193 $duplicateContactsLinks .= $row . '</table>';
1194 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1196 $errors['_qf_default'] = $duplicateContactsLinks;
1198 // let smarty know that there are duplicates
1199 $template = CRM_Core_Smarty
::singleton();
1200 $template->assign('isDuplicate', 1);
1202 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
1203 // add a session message for no matching contacts
1204 CRM_Core_Session
::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1210 * Use the form name to create the tpl file name.
1214 public function getTemplateFileName() {
1215 if ($this->_contactSubType
) {
1216 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1217 $template = CRM_Core_Form
::getTemplate();
1218 if ($template->template_exists($templateFile)) {
1219 return $templateFile;
1222 return parent
::getTemplateFileName();
1226 * Parse all address blocks present in given params
1227 * and return parse result for all address blocks,
1228 * This function either parse street address in to child
1229 * elements or build street address from child elements.
1231 * @param array $params
1232 * of key value consist of address blocks.
1235 * as array of success/fails for each address block
1237 public function parseAddress(&$params) {
1238 $parseSuccess = $parsedFields = array();
1239 if (!is_array($params['address']) ||
1240 CRM_Utils_System
::isNull($params['address'])
1242 return $parseSuccess;
1245 foreach ($params['address'] as $instance => & $address) {
1246 $buildStreetAddress = FALSE;
1247 $parseFieldName = 'street_address';
1253 if (!empty($address[$fld])) {
1254 $parseFieldName = 'street_number';
1255 $buildStreetAddress = TRUE;
1260 // main parse string.
1261 $parseString = CRM_Utils_Array
::value($parseFieldName, $address);
1263 // parse address field.
1264 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($parseString);
1266 if ($buildStreetAddress) {
1267 //hack to ignore spaces between number and suffix.
1268 //here user gives input as street_number so it has to
1269 //be street_number and street_number_suffix, but
1270 //due to spaces though preg detect string as street_name
1271 //consider it as 'street_number_suffix'.
1272 $suffix = $parsedFields['street_number_suffix'];
1274 $suffix = $parsedFields['street_name'];
1276 $address['street_number_suffix'] = $suffix;
1277 $address['street_number'] = $parsedFields['street_number'];
1279 $streetAddress = NULL;
1282 'street_number_suffix',
1286 if (in_array($fld, array(
1290 $streetAddress .= ' ';
1292 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
1294 $address['street_address'] = trim($streetAddress);
1295 $parseSuccess[$instance] = TRUE;
1299 // consider address is automatically parseable,
1300 // when we should found street_number and street_name
1301 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
1305 // check for original street address string.
1306 if (empty($parseString)) {
1310 $parseSuccess[$instance] = $success;
1312 // we do not reset element values, but keep what we've parsed
1313 // in case of partial matches: CRM-8378
1315 // merge parse address in to main address block.
1316 $address = array_merge($address, $parsedFields);
1320 return $parseSuccess;
1324 * Check parse result and if some address block fails then this
1325 * function return the status message for all address blocks.
1327 * @param array $parseResult
1328 * An array of address blk instance and its status.
1330 * @return null|string
1331 * $statusMsg string status message for all address blocks.
1333 public static function parseAddressStatusMsg($parseResult) {
1335 if (!is_array($parseResult) ||
empty($parseResult)) {
1339 $parseFails = array();
1340 foreach ($parseResult as $instance => $success) {
1342 $parseFails[] = self
::ordinalNumber($instance);
1346 if (!empty($parseFails)) {
1347 $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.",
1348 array(1 => implode(', ', $parseFails))
1356 * Convert normal number to ordinal number format.
1357 * like 1 => 1st, 2 => 2nd and so on...
1359 * @param int $number
1360 * number to convert in to ordinal number.
1363 * ordinal number for given number.
1365 public static function ordinalNumber($number) {
1366 if (empty($number)) {
1371 switch (floor($number / 10) %
10) {
1374 switch ($number %
10) {
1389 return "$number$str";
1393 * Update membership status to deceased.
1394 * function return the status message for updated membership.
1396 * @param array $deceasedParams
1397 * having contact id and deceased value.
1399 * @return null|string
1400 * $updateMembershipMsg string status message for updated membership.
1402 public function updateMembershipStatus($deceasedParams) {
1403 $updateMembershipMsg = NULL;
1404 $contactId = CRM_Utils_Array
::value('contact_id', $deceasedParams);
1405 $deceasedDate = CRM_Utils_Array
::value('deceased_date', $deceasedParams);
1407 // process to set membership status to deceased for both active/inactive membership
1409 $this->_contactType
== 'Individual' && !empty($deceasedParams['is_deceased'])
1412 $session = CRM_Core_Session
::singleton();
1413 $userId = $session->get('userID');
1415 $userId = $contactId;
1418 // get deceased status id
1419 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1420 $deceasedStatusId = array_search('Deceased', $allStatus);
1421 if (!$deceasedStatusId) {
1422 return $updateMembershipMsg;
1426 if ($deceasedDate && strtotime($deceasedDate) > $today) {
1427 return $updateMembershipMsg;
1430 // get non deceased membership
1431 $dao = new CRM_Member_DAO_Membership();
1432 $dao->contact_id
= $contactId;
1433 $dao->whereAdd("status_id != $deceasedStatusId");
1435 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1436 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1438 while ($dao->fetch()) {
1439 // update status to deceased (for both active/inactive membership )
1440 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
1441 'status_id', $deceasedStatusId
1444 // add membership log
1445 $membershipLog = array(
1446 'membership_id' => $dao->id
,
1447 'status_id' => $deceasedStatusId,
1448 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1449 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1450 'modified_id' => $userId,
1451 'modified_date' => date('Ymd'),
1452 'membership_type_id' => $dao->membership_type_id
,
1453 'max_related' => $dao->max_related
,
1456 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1458 //create activity when membership status is changed
1459 $activityParam = array(
1460 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
1461 'source_contact_id' => $userId,
1462 'target_contact_id' => $dao->contact_id
,
1463 'source_record_id' => $dao->id
,
1464 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
1468 'activity_date_time' => date('Y-m-d H:i:s'),
1470 'is_current_revision' => 1,
1473 $activityResult = civicrm_api('activity', 'create', $activityParam);
1480 $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
1481 array(1 => $memCount)
1486 return $updateMembershipMsg;