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
20 * This class generates form components for custom data
22 * It delegates the work to lower level subclasses and integrates the changes
23 * back in. It also uses a lot of functionality with the CRM API's, so any change
24 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
27 class CRM_Profile_Form
extends CRM_Core_Form
{
36 protected $_skipPermission = FALSE;
39 * The contact id that we are editing.
46 * The group id that we are editing.
54 * Details of the UFGroup used on this page
56 protected $_ufGroup = ['name' => 'unknown'];
59 * The group id that we are passing in url.
66 * Name of button for saving matching contacts.
69 protected $_duplicateButtonName;
71 * The title of the category we are editing.
78 * The fields needed to build this form.
85 * store contact details.
92 * Do we allow updates of the contact.
96 public $_isUpdateDupe = 0;
99 * Dedupe using a specific rule (CRM-6131).
100 * Not currently exposed in profile settings, but can be set in a buildForm hook.
103 public $_ruleGroupID = NULL;
105 public $_isAddCaptcha = FALSE;
107 protected $_isPermissionedChecksum = FALSE;
110 * THe context from which we came from, allows us to go there if redirect not set.
117 * THe contact type for registration case.
121 protected $_ctype = NULL;
124 * Store profile ids if multiple profile ids are passed using comma separated.
125 * Currently lets implement this functionality only for dialog mode.
128 protected $_profileIds = [];
131 * Contact profile having activity fields?
135 protected $_isContactActivityProfile = FALSE;
138 * Activity Id connected to the profile.
142 protected $_activityId = NULL;
145 protected $_multiRecordFields = NULL;
147 protected $_recordId = NULL;
150 * Action for multi record profile (create/edit/delete).
154 protected $_multiRecord = NULL;
156 protected $_multiRecordProfile = FALSE;
158 protected $_recordExists = TRUE;
160 protected $_customGroupTitle = NULL;
162 protected $_deleteButtonName = NULL;
164 protected $_customGroupId = NULL;
166 protected $_currentUserID = NULL;
167 protected $_session = NULL;
170 * Check for any duplicates.
172 * Depending on form settings & usage scenario we potentially use the found id,
173 * create links to found ids or add an error.
175 * @param array $errors
176 * @param array $fields
177 * @param CRM_Profile_Form $form
181 protected static function handleDuplicateChecking(&$errors, $fields, $form) {
182 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
187 // for edit mode we need to allow our own record to be a dupe match!
188 $exceptions = [CRM_Core_Session
::singleton()->get('userID')];
190 $contactType = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
191 // If all profile fields is of Contact Type then consider
192 // profile is of Individual type(default).
194 $contactType = 'Individual';
197 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
198 $fields, $contactType,
199 ($form->_context
=== 'dialog' ?
'Supervised' : 'Unsupervised'),
205 if ($form->_isUpdateDupe
== 2) {
206 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
208 elseif ($form->_isUpdateDupe
== 1) {
209 $form->_id
= $ids[0];
212 if ($form->_context
== 'dialog') {
213 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
215 $duplicateContactsLinks = '<div class="matching-contacts-found">';
216 $duplicateContactsLinks .= ts('One matching contact was found. ', [
217 'count' => count($contactLinks['rows']),
218 'plural' => '%count matching contacts were found.<br />',
220 if ($contactLinks['msg'] == 'view') {
221 $duplicateContactsLinks .= ts('You can View the existing contact.', [
222 'count' => count($contactLinks['rows']),
223 'plural' => 'You can View the existing contacts.',
227 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
228 'count' => count($contactLinks['rows']),
229 'plural' => 'You can View or Edit the existing contacts.',
232 $duplicateContactsLinks .= '</div>';
233 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
235 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
237 $row .= ' <td class="matching-contacts-name"> ';
238 $row .= $contactLinks['rows'][$i]['display_name'];
240 $row .= ' <td class="matching-contacts-email"> ';
241 $row .= $contactLinks['rows'][$i]['primary_email'];
243 $row .= ' <td class="action-items"> ';
244 $row .= $contactLinks['rows'][$i]['view'] . ' ';
245 $row .= $contactLinks['rows'][$i]['edit'];
250 $duplicateContactsLinks .= $row . '</table>';
251 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
253 $errors['_qf_default'] = $duplicateContactsLinks;
255 // let smarty know that there are duplicates
256 $template = CRM_Core_Smarty
::singleton();
257 $template->assign('isDuplicate', 1);
260 $errors['_qf_default'] = ts('A record already exists with the same information.');
268 * Explicitly declare the entity api name.
270 public function getDefaultEntity() {
275 * Pre processing work done here.
277 * gets session variables for table name, id of entity in table, type of entity and stores them.
279 public function preProcess() {
280 $this->_id
= $this->get('id');
281 $this->_profileIds
= $this->get('profileIds');
282 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
283 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
285 //unset from session when $_GET doesn't have it
286 //except when the form is submitted
288 if (!array_key_exists('multiRecord', $_GET)) {
289 $this->set('multiRecord', NULL);
291 if (!array_key_exists('recordId', $_GET)) {
292 $this->set('recordId', NULL);
296 $this->_currentUserID
= CRM_Core_Session
::singleton()->get('userID');
298 if ($this->_mode
== self
::MODE_EDIT
) {
299 //specifies the action being done on a multi record field
300 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
301 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
302 if ($this->_multiRecord
) {
303 $this->set('multiRecord', $this->_multiRecord
);
306 if ($this->_multiRecord
&&
307 !in_array($this->_multiRecord
, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
])
309 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
312 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
314 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0));
316 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
318 foreach ($gids as $pfId) {
319 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
323 // check if we are rendering mixed profiles
324 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
325 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
328 // for now consider 1'st profile as primary profile and validate it
329 // i.e check for profile type etc.
330 // FIX ME: validations for other than primary
331 $this->_gid
= $this->_profileIds
[0];
332 $this->set('gid', $this->_gid
);
333 $this->set('profileIds', $this->_profileIds
);
337 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
338 $this->set('gid', $this->_gid
);
341 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
342 if (is_numeric($this->_activityId
)) {
343 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
344 if ($latestRevisionId) {
345 $this->_activityId
= $latestRevisionId;
348 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
350 //get values for ufGroupName, captcha and dupe update.
352 $dao = new CRM_Core_DAO_UFGroup();
353 $dao->id
= $this->_gid
;
354 if ($dao->find(TRUE)) {
355 $this->_isUpdateDupe
= $dao->is_update_dupe
;
356 $this->_isAddCaptcha
= $dao->add_captcha
;
357 $this->_ufGroup
= (array) $dao;
360 if (empty($this->_ufGroup
['is_active'])) {
361 CRM_Core_Error
::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', [
366 $this->assign('ufGroupName', $this->_ufGroup
['name']);
368 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
370 // if we don't have a gid use the default, else just use that specific gid
371 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
372 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
373 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
375 elseif ($this->_mode
== self
::MODE_SEARCH
) {
376 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
377 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
381 $this->_skipPermission
,
382 CRM_Core_Permission
::SEARCH
386 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
389 $this->_skipPermission
,
391 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
393 $multiRecordFieldListing = FALSE;
394 //using selector for listing of multi-record fields
395 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
396 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
398 if ($this->_multiRecord
) {
399 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
400 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
403 $this->_recordId
= NULL;
404 $this->set('recordId', NULL);
406 //record id is necessary for _multiRecord view and update/edit action
407 if (!$this->_recordId
408 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
410 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
414 elseif (empty($this->_multiRecordFields
)) {
415 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
420 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
421 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles([$fieldId]);
422 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
423 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
425 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
426 //record exists check
427 foreach ($this->_multiRecordFields
as $key => $field) {
428 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
430 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
432 if (array_key_exists($this->_recordId
, $getValues)) {
433 $this->_recordExists
= TRUE;
436 $this->_recordExists
= FALSE;
437 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
438 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');
442 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
443 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
444 if ($this->_maxRecordLimit
) {
445 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
450 elseif (!empty($this->_multiRecordFields
)
451 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, [
452 CRM_Core_Action
::DELETE
,
453 CRM_Core_Action
::UPDATE
,
456 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
457 //multi-record listing page
458 $multiRecordFieldListing = TRUE;
459 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
460 $cs = $this->get('cs');
461 $page->set('pageCheckSum', $cs);
462 $page->set('contactId', $this->_id
);
463 $page->set('profileId', $this->_gid
);
464 $page->set('action', CRM_Core_Action
::BROWSE
);
465 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
469 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
471 // is profile double-opt in?
472 if (!empty($this->_fields
['group']) &&
473 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
476 foreach ($this->_fields
as $name => $values) {
477 if (substr($name, 0, 6) == 'email-') {
483 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
484 CRM_Core_Session
::singleton()->setStatus($status);
488 //transferring all the multi-record custom fields in _fields
489 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
490 $this->_fields
= $this->_multiRecordFields
;
491 $this->_multiRecordProfile
= TRUE;
493 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
494 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
495 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
499 if (!is_array($this->_fields
)) {
500 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
501 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
506 * Set default values for the form. Note that in edit/view mode
507 * the default values are retrieved from the database
510 public function setDefaultsValues() {
511 $this->_defaults
= [];
512 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
516 if ($this->_mode
!= self
::MODE_SEARCH
) {
517 // set default values for country / state to start with
518 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
521 if ($this->_id
&& !$this->_multiRecordProfile
) {
522 if ($this->_isContactActivityProfile
) {
523 $contactFields = $activityFields = [];
524 foreach ($this->_fields
as $fieldName => $field) {
525 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
526 $activityFields[$fieldName] = $field;
529 $contactFields[$fieldName] = $field;
533 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
534 if ($this->_activityId
) {
535 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
539 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
543 //set custom field defaults
544 if ($this->_multiRecordProfile
) {
545 foreach ($this->_multiRecordFields
as $key => $field) {
546 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
550 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
551 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
552 if ($this->_recordExists
== TRUE) {
553 $defaultValues = $defaultValues[$this->_recordId
];
556 $defaultValues = NULL;
560 if (!empty($defaultValues)) {
561 foreach ($defaultValues as $key => $value) {
562 $name = "custom_{$key}";
563 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
564 if ($htmlType != 'File') {
566 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
575 $this->_defaults
[$name] = "";
579 if ($htmlType == 'File') {
580 $entityId = $this->_id
;
581 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
584 $entityId = $this->_activityId
;
589 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key, $value);
593 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
595 $deleteExtra = ts("Are you sure you want to delete attached file?");
596 $fileId = $url['file_id'];
597 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId);
598 $deleteURL = CRM_Utils_System
::url('civicrm/file',
599 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
601 $text = ts("Delete Attached File");
602 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
604 // also delete the required rule that we've set on the form element
605 $this->removeFileRequiredRules($name);
612 foreach ($this->_fields
as $name => $field) {
613 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
614 $htmlType = $field['html_type'];
615 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
616 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
618 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
626 if ($htmlType == 'File') {
627 $entityId = $this->_id
;
628 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
629 $entityId = $this->_activityId
;
631 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
634 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
636 $deleteExtra = ts("Are you sure you want to delete attached file?");
637 $fileId = $url['file_id'];
638 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
639 $deleteURL = CRM_Utils_System
::url('civicrm/file',
640 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
642 $text = ts("Delete Attached File");
643 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
645 // also delete the required rule that we've set on the form element
646 $this->removeFileRequiredRules($field['name']);
652 if (isset($customFiles)) {
653 $this->assign('customFiles', $customFiles);
656 if ($this->_multiRecordProfile
) {
657 $this->setDefaults($this->_defaults
);
661 if (!empty($this->_defaults
['image_URL'])) {
662 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
663 $this->removeFileRequiredRules('image_URL');
666 $this->setDefaults($this->_defaults
);
670 * Build the form object.
673 public function buildQuickForm() {
674 $this->add('hidden', 'gid', $this->_gid
);
676 switch ($this->_mode
) {
677 case self
::MODE_CREATE
:
678 case self
::MODE_EDIT
:
679 case self
::MODE_REGISTER
:
680 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
683 case self
::MODE_SEARCH
:
684 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
690 //lets have single status message, CRM-4363
692 $statusMessage = NULL;
693 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
697 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
698 if (!$this->_recordExists
) {
699 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId
]), ts('Record doesnot exists'), 'alert');
702 $this->assign('deleteRecord', TRUE);
707 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
709 // we should not allow component and mix profiles in search mode
710 if ($this->_mode
!= self
::MODE_REGISTER
) {
711 //check for mix profile fields (eg: individual + other contact type)
712 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
713 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
714 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
715 if (!empty($errors)) {
716 $statusMessage = array_pop($errors);
721 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
726 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
729 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
730 $contactType = $contactTypes[0];
732 array_shift($contactTypes);
733 $contactSubtypes = $contactTypes;
735 $profileSubType = FALSE;
736 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
737 $profileSubType = $profileType;
738 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
742 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
743 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
744 ($profileType != $contactType))
747 if (!$statusMessage) {
748 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
749 [1 => $profileSubType ?
$profileSubType : $profileType]);
757 ["Membership", "Participant", "Contribution"]
761 if (!$statusMessage) {
762 $statusMessage = ts('Profile is not configured for the selected action.');
767 //lets have single status message,
768 $this->assign('statusMessage', $statusMessage);
773 $this->assign('id', $this->_id
);
774 $this->assign('mode', $this->_mode
);
775 $this->assign('action', $this->_action
);
776 $this->assign('fields', $this->_fields
);
777 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
779 // should we restrict what we display
781 if ($this->_mode
== self
::MODE_EDIT
) {
783 // show all fields that are visible:
784 // if we are a admin OR the same user OR acl-user with access to the profile
785 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
787 CRM_Core_Permission
::check('administer users') ||
788 $this->_id
== $this->_currentUserID ||
789 $this->_isPermissionedChecksum ||
793 CRM_Core_Permission
::EDIT
,
796 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
804 // if false, user is not logged-in.
806 if (!$this->_currentUserID
) {
807 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
808 $primaryLocationType = $defaultLocationType->id
;
811 $this->assign('anonUser', $anonUser);
814 $emailPresent = FALSE;
816 // add the form elements
817 foreach ($this->_fields
as $name => $field) {
818 // make sure that there is enough permission to expose this field
819 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
820 unset($this->_fields
[$name]);
824 // since the CMS manages the email field, suppress the email display if in
825 // register mode which occur within the CMS form
826 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
827 unset($this->_fields
[$name]);
831 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
833 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
835 if ($field['add_to_group_id']) {
836 $addToGroupId = $field['add_to_group_id'];
839 //build array for captcha
840 if ($field['add_captcha']) {
841 $addCaptcha[$field['group_id']] = $field['add_captcha'];
844 if (($name == 'email-Primary') ||
($name == 'email-' . ($primaryLocationType ??
""))) {
845 $emailPresent = TRUE;
846 $this->_mail
= $name;
850 // add captcha only for create mode.
851 if ($this->_mode
== self
::MODE_CREATE
) {
852 // suppress captcha for logged in users only
853 if ($this->_currentUserID
) {
854 $this->_isAddCaptcha
= FALSE;
856 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
857 $this->_isAddCaptcha
= TRUE;
861 $dao = new CRM_Core_DAO_UFGroup();
862 $dao->id
= $this->_gid
;
864 $dao->addSelect('is_update_dupe');
865 if ($dao->find(TRUE)) {
866 if ($dao->is_update_dupe
) {
867 $this->_isUpdateDupe
= $dao->is_update_dupe
;
873 $this->_isAddCaptcha
= FALSE;
876 //finally add captcha to form.
877 if ($this->_isAddCaptcha
) {
878 CRM_Utils_ReCAPTCHA
::enableCaptchaOnForm($this);
881 if ($this->_mode
!= self
::MODE_SEARCH
) {
882 if (isset($addToGroupId)) {
883 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
887 //let's do set defaults for the profile
888 $this->setDefaultsValues();
890 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
892 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
893 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
896 $this->assign('showCMS', FALSE);
899 $this->assign('groupId', $this->_gid
);
901 // if view mode pls freeze it with the done button.
902 if ($this->_action
& CRM_Core_Action
::VIEW
) {
906 if ($this->_context
== 'dialog') {
909 $this->_duplicateButtonName
,
910 ts('Save Matching Contact')
916 * Validate profile and provided activity Id.
918 * @param int $activityId
919 * @param int $contactId
924 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
927 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
931 $activityDetails = [];
932 $activityParams = ['id' => $activityId];
933 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
935 if (empty($activityDetails)) {
936 $errors[] = ts('Invalid Activity Id (aid).');
940 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
942 if ((!empty($profileActivityTypes['Activity']) &&
943 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
945 (!in_array($contactId, $activityDetails['assignee_contact']) &&
946 !in_array($contactId, $activityDetails['target_contact'])
949 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
958 * @param array $fields
959 * The input form values.
960 * @param array $files
961 * The uploaded files if any.
962 * @param CRM_Core_Form $form
966 * true if no errors, else array of errors
968 public static function formRule($fields, $files, $form) {
969 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
971 // if no values, return
972 if (empty($fields)) {
979 // hack we use a -1 in options to indicate that its registration
980 // ... and I can't remove that comment because even though it's clear as mud
981 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
982 // as to what it means....
984 // @todo - wonder if it ever occurred to someone that if they didn't document this param
985 // it might not be crystal clear why we have it....
986 $form->_isUpdateDupe
= 1;
989 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
993 // don't check for duplicates during registration validation: CRM-375
994 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
996 if (!empty($fields['email-Primary'])) {
997 $fields['email'] = $fields['email-Primary'] ??
NULL;
1001 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1002 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1006 self
::handleDuplicateChecking($errors, $fields, $form);
1010 foreach ($fields as $key => $value) {
1011 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1012 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1013 // Validate Country - State list
1014 $countryId = $fields["country-{$locTypeId}"];
1015 $stateProvinceId = $value;
1017 if ($stateProvinceId && $countryId) {
1018 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1019 $stateProvinceDAO->id
= $stateProvinceId;
1020 $stateProvinceDAO->find(TRUE);
1022 if ($stateProvinceDAO->country_id
!= $countryId) {
1023 // country mismatch hence display error
1024 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1025 $countries = CRM_Core_PseudoConstant
::country();
1026 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1031 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1032 // Validate County - State list
1033 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1036 if ($countyId && $stateProvinceId) {
1037 $countyDAO = new CRM_Core_DAO_County();
1038 $countyDAO->id
= $countyId;
1039 $countyDAO->find(TRUE);
1041 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1042 // state province mismatch hence display error
1043 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1044 $counties = CRM_Core_PseudoConstant
::county();
1045 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1050 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1051 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1052 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1053 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1054 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1055 [1 => ucwords(str_replace('_', ' ', $greeting))]
1061 return empty($errors) ?
TRUE : $errors;
1065 * Process the user submitted custom data values.
1068 public function postProcess() {
1069 $params = $this->controller
->exportValues($this->_name
);
1071 //if the delete record button is clicked
1072 if ($this->_deleteButtonName
) {
1073 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1074 $filterParams['id'] = $this->_customGroupId
;
1075 $returnProperties = ['is_multiple', 'table_name'];
1076 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1077 if (!empty($returnValues['is_multiple'])) {
1078 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1079 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1081 1 => [$this->_recordId
, 'Integer'],
1082 2 => [$this->_id
, 'Integer'],
1084 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1085 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1091 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1092 if (!empty($params['image_URL'])) {
1093 CRM_Contact_BAO_Contact
::processImageParams($params);
1097 'addressee' => 'addressee_id',
1098 'email_greeting' => 'email_greeting_id',
1099 'postal_greeting' => 'postal_greeting_id',
1104 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1107 $details = $contactDetails[$this->_id
];
1109 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1110 !empty($details['postal_greeting_id'])
1114 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1115 //Though Profile type is contact we need
1116 //Individual/Household/Organization for setting Greetings.
1117 if ($profileType == 'Contact') {
1118 $profileType = 'Individual';
1119 //if we editing Household/Organization.
1121 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1124 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1125 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1128 foreach ($greetingTypes as $key => $value) {
1129 if (!array_key_exists($key, $params)) {
1130 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1135 $transaction = new CRM_Core_Transaction();
1137 //used to send subscribe mail to the group which user want.
1138 //if the profile double option in is enabled
1142 foreach ($params as $name => $values) {
1143 if (substr($name, 0, 6) == 'email-') {
1144 $result['email'] = $values;
1148 //array of group id, subscribed by contact
1150 if (!empty($params['group']) &&
1151 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1153 $groupSubscribed = [];
1154 if (!empty($result['email'])) {
1156 $contactGroups = new CRM_Contact_DAO_GroupContact();
1157 $contactGroups->contact_id
= $this->_id
;
1158 $contactGroups->status
= 'Added';
1159 $contactGroups->find();
1161 while ($contactGroups->fetch()) {
1162 $contactGroup[] = $contactGroups->group_id
;
1163 $groupSubscribed[$contactGroups->group_id
] = 1;
1166 foreach ($params['group'] as $key => $val) {
1168 unset($params['group'][$key]);
1171 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1172 $key, 'group_type', 'id'
1174 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1175 substr($groupTypes, 1, -1)
1177 //filter group of mailing type and unset it from params
1178 if (in_array(2, $groupType)) {
1179 //if group is already subscribed , ignore it
1180 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1181 if (!isset($groupExist)) {
1182 $mailingType[] = $key;
1183 unset($params['group'][$key]);
1190 $addToGroupId = $this->_ufGroup
['add_to_group_id'] ??
NULL;
1191 if (!empty($addToGroupId)) {
1192 //run same check whether group is a mailing list
1193 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1194 $addToGroupId, 'group_type', 'id'
1196 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1197 substr($groupTypes, 1, -1)
1199 //filter group of mailing type and unset it from params
1200 if (in_array(2, $groupType) && !empty($result['email']) &&
1201 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1203 if (!count($contactGroup)) {
1204 //array of group id, subscribed by contact
1207 $contactGroups = new CRM_Contact_DAO_GroupContact();
1208 $contactGroups->contact_id
= $this->_id
;
1209 $contactGroups->status
= 'Added';
1210 $contactGroups->find();
1212 while ($contactGroups->fetch()) {
1213 $contactGroup[] = $contactGroups->group_id
;
1214 $groupSubscribed[$contactGroups->group_id
] = 1;
1218 //if group is already subscribed , ignore it
1219 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1220 if (!isset($groupExist)) {
1221 $mailingType[] = $addToGroupId;
1222 $addToGroupId = NULL;
1226 // since we are directly adding contact to group lets unset it from mailing
1227 if ($key = array_search($addToGroupId, $mailingType)) {
1228 unset($mailingType[$key]);
1234 $params['group'] = $groupSubscribed;
1237 // commenting below code, since we potentially
1238 // triggered maximum name field formatting cases during CRM-4430.
1240 // $params['preserveDBName'] = true;
1242 $profileFields = $this->_fields
;
1243 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1244 $profileFields = $activityParams = [];
1245 foreach ($this->_fields
as $fieldName => $field) {
1246 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1247 if (isset($params[$fieldName])) {
1248 $activityParams[$fieldName] = $params[$fieldName];
1250 if (isset($params['activity_date_time'])) {
1251 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1253 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1254 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1258 $profileFields[$fieldName] = $field;
1262 if (!empty($activityParams)) {
1263 $activityParams['version'] = 3;
1264 $activityParams['id'] = $this->_activityId
;
1265 $activityParams['skipRecentView'] = TRUE;
1266 civicrm_api('Activity', 'create', $activityParams);
1270 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1271 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1274 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1284 //mailing type group
1285 if (!empty($mailingType)) {
1286 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1288 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1293 $ufGroups[$this->_gid
] = 1;
1295 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1296 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1299 foreach ($ufGroups as $gId => $val) {
1300 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1301 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1302 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1306 //create CMS user (if CMS user option is selected in profile)
1307 if (!empty($params['cms_create_account']) &&
1308 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1310 $params['contactID'] = $this->_id
;
1311 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1312 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1313 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1314 $transaction->rollback();
1315 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1316 'reset=1&gid=' . $this->_gid
1321 $transaction->commit();
1325 * @param null $suffix
1327 * @return null|string
1329 public function checkTemplateFileExists($suffix = NULL) {
1331 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1332 $template = CRM_Core_Form
::getTemplate();
1333 if ($template->template_exists($templateFile)) {
1334 return $templateFile;
1337 // lets see if we have customized by name
1338 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1340 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1341 if ($template->template_exists($templateFile)) {
1342 return $templateFile;
1350 * Use the form name to create the tpl file name.
1354 public function getTemplateFileName() {
1355 $fileName = $this->checkTemplateFileExists();
1356 return $fileName ?
$fileName : parent
::getTemplateFileName();
1360 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1361 * i.e. we dont override
1365 public function overrideExtraTemplateFileName() {
1366 $fileName = $this->checkTemplateFileExists('extra.');
1367 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();