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.
53 * @var array 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 * Pre processing work done here.
276 * gets session variables for table name, id of entity in table, type of entity and stores them.
278 public function preProcess() {
279 $this->_id
= $this->get('id');
280 $this->_profileIds
= $this->get('profileIds');
281 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
282 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
284 //unset from session when $_GET doesn't have it
285 //except when the form is submitted
287 if (!array_key_exists('multiRecord', $_GET)) {
288 $this->set('multiRecord', NULL);
290 if (!array_key_exists('recordId', $_GET)) {
291 $this->set('recordId', NULL);
295 $this->_currentUserID
= CRM_Core_Session
::singleton()->get('userID');
297 if ($this->_mode
== self
::MODE_EDIT
) {
298 //specifies the action being done on a multi record field
299 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
300 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
301 if ($this->_multiRecord
) {
302 $this->set('multiRecord', $this->_multiRecord
);
305 if ($this->_multiRecord
&&
306 !in_array($this->_multiRecord
, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
])
308 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
311 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
313 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0));
315 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
317 foreach ($gids as $pfId) {
318 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
322 // check if we are rendering mixed profiles
323 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
324 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
327 // for now consider 1'st profile as primary profile and validate it
328 // i.e check for profile type etc.
329 // FIX ME: validations for other than primary
330 $this->_gid
= $this->_profileIds
[0];
331 $this->set('gid', $this->_gid
);
332 $this->set('profileIds', $this->_profileIds
);
336 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
337 $this->set('gid', $this->_gid
);
340 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
341 if (is_numeric($this->_activityId
)) {
342 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
343 if ($latestRevisionId) {
344 $this->_activityId
= $latestRevisionId;
347 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
349 //get values for ufGroupName, captcha and dupe update.
351 $dao = new CRM_Core_DAO_UFGroup();
352 $dao->id
= $this->_gid
;
353 if ($dao->find(TRUE)) {
354 $this->_isUpdateDupe
= $dao->is_update_dupe
;
355 $this->_isAddCaptcha
= $dao->add_captcha
;
356 $this->_ufGroup
= (array) $dao;
359 if (!CRM_Utils_Array
::value('is_active', $this->_ufGroup
)) {
360 CRM_Core_Error
::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', [
365 $this->assign('ufGroupName', $this->_ufGroup
['name']);
367 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
369 // if we don't have a gid use the default, else just use that specific gid
370 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
371 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
372 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
374 elseif ($this->_mode
== self
::MODE_SEARCH
) {
375 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
376 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
380 $this->_skipPermission
,
381 CRM_Core_Permission
::SEARCH
385 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
388 $this->_skipPermission
,
390 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
392 $multiRecordFieldListing = FALSE;
393 //using selector for listing of multi-record fields
394 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
395 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
397 if ($this->_multiRecord
) {
398 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
399 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
402 $this->_recordId
= NULL;
403 $this->set('recordId', NULL);
405 //record id is necessary for _multiRecord view and update/edit action
406 if (!$this->_recordId
407 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
409 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
413 elseif (empty($this->_multiRecordFields
)) {
414 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
419 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
420 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles([$fieldId]);
421 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
422 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
424 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
425 //record exists check
426 foreach ($this->_multiRecordFields
as $key => $field) {
427 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
429 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
431 if (array_key_exists($this->_recordId
, $getValues)) {
432 $this->_recordExists
= TRUE;
435 $this->_recordExists
= FALSE;
436 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
437 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');
441 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
442 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
443 if ($this->_maxRecordLimit
) {
444 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
449 elseif (!empty($this->_multiRecordFields
)
450 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, [
451 CRM_Core_Action
::DELETE
,
452 CRM_Core_Action
::UPDATE
,
455 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
456 //multi-record listing page
457 $multiRecordFieldListing = TRUE;
458 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
459 $cs = $this->get('cs');
460 $page->set('pageCheckSum', $cs);
461 $page->set('contactId', $this->_id
);
462 $page->set('profileId', $this->_gid
);
463 $page->set('action', CRM_Core_Action
::BROWSE
);
464 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
468 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
470 // is profile double-opt in?
471 if (!empty($this->_fields
['group']) &&
472 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
475 foreach ($this->_fields
as $name => $values) {
476 if (substr($name, 0, 6) == 'email-') {
482 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
483 CRM_Core_Session
::singleton()->setStatus($status);
487 //transferring all the multi-record custom fields in _fields
488 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
489 $this->_fields
= $this->_multiRecordFields
;
490 $this->_multiRecordProfile
= TRUE;
492 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
493 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
494 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
498 if (!is_array($this->_fields
)) {
499 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
500 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
505 * Set default values for the form. Note that in edit/view mode
506 * the default values are retrieved from the database
509 public function setDefaultsValues() {
510 $this->_defaults
= [];
511 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
515 if ($this->_mode
!= self
::MODE_SEARCH
) {
516 // set default values for country / state to start with
517 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
520 if ($this->_id
&& !$this->_multiRecordProfile
) {
521 if ($this->_isContactActivityProfile
) {
522 $contactFields = $activityFields = [];
523 foreach ($this->_fields
as $fieldName => $field) {
524 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
525 $activityFields[$fieldName] = $field;
528 $contactFields[$fieldName] = $field;
532 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
533 if ($this->_activityId
) {
534 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
538 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
542 //set custom field defaults
543 if ($this->_multiRecordProfile
) {
544 foreach ($this->_multiRecordFields
as $key => $field) {
545 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
549 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
550 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
551 if ($this->_recordExists
== TRUE) {
552 $defaultValues = $defaultValues[$this->_recordId
];
555 $defaultValues = NULL;
559 if (!empty($defaultValues)) {
560 foreach ($defaultValues as $key => $value) {
561 $name = "custom_{$key}";
562 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
563 if ($htmlType != 'File') {
565 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
574 $this->_defaults
[$name] = "";
578 if ($htmlType == 'File') {
579 $entityId = $this->_id
;
580 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
583 $entityId = $this->_activityId
;
588 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key, $value);
592 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
594 $deleteExtra = ts("Are you sure you want to delete attached file?");
595 $fileId = $url['file_id'];
596 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId);
597 $deleteURL = CRM_Utils_System
::url('civicrm/file',
598 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
600 $text = ts("Delete Attached File");
601 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
603 // also delete the required rule that we've set on the form element
604 $this->removeFileRequiredRules($name);
611 foreach ($this->_fields
as $name => $field) {
612 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
613 $htmlType = $field['html_type'];
614 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
615 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
617 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
625 if ($htmlType == 'File') {
626 $entityId = $this->_id
;
627 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
628 $entityId = $this->_activityId
;
630 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
633 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
635 $deleteExtra = ts("Are you sure you want to delete attached file?");
636 $fileId = $url['file_id'];
637 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
638 $deleteURL = CRM_Utils_System
::url('civicrm/file',
639 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
641 $text = ts("Delete Attached File");
642 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
644 // also delete the required rule that we've set on the form element
645 $this->removeFileRequiredRules($field['name']);
651 if (isset($customFiles)) {
652 $this->assign('customFiles', $customFiles);
655 if ($this->_multiRecordProfile
) {
656 $this->setDefaults($this->_defaults
);
660 if (!empty($this->_defaults
['image_URL'])) {
661 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
662 $this->removeFileRequiredRules('image_URL');
665 $this->setDefaults($this->_defaults
);
669 * Build the form object.
672 public function buildQuickForm() {
673 $this->add('hidden', 'gid', $this->_gid
);
675 switch ($this->_mode
) {
676 case self
::MODE_CREATE
:
677 case self
::MODE_EDIT
:
678 case self
::MODE_REGISTER
:
679 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
682 case self
::MODE_SEARCH
:
683 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
689 //lets have single status message, CRM-4363
691 $statusMessage = NULL;
692 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
696 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
697 if (!$this->_recordExists
) {
698 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId
]), ts('Record doesnot exists'), 'alert');
701 $this->assign('deleteRecord', TRUE);
706 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
708 // we should not allow component and mix profiles in search mode
709 if ($this->_mode
!= self
::MODE_REGISTER
) {
710 //check for mix profile fields (eg: individual + other contact type)
711 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
712 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
713 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
714 if (!empty($errors)) {
715 $statusMessage = array_pop($errors);
720 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
725 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
728 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
729 $contactType = $contactTypes[0];
731 array_shift($contactTypes);
732 $contactSubtypes = $contactTypes;
734 $profileSubType = FALSE;
735 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
736 $profileSubType = $profileType;
737 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
741 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
742 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
743 ($profileType != $contactType))
746 if (!$statusMessage) {
747 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
748 [1 => $profileSubType ?
$profileSubType : $profileType]);
756 ["Membership", "Participant", "Contribution"]
760 if (!$statusMessage) {
761 $statusMessage = ts('Profile is not configured for the selected action.');
766 //lets have single status message,
767 $this->assign('statusMessage', $statusMessage);
772 $this->assign('id', $this->_id
);
773 $this->assign('mode', $this->_mode
);
774 $this->assign('action', $this->_action
);
775 $this->assign('fields', $this->_fields
);
776 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
778 // should we restrict what we display
780 if ($this->_mode
== self
::MODE_EDIT
) {
782 // show all fields that are visible:
783 // if we are a admin OR the same user OR acl-user with access to the profile
784 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
786 CRM_Core_Permission
::check('administer users') ||
787 $this->_id
== $this->_currentUserID ||
788 $this->_isPermissionedChecksum ||
792 CRM_Core_Permission
::EDIT
,
795 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
803 // if false, user is not logged-in.
805 if (!$this->_currentUserID
) {
806 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
807 $primaryLocationType = $defaultLocationType->id
;
810 $this->assign('anonUser', $anonUser);
813 $emailPresent = FALSE;
815 // add the form elements
816 foreach ($this->_fields
as $name => $field) {
817 // make sure that there is enough permission to expose this field
818 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
819 unset($this->_fields
[$name]);
823 // since the CMS manages the email field, suppress the email display if in
824 // register mode which occur within the CMS form
825 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
826 unset($this->_fields
[$name]);
830 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
832 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
834 if ($field['add_to_group_id']) {
835 $addToGroupId = $field['add_to_group_id'];
838 //build array for captcha
839 if ($field['add_captcha']) {
840 $addCaptcha[$field['group_id']] = $field['add_captcha'];
843 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
844 $emailPresent = TRUE;
845 $this->_mail
= $name;
849 // add captcha only for create mode.
850 if ($this->_mode
== self
::MODE_CREATE
) {
851 // suppress captcha for logged in users only
852 if ($this->_currentUserID
) {
853 $this->_isAddCaptcha
= FALSE;
855 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
856 $this->_isAddCaptcha
= TRUE;
860 $dao = new CRM_Core_DAO_UFGroup();
861 $dao->id
= $this->_gid
;
863 $dao->addSelect('is_update_dupe');
864 if ($dao->find(TRUE)) {
865 if ($dao->is_update_dupe
) {
866 $this->_isUpdateDupe
= $dao->is_update_dupe
;
872 $this->_isAddCaptcha
= FALSE;
875 //finally add captcha to form.
876 if ($this->_isAddCaptcha
) {
877 CRM_Utils_ReCAPTCHA
::enableCaptchaOnForm($this);
880 if ($this->_mode
!= self
::MODE_SEARCH
) {
881 if (isset($addToGroupId)) {
882 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
886 //let's do set defaults for the profile
887 $this->setDefaultsValues();
889 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
891 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
892 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
895 $this->assign('showCMS', FALSE);
898 $this->assign('groupId', $this->_gid
);
900 // if view mode pls freeze it with the done button.
901 if ($this->_action
& CRM_Core_Action
::VIEW
) {
905 if ($this->_context
== 'dialog') {
908 $this->_duplicateButtonName
,
909 ts('Save Matching Contact')
915 * Validate profile and provided activity Id.
917 * @param int $activityId
918 * @param int $contactId
923 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
926 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
930 $activityDetails = [];
931 $activityParams = ['id' => $activityId];
932 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
934 if (empty($activityDetails)) {
935 $errors[] = ts('Invalid Activity Id (aid).');
939 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
941 if ((!empty($profileActivityTypes['Activity']) &&
942 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
944 (!in_array($contactId, $activityDetails['assignee_contact']) &&
945 !in_array($contactId, $activityDetails['target_contact'])
948 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
957 * @param array $fields
958 * The input form values.
959 * @param array $files
960 * The uploaded files if any.
961 * @param CRM_Core_Form $form
965 * true if no errors, else array of errors
967 public static function formRule($fields, $files, $form) {
968 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
970 // if no values, return
971 if (empty($fields)) {
978 // hack we use a -1 in options to indicate that its registration
979 // ... and I can't remove that comment because even though it's clear as mud
980 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
981 // as to what it means....
983 // @todo - wonder if it ever occurred to someone that if they didn't document this param
984 // it might not be crystal clear why we have it....
985 $form->_isUpdateDupe
= 1;
988 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
992 // don't check for duplicates during registration validation: CRM-375
993 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
995 if (!empty($fields['email-Primary'])) {
996 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
1000 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1001 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1005 self
::handleDuplicateChecking($errors, $fields, $form);
1009 foreach ($fields as $key => $value) {
1010 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1011 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1012 // Validate Country - State list
1013 $countryId = $fields["country-{$locTypeId}"];
1014 $stateProvinceId = $value;
1016 if ($stateProvinceId && $countryId) {
1017 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1018 $stateProvinceDAO->id
= $stateProvinceId;
1019 $stateProvinceDAO->find(TRUE);
1021 if ($stateProvinceDAO->country_id
!= $countryId) {
1022 // country mismatch hence display error
1023 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1024 $countries = CRM_Core_PseudoConstant
::country();
1025 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1030 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1031 // Validate County - State list
1032 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1035 if ($countyId && $stateProvinceId) {
1036 $countyDAO = new CRM_Core_DAO_County();
1037 $countyDAO->id
= $countyId;
1038 $countyDAO->find(TRUE);
1040 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1041 // state province mismatch hence display error
1042 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1043 $counties = CRM_Core_PseudoConstant
::county();
1044 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1049 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1050 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1051 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1052 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1053 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1054 [1 => ucwords(str_replace('_', ' ', $greeting))]
1060 return empty($errors) ?
TRUE : $errors;
1064 * Process the user submitted custom data values.
1067 public function postProcess() {
1068 $params = $this->controller
->exportValues($this->_name
);
1070 //if the delete record button is clicked
1071 if ($this->_deleteButtonName
) {
1072 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1073 $filterParams['id'] = $this->_customGroupId
;
1074 $returnProperties = ['is_multiple', 'table_name'];
1075 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1076 if (!empty($returnValues['is_multiple'])) {
1077 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1078 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1080 1 => [$this->_recordId
, 'Integer'],
1081 2 => [$this->_id
, 'Integer'],
1083 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1084 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1090 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1091 if (!empty($params['image_URL'])) {
1092 CRM_Contact_BAO_Contact
::processImageParams($params);
1096 'addressee' => 'addressee_id',
1097 'email_greeting' => 'email_greeting_id',
1098 'postal_greeting' => 'postal_greeting_id',
1103 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1106 $details = $contactDetails[$this->_id
];
1108 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1109 CRM_Utils_Array
::value('postal_greeting_id', $details)
1113 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1114 //Though Profile type is contact we need
1115 //Individual/Household/Organization for setting Greetings.
1116 if ($profileType == 'Contact') {
1117 $profileType = 'Individual';
1118 //if we editing Household/Organization.
1120 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1123 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1124 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1127 foreach ($greetingTypes as $key => $value) {
1128 if (!array_key_exists($key, $params)) {
1129 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1134 $transaction = new CRM_Core_Transaction();
1136 //used to send subscribe mail to the group which user want.
1137 //if the profile double option in is enabled
1141 foreach ($params as $name => $values) {
1142 if (substr($name, 0, 6) == 'email-') {
1143 $result['email'] = $values;
1147 //array of group id, subscribed by contact
1149 if (!empty($params['group']) &&
1150 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1152 $groupSubscribed = [];
1153 if (!empty($result['email'])) {
1155 $contactGroups = new CRM_Contact_DAO_GroupContact();
1156 $contactGroups->contact_id
= $this->_id
;
1157 $contactGroups->status
= 'Added';
1158 $contactGroups->find();
1160 while ($contactGroups->fetch()) {
1161 $contactGroup[] = $contactGroups->group_id
;
1162 $groupSubscribed[$contactGroups->group_id
] = 1;
1165 foreach ($params['group'] as $key => $val) {
1167 unset($params['group'][$key]);
1170 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1171 $key, 'group_type', 'id'
1173 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1174 substr($groupTypes, 1, -1)
1176 //filter group of mailing type and unset it from params
1177 if (in_array(2, $groupType)) {
1178 //if group is already subscribed , ignore it
1179 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1180 if (!isset($groupExist)) {
1181 $mailingType[] = $key;
1182 unset($params['group'][$key]);
1189 $addToGroupId = CRM_Utils_Array
::value('add_to_group_id', $this->_ufGroup
);
1190 if (!empty($addToGroupId)) {
1191 //run same check whether group is a mailing list
1192 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1193 $addToGroupId, 'group_type', 'id'
1195 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1196 substr($groupTypes, 1, -1)
1198 //filter group of mailing type and unset it from params
1199 if (in_array(2, $groupType) && !empty($result['email']) &&
1200 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1202 if (!count($contactGroup)) {
1203 //array of group id, subscribed by contact
1206 $contactGroups = new CRM_Contact_DAO_GroupContact();
1207 $contactGroups->contact_id
= $this->_id
;
1208 $contactGroups->status
= 'Added';
1209 $contactGroups->find();
1211 while ($contactGroups->fetch()) {
1212 $contactGroup[] = $contactGroups->group_id
;
1213 $groupSubscribed[$contactGroups->group_id
] = 1;
1217 //if group is already subscribed , ignore it
1218 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1219 if (!isset($groupExist)) {
1220 $mailingType[] = $addToGroupId;
1221 $addToGroupId = NULL;
1225 // since we are directly adding contact to group lets unset it from mailing
1226 if ($key = array_search($addToGroupId, $mailingType)) {
1227 unset($mailingType[$key]);
1233 $params['group'] = $groupSubscribed;
1236 // commenting below code, since we potentially
1237 // triggered maximum name field formatting cases during CRM-4430.
1239 // $params['preserveDBName'] = true;
1241 $profileFields = $this->_fields
;
1242 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1243 $profileFields = $activityParams = [];
1244 foreach ($this->_fields
as $fieldName => $field) {
1245 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1246 if (isset($params[$fieldName])) {
1247 $activityParams[$fieldName] = $params[$fieldName];
1249 if (isset($params['activity_date_time'])) {
1250 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1252 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1253 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1257 $profileFields[$fieldName] = $field;
1261 if (!empty($activityParams)) {
1262 $activityParams['version'] = 3;
1263 $activityParams['id'] = $this->_activityId
;
1264 $activityParams['skipRecentView'] = TRUE;
1265 civicrm_api('Activity', 'create', $activityParams);
1269 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1270 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1273 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1283 //mailing type group
1284 if (!empty($mailingType)) {
1285 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1287 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1292 $ufGroups[$this->_gid
] = 1;
1294 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1295 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1298 foreach ($ufGroups as $gId => $val) {
1299 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1300 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1301 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1305 //create CMS user (if CMS user option is selected in profile)
1306 if (!empty($params['cms_create_account']) &&
1307 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1309 $params['contactID'] = $this->_id
;
1310 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1311 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1312 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1313 $transaction->rollback();
1314 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1315 'reset=1&gid=' . $this->_gid
1320 $transaction->commit();
1324 * @param null $suffix
1326 * @return null|string
1328 public function checkTemplateFileExists($suffix = NULL) {
1330 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1331 $template = CRM_Core_Form
::getTemplate();
1332 if ($template->template_exists($templateFile)) {
1333 return $templateFile;
1336 // lets see if we have customized by name
1337 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1339 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1340 if ($template->template_exists($templateFile)) {
1341 return $templateFile;
1349 * Use the form name to create the tpl file name.
1353 public function getTemplateFileName() {
1354 $fileName = $this->checkTemplateFileExists();
1355 return $fileName ?
$fileName : parent
::getTemplateFileName();
1359 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1360 * i.e. we dont override
1364 public function overrideExtraTemplateFileName() {
1365 $fileName = $this->checkTemplateFileExists('extra.');
1366 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();