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 public $_isAddCaptcha = FALSE;
106 protected $_isPermissionedChecksum = FALSE;
109 * THe context from which we came from, allows us to go there if redirect not set.
116 * THe contact type for registration case.
120 protected $_ctype = NULL;
123 * Store profile ids if multiple profile ids are passed using comma separated.
124 * Currently lets implement this functionality only for dialog mode.
127 protected $_profileIds = [];
130 * Contact profile having activity fields?
134 protected $_isContactActivityProfile = FALSE;
137 * Activity Id connected to the profile.
141 protected $_activityId = NULL;
144 protected $_multiRecordFields = NULL;
146 protected $_recordId = NULL;
149 * Action for multi record profile (create/edit/delete).
153 protected $_multiRecord = NULL;
155 protected $_multiRecordProfile = FALSE;
157 protected $_recordExists = TRUE;
159 protected $_customGroupTitle = NULL;
161 protected $_deleteButtonName = NULL;
163 protected $_customGroupId = NULL;
165 protected $_currentUserID = NULL;
166 protected $_session = NULL;
169 * Check for any duplicates.
171 * Depending on form settings & usage scenario we potentially use the found id,
172 * create links to found ids or add an error.
174 * @param array $errors
175 * @param array $fields
176 * @param CRM_Profile_Form $form
180 protected static function handleDuplicateChecking(&$errors, $fields, $form) {
181 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
186 // for edit mode we need to allow our own record to be a dupe match!
187 $exceptions = [CRM_Core_Session
::singleton()->get('userID')];
189 $contactType = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
190 // If all profile fields is of Contact Type then consider
191 // profile is of Individual type(default).
193 $contactType = 'Individual';
196 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
197 $fields, $contactType,
198 ($form->_context
=== 'dialog' ?
'Supervised' : 'Unsupervised'),
204 if ($form->_isUpdateDupe
== 2) {
205 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
207 elseif ($form->_isUpdateDupe
== 1) {
208 $form->_id
= $ids[0];
211 if ($form->_context
== 'dialog') {
212 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
214 $duplicateContactsLinks = '<div class="matching-contacts-found">';
215 $duplicateContactsLinks .= ts('One matching contact was found. ', [
216 'count' => count($contactLinks['rows']),
217 'plural' => '%count matching contacts were found.<br />',
219 if ($contactLinks['msg'] == 'view') {
220 $duplicateContactsLinks .= ts('You can View the existing contact.', [
221 'count' => count($contactLinks['rows']),
222 'plural' => 'You can View the existing contacts.',
226 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
227 'count' => count($contactLinks['rows']),
228 'plural' => 'You can View or Edit the existing contacts.',
231 $duplicateContactsLinks .= '</div>';
232 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
234 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
236 $row .= ' <td class="matching-contacts-name"> ';
237 $row .= $contactLinks['rows'][$i]['display_name'];
239 $row .= ' <td class="matching-contacts-email"> ';
240 $row .= $contactLinks['rows'][$i]['primary_email'];
242 $row .= ' <td class="action-items"> ';
243 $row .= $contactLinks['rows'][$i]['view'] . ' ';
244 $row .= $contactLinks['rows'][$i]['edit'];
249 $duplicateContactsLinks .= $row . '</table>';
250 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
252 $errors['_qf_default'] = $duplicateContactsLinks;
254 // let smarty know that there are duplicates
255 $template = CRM_Core_Smarty
::singleton();
256 $template->assign('isDuplicate', 1);
259 $errors['_qf_default'] = ts('A record already exists with the same information.');
267 * Explicitly declare the entity api name.
269 public function getDefaultEntity() {
274 * Get the active UFGroups (profiles) on this form
275 * Many forms load one or more UFGroups (profiles).
276 * This provides a standard function to retrieve the IDs of those profiles from the form
277 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
279 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
283 public function getUFGroupIDs() {
284 if (empty($this->_profileIds
)) {
285 $dao = new CRM_Core_DAO_UFGroup();
286 $dao->id
= $this->_gid
;
287 $this->_profileIds
= (array) $dao;
289 return $this->_profileIds
;
293 * Are we using the profile in create mode?
297 public function getIsCreateMode() {
298 return ($this->_mode
== self
::MODE_CREATE
);
302 * Pre processing work done here.
304 * gets session variables for table name, id of entity in table, type of entity and stores them.
306 public function preProcess() {
307 $this->_id
= $this->get('id');
308 $this->_profileIds
= $this->get('profileIds');
309 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
310 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
312 //unset from session when $_GET doesn't have it
313 //except when the form is submitted
315 if (!array_key_exists('multiRecord', $_GET)) {
316 $this->set('multiRecord', NULL);
318 if (!array_key_exists('recordId', $_GET)) {
319 $this->set('recordId', NULL);
323 $this->_currentUserID
= CRM_Core_Session
::singleton()->get('userID');
325 if ($this->_mode
== self
::MODE_EDIT
) {
326 //specifies the action being done on a multi record field
327 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
328 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
329 if ($this->_multiRecord
) {
330 $this->set('multiRecord', $this->_multiRecord
);
333 if ($this->_multiRecord
&&
334 !in_array($this->_multiRecord
, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
])
336 CRM_Core_Error
::statusBounce(ts('Proper action not specified for this custom value record profile'));
339 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
341 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0));
343 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
345 foreach ($gids as $pfId) {
346 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
350 // check if we are rendering mixed profiles
351 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
352 CRM_Core_Error
::statusBounce(ts('You cannot combine profiles of multiple types.'));
355 // for now consider 1'st profile as primary profile and validate it
356 // i.e check for profile type etc.
357 // FIX ME: validations for other than primary
358 $this->_gid
= $this->_profileIds
[0];
359 $this->set('gid', $this->_gid
);
360 $this->set('profileIds', $this->_profileIds
);
364 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
365 $this->set('gid', $this->_gid
);
368 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
369 if (is_numeric($this->_activityId
)) {
370 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
371 if ($latestRevisionId) {
372 $this->_activityId
= $latestRevisionId;
375 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
377 //get values for ufGroupName, captcha and dupe update.
379 $dao = new CRM_Core_DAO_UFGroup();
380 $dao->id
= $this->_gid
;
381 if ($dao->find(TRUE)) {
382 $this->_isUpdateDupe
= $dao->is_update_dupe
;
383 $this->_isAddCaptcha
= $dao->add_captcha
;
384 $this->_ufGroup
= (array) $dao;
387 if (empty($this->_ufGroup
['is_active'])) {
388 CRM_Core_Error
::statusBounce(ts('The requested profile (gid=%1) is inactive or does not exist.', [
393 $this->assign('ufGroupName', $this->_ufGroup
['name']);
395 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
397 // if we don't have a gid use the default, else just use that specific gid
398 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
399 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
400 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
402 elseif ($this->_mode
== self
::MODE_SEARCH
) {
403 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
404 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
408 $this->_skipPermission
,
409 CRM_Core_Permission
::SEARCH
413 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
416 $this->_skipPermission
,
418 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
420 $multiRecordFieldListing = FALSE;
421 //using selector for listing of multi-record fields
422 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
423 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
425 if ($this->_multiRecord
) {
426 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
427 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
430 $this->_recordId
= NULL;
431 $this->set('recordId', NULL);
433 //record id is necessary for _multiRecord view and update/edit action
434 if (!$this->_recordId
435 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
437 CRM_Core_Error
::statusBounce(ts('The requested Profile (gid=%1) requires record id while performing this action',
441 elseif (empty($this->_multiRecordFields
)) {
442 CRM_Core_Error
::statusBounce(ts('No Multi-Record Fields configured for this profile (gid=%1)',
447 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
448 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles([$fieldId]);
449 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
450 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
452 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
453 //record exists check
454 foreach ($this->_multiRecordFields
as $key => $field) {
455 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
457 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
459 if (array_key_exists($this->_recordId
, $getValues)) {
460 $this->_recordExists
= TRUE;
463 $this->_recordExists
= FALSE;
464 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
465 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');
469 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
470 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
471 if ($this->_maxRecordLimit
) {
472 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
477 elseif (!empty($this->_multiRecordFields
)
478 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, [
479 CRM_Core_Action
::DELETE
,
480 CRM_Core_Action
::UPDATE
,
483 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
484 //multi-record listing page
485 $multiRecordFieldListing = TRUE;
486 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
487 $cs = $this->get('cs');
488 $page->set('pageCheckSum', $cs);
489 $page->set('contactId', $this->_id
);
490 $page->set('profileId', $this->_gid
);
491 $page->set('action', CRM_Core_Action
::BROWSE
);
492 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
496 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
498 // is profile double-opt in?
499 if (!empty($this->_fields
['group']) &&
500 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
503 foreach ($this->_fields
as $name => $values) {
504 if (substr($name, 0, 6) == 'email-') {
510 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
511 CRM_Core_Session
::singleton()->setStatus($status);
515 //transferring all the multi-record custom fields in _fields
516 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
517 $this->_fields
= $this->_multiRecordFields
;
518 $this->_multiRecordProfile
= TRUE;
520 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
521 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
522 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
526 if (!is_array($this->_fields
)) {
527 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
528 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
533 * Set default values for the form. Note that in edit/view mode
534 * the default values are retrieved from the database
537 public function setDefaultsValues() {
538 $this->_defaults
= [];
539 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
543 if ($this->_mode
!= self
::MODE_SEARCH
) {
544 // set default values for country / state to start with
545 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
548 if ($this->_id
&& !$this->_multiRecordProfile
) {
549 if ($this->_isContactActivityProfile
) {
550 $contactFields = $activityFields = [];
551 foreach ($this->_fields
as $fieldName => $field) {
552 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
553 $activityFields[$fieldName] = $field;
556 $contactFields[$fieldName] = $field;
560 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
561 if ($this->_activityId
) {
562 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
566 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
570 //set custom field defaults
571 if ($this->_multiRecordProfile
) {
572 foreach ($this->_multiRecordFields
as $key => $field) {
573 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
577 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
578 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
579 if ($this->_recordExists
== TRUE) {
580 $defaultValues = $defaultValues[$this->_recordId
];
583 $defaultValues = NULL;
587 if (!empty($defaultValues)) {
588 foreach ($defaultValues as $key => $value) {
589 $name = "custom_{$key}";
590 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
591 if ($htmlType != 'File') {
593 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
602 $this->_defaults
[$name] = "";
606 if ($htmlType == 'File') {
607 $entityId = $this->_id
;
608 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
611 $entityId = $this->_activityId
;
616 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key, $value);
620 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
622 $deleteExtra = ts("Are you sure you want to delete attached file?");
623 $fileId = $url['file_id'];
624 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId);
625 $deleteURL = CRM_Utils_System
::url('civicrm/file',
626 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
628 $text = ts("Delete Attached File");
629 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
631 // also delete the required rule that we've set on the form element
632 $this->removeFileRequiredRules($name);
639 foreach ($this->_fields
as $name => $field) {
640 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
641 $htmlType = $field['html_type'];
642 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
643 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
645 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
653 if ($htmlType == 'File') {
654 $entityId = $this->_id
;
655 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
656 $entityId = $this->_activityId
;
658 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
661 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
663 $deleteExtra = ts("Are you sure you want to delete attached file?");
664 $fileId = $url['file_id'];
665 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
666 $deleteURL = CRM_Utils_System
::url('civicrm/file',
667 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
669 $text = ts("Delete Attached File");
670 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
672 // also delete the required rule that we've set on the form element
673 $this->removeFileRequiredRules($field['name']);
679 if (isset($customFiles)) {
680 $this->assign('customFiles', $customFiles);
683 if ($this->_multiRecordProfile
) {
684 $this->setDefaults($this->_defaults
);
688 if (!empty($this->_defaults
['image_URL'])) {
689 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
690 $this->removeFileRequiredRules('image_URL');
693 $this->setDefaults($this->_defaults
);
697 * Build the form object.
700 public function buildQuickForm() {
701 $this->add('hidden', 'gid', $this->_gid
);
703 switch ($this->_mode
) {
704 case self
::MODE_CREATE
:
705 case self
::MODE_EDIT
:
706 case self
::MODE_REGISTER
:
707 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
710 case self
::MODE_SEARCH
:
711 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
717 //lets have single status message, CRM-4363
719 $statusMessage = NULL;
720 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
724 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
725 if (!$this->_recordExists
) {
726 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId
]), ts('Record doesnot exists'), 'alert');
729 $this->assign('deleteRecord', TRUE);
734 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
736 // we should not allow component and mix profiles in search mode
737 if ($this->_mode
!= self
::MODE_REGISTER
) {
738 //check for mix profile fields (eg: individual + other contact type)
739 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
740 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
741 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
742 if (!empty($errors)) {
743 $statusMessage = array_pop($errors);
748 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
753 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
756 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
757 $contactType = $contactTypes[0];
759 array_shift($contactTypes);
760 $contactSubtypes = $contactTypes;
762 $profileSubType = FALSE;
763 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
764 $profileSubType = $profileType;
765 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
769 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
770 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
771 ($profileType != $contactType))
774 if (!$statusMessage) {
775 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
776 [1 => $profileSubType ?
$profileSubType : $profileType]);
784 ["Membership", "Participant", "Contribution"]
788 if (!$statusMessage) {
789 $statusMessage = ts('Profile is not configured for the selected action.');
794 //lets have single status message,
795 $this->assign('statusMessage', $statusMessage);
800 $this->assign('id', $this->_id
);
801 $this->assign('mode', $this->_mode
);
802 $this->assign('action', $this->_action
);
803 $this->assign('fields', $this->_fields
);
804 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
806 // should we restrict what we display
808 if ($this->_mode
== self
::MODE_EDIT
) {
810 // show all fields that are visible:
811 // if we are a admin OR the same user OR acl-user with access to the profile
812 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
814 CRM_Core_Permission
::check('administer users') ||
815 $this->_id
== $this->_currentUserID ||
816 $this->_isPermissionedChecksum ||
820 CRM_Core_Permission
::EDIT
,
823 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
831 // if false, user is not logged-in.
833 if (!$this->_currentUserID
) {
834 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
835 $primaryLocationType = $defaultLocationType->id
;
838 $this->assign('anonUser', $anonUser);
841 $emailPresent = FALSE;
843 // add the form elements
844 foreach ($this->_fields
as $name => $field) {
845 // make sure that there is enough permission to expose this field
846 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
847 unset($this->_fields
[$name]);
851 // since the CMS manages the email field, suppress the email display if in
852 // register mode which occur within the CMS form
853 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
854 unset($this->_fields
[$name]);
858 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
860 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
862 if ($field['add_to_group_id']) {
863 $addToGroupId = $field['add_to_group_id'];
866 //build array for captcha
867 if ($field['add_captcha']) {
868 $addCaptcha[$field['group_id']] = $field['add_captcha'];
871 if (($name == 'email-Primary') ||
($name == 'email-' . ($primaryLocationType ??
""))) {
872 $emailPresent = TRUE;
873 $this->_mail
= $name;
877 // add captcha only for create mode.
878 if ($this->_mode
== self
::MODE_CREATE
) {
879 // suppress captcha for logged in users only
880 if ($this->_currentUserID
) {
881 $this->_isAddCaptcha
= FALSE;
883 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
884 $this->_isAddCaptcha
= TRUE;
888 $dao = new CRM_Core_DAO_UFGroup();
889 $dao->id
= $this->_gid
;
891 $dao->addSelect('is_update_dupe');
892 if ($dao->find(TRUE)) {
893 if ($dao->is_update_dupe
) {
894 $this->_isUpdateDupe
= $dao->is_update_dupe
;
900 $this->_isAddCaptcha
= FALSE;
903 //finally add captcha to form.
904 if ($this->_isAddCaptcha
) {
905 CRM_Utils_ReCAPTCHA
::enableCaptchaOnForm($this);
908 if ($this->_mode
!= self
::MODE_SEARCH
) {
909 if (isset($addToGroupId)) {
910 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
914 //let's do set defaults for the profile
915 $this->setDefaultsValues();
917 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
919 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
920 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
923 $this->assign('showCMS', FALSE);
926 $this->assign('groupId', $this->_gid
);
928 // if view mode pls freeze it with the done button.
929 if ($this->_action
& CRM_Core_Action
::VIEW
) {
933 if ($this->_context
== 'dialog') {
936 $this->_duplicateButtonName
,
937 ts('Save Matching Contact'),
940 'class' => 'crm-button',
947 * Validate profile and provided activity Id.
949 * @param int $activityId
950 * @param int $contactId
955 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
958 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
962 $activityDetails = [];
963 $activityParams = ['id' => $activityId];
964 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
966 if (empty($activityDetails)) {
967 $errors[] = ts('Invalid Activity Id (aid).');
971 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
973 if ((!empty($profileActivityTypes['Activity']) &&
974 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
976 (!in_array($contactId, $activityDetails['assignee_contact']) &&
977 !in_array($contactId, $activityDetails['target_contact'])
980 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
989 * @param array $fields
990 * The input form values.
991 * @param array $files
992 * The uploaded files if any.
993 * @param CRM_Core_Form $form
997 * true if no errors, else array of errors
999 public static function formRule($fields, $files, $form) {
1000 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
1002 // if no values, return
1003 if (empty($fields)) {
1010 // hack we use a -1 in options to indicate that its registration
1011 // ... and I can't remove that comment because even though it's clear as mud
1012 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
1013 // as to what it means....
1015 // @todo - wonder if it ever occurred to someone that if they didn't document this param
1016 // it might not be crystal clear why we have it....
1017 $form->_isUpdateDupe
= 1;
1020 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
1024 // don't check for duplicates during registration validation: CRM-375
1025 if (!$register && !array_key_exists('_qf_Edit_upload_duplicate', $fields)) {
1027 if (!empty($fields['email-Primary'])) {
1028 $fields['email'] = $fields['email-Primary'] ??
NULL;
1032 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1033 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1037 self
::handleDuplicateChecking($errors, $fields, $form);
1041 foreach ($fields as $key => $value) {
1042 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1043 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1044 // Validate Country - State list
1045 $countryId = $fields["country-{$locTypeId}"];
1046 $stateProvinceId = $value;
1048 if ($stateProvinceId && $countryId) {
1049 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1050 $stateProvinceDAO->id
= $stateProvinceId;
1051 $stateProvinceDAO->find(TRUE);
1053 if ($stateProvinceDAO->country_id
!= $countryId) {
1054 // country mismatch hence display error
1055 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1056 $countries = CRM_Core_PseudoConstant
::country();
1057 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1062 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1063 // Validate County - State list
1064 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1067 if ($countyId && $stateProvinceId) {
1068 $countyDAO = new CRM_Core_DAO_County();
1069 $countyDAO->id
= $countyId;
1070 $countyDAO->find(TRUE);
1072 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1073 // state province mismatch hence display error
1074 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1075 $counties = CRM_Core_PseudoConstant
::county();
1076 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1081 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1082 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1083 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1084 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1085 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1086 [1 => ucwords(str_replace('_', ' ', $greeting))]
1092 return empty($errors) ?
TRUE : $errors;
1096 * Process the user submitted custom data values.
1099 public function postProcess() {
1100 $params = $this->controller
->exportValues($this->_name
);
1102 //if the delete record button is clicked
1103 if ($this->_deleteButtonName
) {
1104 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1105 $filterParams['id'] = $this->_customGroupId
;
1106 $returnProperties = ['is_multiple', 'table_name'];
1107 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1108 if (!empty($returnValues['is_multiple'])) {
1109 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1110 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1112 1 => [$this->_recordId
, 'Integer'],
1113 2 => [$this->_id
, 'Integer'],
1115 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1116 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1122 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1123 if (!empty($params['image_URL'])) {
1124 CRM_Contact_BAO_Contact
::processImageParams($params);
1128 'addressee' => 'addressee_id',
1129 'email_greeting' => 'email_greeting_id',
1130 'postal_greeting' => 'postal_greeting_id',
1135 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1138 $details = $contactDetails[$this->_id
];
1140 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1141 !empty($details['postal_greeting_id'])
1145 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1146 //Though Profile type is contact we need
1147 //Individual/Household/Organization for setting Greetings.
1148 if ($profileType == 'Contact') {
1149 $profileType = 'Individual';
1150 //if we editing Household/Organization.
1152 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1155 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1156 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1159 foreach ($greetingTypes as $key => $value) {
1160 if (!array_key_exists($key, $params)) {
1161 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1166 $transaction = new CRM_Core_Transaction();
1168 //used to send subscribe mail to the group which user want.
1169 //if the profile double option in is enabled
1173 foreach ($params as $name => $values) {
1174 if (substr($name, 0, 6) == 'email-') {
1175 $result['email'] = $values;
1179 //array of group id, subscribed by contact
1181 if (!empty($params['group']) &&
1182 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1184 $groupSubscribed = [];
1185 if (!empty($result['email'])) {
1187 $contactGroups = new CRM_Contact_DAO_GroupContact();
1188 $contactGroups->contact_id
= $this->_id
;
1189 $contactGroups->status
= 'Added';
1190 $contactGroups->find();
1192 while ($contactGroups->fetch()) {
1193 $contactGroup[] = $contactGroups->group_id
;
1194 $groupSubscribed[$contactGroups->group_id
] = 1;
1197 foreach ($params['group'] as $key => $val) {
1199 unset($params['group'][$key]);
1202 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1203 $key, 'group_type', 'id'
1205 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1206 substr($groupTypes, 1, -1)
1208 //filter group of mailing type and unset it from params
1209 if (in_array(2, $groupType)) {
1210 //if group is already subscribed , ignore it
1211 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1212 if (!isset($groupExist)) {
1213 $mailingType[] = $key;
1214 unset($params['group'][$key]);
1221 $addToGroupId = $this->_ufGroup
['add_to_group_id'] ??
NULL;
1222 if (!empty($addToGroupId)) {
1223 //run same check whether group is a mailing list
1224 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1225 $addToGroupId, 'group_type', 'id'
1227 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1228 substr($groupTypes, 1, -1)
1230 //filter group of mailing type and unset it from params
1231 if (in_array(2, $groupType) && !empty($result['email']) &&
1232 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1234 if (!count($contactGroup)) {
1235 //array of group id, subscribed by contact
1238 $contactGroups = new CRM_Contact_DAO_GroupContact();
1239 $contactGroups->contact_id
= $this->_id
;
1240 $contactGroups->status
= 'Added';
1241 $contactGroups->find();
1243 while ($contactGroups->fetch()) {
1244 $contactGroup[] = $contactGroups->group_id
;
1245 $groupSubscribed[$contactGroups->group_id
] = 1;
1249 //if group is already subscribed , ignore it
1250 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1251 if (!isset($groupExist)) {
1252 $mailingType[] = $addToGroupId;
1253 $addToGroupId = NULL;
1257 // since we are directly adding contact to group lets unset it from mailing
1258 if ($key = array_search($addToGroupId, $mailingType)) {
1259 unset($mailingType[$key]);
1265 $params['group'] = $groupSubscribed;
1268 // commenting below code, since we potentially
1269 // triggered maximum name field formatting cases during CRM-4430.
1271 // $params['preserveDBName'] = true;
1273 $profileFields = $this->_fields
;
1274 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1275 $profileFields = $activityParams = [];
1276 foreach ($this->_fields
as $fieldName => $field) {
1277 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1278 if (isset($params[$fieldName])) {
1279 $activityParams[$fieldName] = $params[$fieldName];
1281 if (isset($params['activity_date_time'])) {
1282 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1284 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1285 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1289 $profileFields[$fieldName] = $field;
1293 if (!empty($activityParams)) {
1294 $activityParams['version'] = 3;
1295 $activityParams['id'] = $this->_activityId
;
1296 $activityParams['skipRecentView'] = TRUE;
1297 civicrm_api('Activity', 'create', $activityParams);
1301 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1302 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1305 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1315 //mailing type group
1316 if (!empty($mailingType)) {
1317 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1319 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1324 $ufGroups[$this->_gid
] = 1;
1326 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1327 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1330 foreach ($ufGroups as $gId => $val) {
1331 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1332 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1333 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1337 //create CMS user (if CMS user option is selected in profile)
1338 if (!empty($params['cms_create_account']) &&
1339 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1341 $params['contactID'] = $this->_id
;
1342 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1343 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1344 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1345 $transaction->rollback();
1346 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1347 'reset=1&gid=' . $this->_gid
1352 $transaction->commit();
1356 * Check template file exists.
1358 * @param string|null $suffix
1360 * @return string|null
1361 * Template file path, else null
1363 public function checkTemplateFileExists($suffix = NULL) {
1365 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1366 $template = CRM_Core_Form
::getTemplate();
1367 if ($template->template_exists($templateFile)) {
1368 return $templateFile;
1371 // lets see if we have customized by name
1372 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1374 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1375 if ($template->template_exists($templateFile)) {
1376 return $templateFile;
1384 * Use the form name to create the tpl file name.
1388 public function getTemplateFileName() {
1389 $fileName = $this->checkTemplateFileExists();
1390 return $fileName ?
$fileName : parent
::getTemplateFileName();
1394 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1395 * i.e. we dont override
1399 public function overrideExtraTemplateFileName() {
1400 $fileName = $this->checkTemplateFileExists('extra.');
1401 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();