3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for custom data
21 * It delegates the work to lower level subclasses and integrates the changes
22 * back in. It also uses a lot of functionality with the CRM API's, so any change
23 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
26 class CRM_Profile_Form
extends CRM_Core_Form
{
35 protected $_skipPermission = FALSE;
38 * The contact id that we are editing.
45 * The group id that we are editing.
53 * Details of the UFGroup used on this page
55 protected $_ufGroup = ['name' => 'unknown'];
58 * The group id that we are passing in url.
65 * Name of button for saving matching contacts.
68 protected $_duplicateButtonName;
70 * The title of the category we are editing.
77 * The fields needed to build this form.
84 * store contact details.
91 * Do we allow updates of the contact.
95 public $_isUpdateDupe = 0;
98 * Dedupe using a specific rule (CRM-6131).
99 * Not currently exposed in profile settings, but can be set in a buildForm hook.
102 public $_ruleGroupID = NULL;
104 protected $_isPermissionedChecksum = FALSE;
107 * THe context from which we came from, allows us to go there if redirect not set.
114 * THe contact type for registration case.
118 protected $_ctype = NULL;
121 * Store profile ids if multiple profile ids are passed using comma separated.
122 * Currently lets implement this functionality only for dialog mode.
125 protected $_profileIds = [];
128 * Contact profile having activity fields?
132 protected $_isContactActivityProfile = FALSE;
135 * Activity Id connected to the profile.
139 protected $_activityId = NULL;
142 protected $_multiRecordFields = NULL;
144 protected $_recordId = NULL;
147 * Action for multi record profile (create/edit/delete).
151 protected $_multiRecord = NULL;
153 protected $_multiRecordProfile = FALSE;
155 protected $_recordExists = TRUE;
157 protected $_customGroupTitle = NULL;
159 protected $_deleteButtonName = NULL;
161 protected $_customGroupId = NULL;
163 protected $_currentUserID = NULL;
164 protected $_session = NULL;
167 * Check for any duplicates.
169 * Depending on form settings & usage scenario we potentially use the found id,
170 * create links to found ids or add an error.
172 * @param array $errors
173 * @param array $fields
174 * @param CRM_Profile_Form $form
178 protected static function handleDuplicateChecking(&$errors, $fields, $form) {
179 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
184 // for edit mode we need to allow our own record to be a dupe match!
185 $exceptions = [CRM_Core_Session
::singleton()->get('userID')];
187 $contactType = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
188 // If all profile fields is of Contact Type then consider
189 // profile is of Individual type(default).
191 $contactType = 'Individual';
194 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
195 $fields, $contactType,
196 ($form->_context
=== 'dialog' ?
'Supervised' : 'Unsupervised'),
202 if ($form->_isUpdateDupe
== 2) {
203 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
205 elseif ($form->_isUpdateDupe
== 1) {
206 $form->_id
= $ids[0];
209 if ($form->_context
== 'dialog') {
210 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
212 $duplicateContactsLinks = '<div class="matching-contacts-found">';
213 $duplicateContactsLinks .= ts('One matching contact was found. ', [
214 'count' => count($contactLinks['rows']),
215 'plural' => '%count matching contacts were found.<br />',
217 if ($contactLinks['msg'] == 'view') {
218 $duplicateContactsLinks .= ts('You can View the existing contact.', [
219 'count' => count($contactLinks['rows']),
220 'plural' => 'You can View the existing contacts.',
224 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
225 'count' => count($contactLinks['rows']),
226 'plural' => 'You can View or Edit the existing contacts.',
229 $duplicateContactsLinks .= '</div>';
230 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
232 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
234 $row .= ' <td class="matching-contacts-name"> ';
235 $row .= $contactLinks['rows'][$i]['display_name'];
237 $row .= ' <td class="matching-contacts-email"> ';
238 $row .= $contactLinks['rows'][$i]['primary_email'];
240 $row .= ' <td class="action-items"> ';
241 $row .= $contactLinks['rows'][$i]['view'] . ' ';
242 $row .= $contactLinks['rows'][$i]['edit'];
247 $duplicateContactsLinks .= $row . '</table>';
248 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
250 $errors['_qf_default'] = $duplicateContactsLinks;
252 // let smarty know that there are duplicates
253 $template = CRM_Core_Smarty
::singleton();
254 $template->assign('isDuplicate', 1);
257 $errors['_qf_default'] = ts('A record already exists with the same information.');
265 * Explicitly declare the entity api name.
267 public function getDefaultEntity() {
272 * Get the active UFGroups (profiles) on this form
273 * Many forms load one or more UFGroups (profiles).
274 * This provides a standard function to retrieve the IDs of those profiles from the form
275 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
277 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
281 public function getUFGroupIDs() {
282 return [$this->_gid
];
286 * Are we using the profile in create mode?
290 public function getIsCreateMode() {
291 return ($this->_mode
== self
::MODE_CREATE
);
295 * Pre processing work done here.
297 * gets session variables for table name, id of entity in table, type of entity and stores them.
299 public function preProcess() {
300 $this->_id
= $this->get('id');
301 $this->_profileIds
= $this->get('profileIds');
302 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
303 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
305 //unset from session when $_GET doesn't have it
306 //except when the form is submitted
308 if (!array_key_exists('multiRecord', $_GET)) {
309 $this->set('multiRecord', NULL);
311 if (!array_key_exists('recordId', $_GET)) {
312 $this->set('recordId', NULL);
316 $this->_currentUserID
= CRM_Core_Session
::singleton()->get('userID');
318 if ($this->_mode
== self
::MODE_EDIT
) {
319 //specifies the action being done on a multi record field
320 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
321 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
322 if ($this->_multiRecord
) {
323 $this->set('multiRecord', $this->_multiRecord
);
326 if ($this->_multiRecord
&&
327 !in_array($this->_multiRecord
, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
])
329 CRM_Core_Error
::statusBounce(ts('Proper action not specified for this custom value record profile'));
332 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
334 $gids = explode(',', (CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0) ??
''));
336 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
338 foreach ($gids as $pfId) {
339 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
343 // check if we are rendering mixed profiles
344 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
345 CRM_Core_Error
::statusBounce(ts('You cannot combine profiles of multiple types.'));
348 // for now consider 1'st profile as primary profile and validate it
349 // i.e check for profile type etc.
350 // FIX ME: validations for other than primary
351 $this->_gid
= $this->_profileIds
[0];
352 $this->set('gid', $this->_gid
);
353 $this->set('profileIds', $this->_profileIds
);
357 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
358 $this->set('gid', $this->_gid
);
361 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
362 if (is_numeric($this->_activityId
)) {
363 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
364 if ($latestRevisionId) {
365 $this->_activityId
= $latestRevisionId;
368 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
370 //get values for ufGroupName and dupe update.
372 $dao = new CRM_Core_DAO_UFGroup();
373 $dao->id
= $this->_gid
;
374 if ($dao->find(TRUE)) {
375 $this->_isUpdateDupe
= $dao->is_update_dupe
;
376 $this->_ufGroup
= (array) $dao;
379 if (empty($this->_ufGroup
['is_active'])) {
380 CRM_Core_Error
::statusBounce(ts('The requested profile (gid=%1) is inactive or does not exist.', [
385 $this->assign('ufGroupName', $this->_ufGroup
['name']);
387 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
389 // if we don't have a gid use the default, else just use that specific gid
390 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
391 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
392 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
394 elseif ($this->_mode
== self
::MODE_SEARCH
) {
395 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
396 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
400 $this->_skipPermission
,
401 CRM_Core_Permission
::SEARCH
405 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
408 $this->_skipPermission
,
410 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
412 $multiRecordFieldListing = FALSE;
413 //using selector for listing of multi-record fields
414 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
415 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
417 if ($this->_multiRecord
) {
418 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
419 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
422 $this->_recordId
= NULL;
423 $this->set('recordId', NULL);
425 //record id is necessary for _multiRecord view and update/edit action
426 if (!$this->_recordId
427 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
429 CRM_Core_Error
::statusBounce(ts('The requested Profile (gid=%1) requires record id while performing this action',
433 elseif (empty($this->_multiRecordFields
)) {
434 CRM_Core_Error
::statusBounce(ts('No Multi-Record Fields configured for this profile (gid=%1)',
439 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
440 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles([$fieldId]);
441 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
442 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
444 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
445 //record exists check
446 foreach ($this->_multiRecordFields
as $key => $field) {
447 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
449 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
451 if (array_key_exists($this->_recordId
, $getValues)) {
452 $this->_recordExists
= TRUE;
455 $this->_recordExists
= FALSE;
456 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
457 CRM_Core_Session
::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', [1 => $this->_recordId
]), ts('Record doesnot exist'), 'alert');
461 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
462 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
463 if ($this->_maxRecordLimit
) {
464 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
469 elseif (!empty($this->_multiRecordFields
)
470 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, [
471 CRM_Core_Action
::DELETE
,
472 CRM_Core_Action
::UPDATE
,
475 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
476 //multi-record listing page
477 $multiRecordFieldListing = TRUE;
478 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
479 $cs = $this->get('cs');
480 $page->set('pageCheckSum', $cs);
481 $page->set('contactId', $this->_id
);
482 $page->set('profileId', $this->_gid
);
483 $page->set('action', CRM_Core_Action
::BROWSE
);
484 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
488 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
490 // is profile double-opt in?
491 if (!empty($this->_fields
['group']) &&
492 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
495 foreach ($this->_fields
as $name => $values) {
496 if (substr($name, 0, 6) == 'email-') {
502 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
503 CRM_Core_Session
::singleton()->setStatus($status);
507 //transferring all the multi-record custom fields in _fields
508 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
509 $this->_fields
= $this->_multiRecordFields
;
510 $this->_multiRecordProfile
= TRUE;
512 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
513 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
514 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
518 if (!is_array($this->_fields
)) {
519 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
520 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
525 * Set default values for the form. Note that in edit/view mode
526 * the default values are retrieved from the database
529 public function setDefaultsValues() {
530 $this->_defaults
= [];
531 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
535 if ($this->_mode
!= self
::MODE_SEARCH
) {
536 // set default values for country / state to start with
537 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
540 if ($this->_id
&& !$this->_multiRecordProfile
) {
541 if ($this->_isContactActivityProfile
) {
542 $contactFields = $activityFields = [];
543 foreach ($this->_fields
as $fieldName => $field) {
544 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
545 $activityFields[$fieldName] = $field;
548 $contactFields[$fieldName] = $field;
552 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
553 if ($this->_activityId
) {
554 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
558 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
562 //set custom field defaults
563 if ($this->_multiRecordProfile
) {
564 foreach ($this->_multiRecordFields
as $key => $field) {
565 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
569 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
570 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
571 if ($this->_recordExists
== TRUE) {
572 $defaultValues = $defaultValues[$this->_recordId
];
575 $defaultValues = NULL;
579 if (!empty($defaultValues)) {
580 foreach ($defaultValues as $key => $value) {
581 $name = "custom_{$key}";
582 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
583 if ($htmlType != 'File') {
585 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
594 $this->_defaults
[$name] = "";
598 if ($htmlType == 'File') {
599 $entityId = $this->_id
;
600 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
603 $entityId = $this->_activityId
;
608 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key, $value);
612 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
614 $deleteExtra = ts("Are you sure you want to delete attached file?");
615 $fileId = $url['file_id'];
616 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId);
617 $deleteURL = CRM_Utils_System
::url('civicrm/file',
618 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
620 $text = ts("Delete Attached File");
621 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
623 // also delete the required rule that we've set on the form element
624 $this->removeFileRequiredRules($name);
631 foreach ($this->_fields
as $name => $field) {
632 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
633 $htmlType = $field['html_type'];
634 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
635 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
637 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
645 if ($htmlType == 'File') {
646 $entityId = $this->_id
;
647 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
648 $entityId = $this->_activityId
;
650 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
653 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
655 $deleteExtra = ts("Are you sure you want to delete attached file?");
656 $fileId = $url['file_id'];
657 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
658 $deleteURL = CRM_Utils_System
::url('civicrm/file',
659 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
661 $text = ts("Delete Attached File");
662 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
664 // also delete the required rule that we've set on the form element
665 $this->removeFileRequiredRules($field['name']);
671 if (isset($customFiles)) {
672 $this->assign('customFiles', $customFiles);
675 if ($this->_multiRecordProfile
) {
676 $this->setDefaults($this->_defaults
);
680 if (!empty($this->_defaults
['image_URL'])) {
681 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
682 $this->removeFileRequiredRules('image_URL');
685 $this->setDefaults($this->_defaults
);
689 * Build the form object.
692 public function buildQuickForm(): void
{
693 $this->add('hidden', 'gid', $this->_gid
);
694 $this->assign('deleteRecord', $this->isDeleteMode());
696 switch ($this->_mode
) {
697 case self
::MODE_CREATE
:
698 case self
::MODE_EDIT
:
699 case self
::MODE_REGISTER
:
700 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
703 case self
::MODE_SEARCH
:
704 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
710 //lets have single status message, CRM-4363
712 $statusMessage = NULL;
713 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
717 if ($this->isDeleteMode()) {
718 if (!$this->_recordExists
) {
719 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId
]), ts('Record doesnot exists'), 'alert');
724 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
726 // we should not allow component and mix profiles in search mode
727 if ($this->_mode
!= self
::MODE_REGISTER
) {
728 //check for mix profile fields (eg: individual + other contact type)
729 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
730 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
731 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
732 if (!empty($errors)) {
733 $statusMessage = array_pop($errors);
738 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
743 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
746 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
747 $contactType = $contactTypes[0];
749 array_shift($contactTypes);
750 $contactSubtypes = $contactTypes;
752 $profileSubType = FALSE;
753 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
754 $profileSubType = $profileType;
755 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
759 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
760 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
761 ($profileType != $contactType))
764 if (!$statusMessage) {
765 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
766 [1 => $profileSubType ?
$profileSubType : $profileType]);
774 ["Membership", "Participant", "Contribution"]
778 if (!$statusMessage) {
779 $statusMessage = ts('Profile is not configured for the selected action.');
784 //lets have single status message,
785 $this->assign('statusMessage', $statusMessage);
790 $this->assign('id', $this->_id
);
791 $this->assign('mode', $this->_mode
);
792 $this->assign('action', $this->_action
);
793 $this->assign('fields', $this->_fields
);
794 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
796 // should we restrict what we display
798 if ($this->_mode
== self
::MODE_EDIT
) {
800 // show all fields that are visible:
801 // if we are a admin OR the same user OR acl-user with access to the profile
802 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
804 CRM_Core_Permission
::check('administer users') ||
805 $this->_id
== $this->_currentUserID ||
806 $this->_isPermissionedChecksum ||
810 CRM_Core_Permission
::EDIT
,
813 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
821 // if false, user is not logged-in.
823 if (!$this->_currentUserID
) {
824 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
825 $primaryLocationType = $defaultLocationType->id
;
828 $this->assign('anonUser', $anonUser);
830 $emailPresent = FALSE;
832 // add the form elements
833 foreach ($this->_fields
as $name => $field) {
834 // make sure that there is enough permission to expose this field
835 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
836 unset($this->_fields
[$name]);
840 // since the CMS manages the email field, suppress the email display if in
841 // register mode which occur within the CMS form
842 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
843 unset($this->_fields
[$name]);
847 [$prefixName, $index] = CRM_Utils_System
::explode('-', $name, 2);
849 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
851 if ($field['add_to_group_id']) {
852 $addToGroupId = $field['add_to_group_id'];
855 if (($name == 'email-Primary') ||
($name == 'email-' . ($primaryLocationType ??
""))) {
856 $emailPresent = TRUE;
857 $this->_mail
= $name;
861 if ($this->_mode
== self
::MODE_CREATE
) {
863 $dao = new CRM_Core_DAO_UFGroup();
864 $dao->id
= $this->_gid
;
866 $dao->addSelect('is_update_dupe');
867 if ($dao->find(TRUE)) {
868 if ($dao->is_update_dupe
) {
869 $this->_isUpdateDupe
= $dao->is_update_dupe
;
875 if ($this->_mode
!= self
::MODE_SEARCH
) {
876 if (isset($addToGroupId)) {
877 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
881 //let's do set defaults for the profile
882 $this->setDefaultsValues();
884 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
886 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
887 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
890 $this->assign('showCMS', FALSE);
893 $this->assign('groupId', $this->_gid
);
895 // if view mode pls freeze it with the done button.
896 if ($this->_action
& CRM_Core_Action
::VIEW
) {
900 if ($this->_context
== 'dialog') {
903 $this->_duplicateButtonName
,
904 ts('Save Matching Contact'),
907 'class' => 'crm-button',
914 * Validate profile and provided activity Id.
916 * @param int $activityId
917 * @param int $contactId
922 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
925 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
929 $activityDetails = [];
930 $activityParams = ['id' => $activityId];
931 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
933 if (empty($activityDetails)) {
934 $errors[] = ts('Invalid Activity Id (aid).');
938 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
940 if ((!empty($profileActivityTypes['Activity']) &&
941 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
943 (!in_array($contactId, $activityDetails['assignee_contact']) &&
944 !in_array($contactId, $activityDetails['target_contact'])
947 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
956 * @param array $fields
957 * The input form values.
958 * @param array $files
959 * The uploaded files if any.
960 * @param CRM_Core_Form $form
964 * true if no errors, else array of errors
966 public static function formRule($fields, $files, $form) {
967 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
969 // if no values, return
970 if (empty($fields)) {
977 // hack we use a -1 in options to indicate that its registration
978 // ... and I can't remove that comment because even though it's clear as mud
979 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
980 // as to what it means....
982 // @todo - wonder if it ever occurred to someone that if they didn't document this param
983 // it might not be crystal clear why we have it....
984 $form->_isUpdateDupe
= 1;
987 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
991 // don't check for duplicates during registration validation: CRM-375
992 if (!$register && !array_key_exists('_qf_Edit_upload_duplicate', $fields)) {
994 if (!empty($fields['email-Primary'])) {
995 $fields['email'] = $fields['email-Primary'] ??
NULL;
999 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1000 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1004 self
::handleDuplicateChecking($errors, $fields, $form);
1008 foreach ($fields as $key => $value) {
1009 [$fieldName, $locTypeId, $phoneTypeId] = CRM_Utils_System
::explode('-', $key, 3);
1010 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1011 // Validate Country - State list
1012 $countryId = $fields["country-{$locTypeId}"];
1013 $stateProvinceId = $value;
1015 if ($stateProvinceId && $countryId) {
1016 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1017 $stateProvinceDAO->id
= $stateProvinceId;
1018 $stateProvinceDAO->find(TRUE);
1020 if ($stateProvinceDAO->country_id
!= $countryId) {
1021 // country mismatch hence display error
1022 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1023 $countries = CRM_Core_PseudoConstant
::country();
1024 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1029 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1030 // Validate County - State list
1031 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1034 if ($countyId && $stateProvinceId) {
1035 $countyDAO = new CRM_Core_DAO_County();
1036 $countyDAO->id
= $countyId;
1037 $countyDAO->find(TRUE);
1039 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1040 // state province mismatch hence display error
1041 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1042 $counties = CRM_Core_PseudoConstant
::county();
1043 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1048 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1049 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1050 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1051 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1052 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1053 [1 => ucwords(str_replace('_', ' ', $greeting))]
1059 return empty($errors) ?
TRUE : $errors;
1063 * Process the user submitted custom data values.
1066 public function postProcess() {
1067 $params = $this->controller
->exportValues($this->_name
);
1069 //if the delete record button is clicked
1070 if ($this->_deleteButtonName
) {
1071 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1072 $filterParams['id'] = $this->_customGroupId
;
1073 $returnProperties = ['is_multiple', 'table_name'];
1074 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1075 if (!empty($returnValues['is_multiple'])) {
1076 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1077 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1079 1 => [$this->_recordId
, 'Integer'],
1080 2 => [$this->_id
, 'Integer'],
1082 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1083 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1089 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1090 if (!empty($params['image_URL'])) {
1091 CRM_Contact_BAO_Contact
::processImageParams($params);
1095 'addressee' => 'addressee_id',
1096 'email_greeting' => 'email_greeting_id',
1097 'postal_greeting' => 'postal_greeting_id',
1102 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1105 $details = $contactDetails[$this->_id
];
1107 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1108 !empty($details['postal_greeting_id'])
1112 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1113 //Though Profile type is contact we need
1114 //Individual/Household/Organization for setting Greetings.
1115 if ($profileType == 'Contact') {
1116 $profileType = 'Individual';
1117 //if we editing Household/Organization.
1119 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1122 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1123 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1126 foreach ($greetingTypes as $key => $value) {
1127 if (!array_key_exists($key, $params)) {
1128 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1133 $transaction = new CRM_Core_Transaction();
1135 //used to send subscribe mail to the group which user want.
1136 //if the profile double option in is enabled
1140 foreach ($params as $name => $values) {
1141 if (substr($name, 0, 6) == 'email-') {
1142 $result['email'] = $values;
1146 //array of group id, subscribed by contact
1148 if (!empty($params['group']) &&
1149 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1151 $groupSubscribed = [];
1152 if (!empty($result['email'])) {
1154 $contactGroups = new CRM_Contact_DAO_GroupContact();
1155 $contactGroups->contact_id
= $this->_id
;
1156 $contactGroups->status
= 'Added';
1157 $contactGroups->find();
1159 while ($contactGroups->fetch()) {
1160 $contactGroup[] = $contactGroups->group_id
;
1161 $groupSubscribed[$contactGroups->group_id
] = 1;
1164 foreach ($params['group'] as $key => $val) {
1166 unset($params['group'][$key]);
1169 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1170 $key, 'group_type', 'id'
1172 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1173 substr($groupTypes, 1, -1)
1175 //filter group of mailing type and unset it from params
1176 if (in_array(2, $groupType)) {
1177 //if group is already subscribed , ignore it
1178 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1179 if (!isset($groupExist)) {
1180 $mailingType[] = $key;
1181 unset($params['group'][$key]);
1188 $addToGroupId = $this->_ufGroup
['add_to_group_id'] ??
NULL;
1189 if (!empty($addToGroupId)) {
1190 //run same check whether group is a mailing list
1191 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1192 $addToGroupId, 'group_type', 'id'
1194 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1195 substr($groupTypes, 1, -1)
1197 //filter group of mailing type and unset it from params
1198 if (in_array(2, $groupType) && !empty($result['email']) &&
1199 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1201 if (!count($contactGroup)) {
1202 //array of group id, subscribed by contact
1205 $contactGroups = new CRM_Contact_DAO_GroupContact();
1206 $contactGroups->contact_id
= $this->_id
;
1207 $contactGroups->status
= 'Added';
1208 $contactGroups->find();
1210 while ($contactGroups->fetch()) {
1211 $contactGroup[] = $contactGroups->group_id
;
1212 $groupSubscribed[$contactGroups->group_id
] = 1;
1216 //if group is already subscribed , ignore it
1217 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1218 if (!isset($groupExist)) {
1219 $mailingType[] = $addToGroupId;
1220 $addToGroupId = NULL;
1224 // since we are directly adding contact to group lets unset it from mailing
1225 if ($key = array_search($addToGroupId, $mailingType)) {
1226 unset($mailingType[$key]);
1232 $params['group'] = $groupSubscribed;
1235 // commenting below code, since we potentially
1236 // triggered maximum name field formatting cases during CRM-4430.
1238 // $params['preserveDBName'] = true;
1240 $profileFields = $this->_fields
;
1241 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1242 $profileFields = $activityParams = [];
1243 foreach ($this->_fields
as $fieldName => $field) {
1244 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1245 if (isset($params[$fieldName])) {
1246 $activityParams[$fieldName] = $params[$fieldName];
1248 if (isset($params['activity_date_time'])) {
1249 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1251 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1252 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1256 $profileFields[$fieldName] = $field;
1260 if (!empty($activityParams)) {
1261 $activityParams['version'] = 3;
1262 $activityParams['id'] = $this->_activityId
;
1263 $activityParams['skipRecentView'] = TRUE;
1264 civicrm_api('Activity', 'create', $activityParams);
1268 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1269 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1272 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1282 //mailing type group
1283 if (!empty($mailingType)) {
1284 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1286 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1291 $ufGroups[$this->_gid
] = 1;
1293 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1294 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1297 foreach ($ufGroups as $gId => $val) {
1298 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1299 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1300 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1304 //create CMS user (if CMS user option is selected in profile)
1305 if (!empty($params['cms_create_account']) &&
1306 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1308 $params['contactID'] = $this->_id
;
1309 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1310 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1311 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1312 $transaction->rollback();
1313 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1314 'reset=1&gid=' . $this->_gid
1319 $transaction->commit();
1323 * Check template file exists.
1325 * @param string|null $suffix
1327 * @return string|null
1328 * Template file path, else null
1330 public function checkTemplateFileExists($suffix = NULL) {
1332 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1333 $template = CRM_Core_Form
::getTemplate();
1334 if ($template->template_exists($templateFile)) {
1335 return $templateFile;
1338 // lets see if we have customized by name
1339 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1341 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1342 if ($template->template_exists($templateFile)) {
1343 return $templateFile;
1351 * Use the form name to create the tpl file name.
1355 public function getTemplateFileName() {
1356 $fileName = $this->checkTemplateFileExists();
1357 return $fileName ?
$fileName : parent
::getTemplateFileName();
1361 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1362 * i.e. we dont override
1366 public function overrideExtraTemplateFileName() {
1367 $fileName = $this->checkTemplateFileExists('extra.');
1368 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();
1372 * @return int|string
1374 private function isDeleteMode() {
1375 return ($this->_multiRecord
& CRM_Core_Action
::DELETE
);