3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
36 * This class generates form components for custom data
38 * It delegates the work to lower level subclasses and integrates the changes
39 * back in. It also uses a lot of functionality with the CRM API's, so any change
40 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
43 class CRM_Profile_Form
extends CRM_Core_Form
{
52 protected $_skipPermission = FALSE;
55 * The contact id that we are editing.
62 * The group id that we are editing.
69 * @var array details of the UFGroup used on this page
71 protected $_ufGroup = array('name' => 'unknown');
74 * The group id that we are passing in url.
81 * Name of button for saving matching contacts.
84 protected $_duplicateButtonName;
86 * The title of the category we are editing.
93 * The fields needed to build this form.
100 * store contact details.
107 * Do we allow updates of the contact.
111 public $_isUpdateDupe = 0;
114 * Dedupe using a specific rule (CRM-6131).
115 * Not currently exposed in profile settings, but can be set in a buildForm hook.
117 public $_ruleGroupID = NULL;
119 public $_isAddCaptcha = FALSE;
121 protected $_isPermissionedChecksum = FALSE;
124 * THe context from which we came from, allows us to go there if redirect not set.
131 * THe contact type for registration case.
135 protected $_ctype = NULL;
138 * Store profile ids if multiple profile ids are passed using comma separated.
139 * Currently lets implement this functionality only for dialog mode.
141 protected $_profileIds = array();
144 * Contact profile having activity fields?
148 protected $_isContactActivityProfile = FALSE;
151 * Activity Id connected to the profile.
155 protected $_activityId = NULL;
158 protected $_multiRecordFields = NULL;
160 protected $_recordId = NULL;
163 * Action for multi record profile (create/edit/delete).
167 protected $_multiRecord = NULL;
169 protected $_multiRecordProfile = FALSE;
171 protected $_recordExists = TRUE;
173 protected $_customGroupTitle = NULL;
175 protected $_deleteButtonName = NULL;
177 protected $_customGroupId = NULL;
179 protected $_currentUserID = NULL;
180 protected $_session = NULL;
183 * Explicitly declare the entity api name.
185 public function getDefaultEntity() {
190 * Pre processing work done here.
192 * gets session variables for table name, id of entity in table, type of entity and stores them.
194 public function preProcess() {
195 $this->_id
= $this->get('id');
196 $this->_profileIds
= $this->get('profileIds');
197 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
198 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
200 //unset from session when $_GET doesn't have it
201 //except when the form is submitted
203 if (!array_key_exists('multiRecord', $_GET)) {
204 $this->set('multiRecord', NULL);
206 if (!array_key_exists('recordId', $_GET)) {
207 $this->set('recordId', NULL);
211 $this->_session
= CRM_Core_Session
::singleton();
212 $this->_currentUserID
= $this->_session
->get('userID');
214 if ($this->_mode
== self
::MODE_EDIT
) {
215 //specifies the action being done on a multi record field
216 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
217 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
218 if ($this->_multiRecord
) {
219 $this->set('multiRecord', $this->_multiRecord
);
222 if ($this->_multiRecord
&&
223 !in_array($this->_multiRecord
, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
))
225 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
228 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
230 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0));
232 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
234 foreach ($gids as $pfId) {
235 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
239 // check if we are rendering mixed profiles
240 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
241 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
244 // for now consider 1'st profile as primary profile and validate it
245 // i.e check for profile type etc.
246 // FIX ME: validations for other than primary
247 $this->_gid
= $this->_profileIds
[0];
248 $this->set('gid', $this->_gid
);
249 $this->set('profileIds', $this->_profileIds
);
253 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
254 $this->set('gid', $this->_gid
);
257 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
258 if (is_numeric($this->_activityId
)) {
259 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
260 if ($latestRevisionId) {
261 $this->_activityId
= $latestRevisionId;
264 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
266 //get values for ufGroupName, captcha and dupe update.
268 $dao = new CRM_Core_DAO_UFGroup();
269 $dao->id
= $this->_gid
;
270 if ($dao->find(TRUE)) {
271 $this->_isUpdateDupe
= $dao->is_update_dupe
;
272 $this->_isAddCaptcha
= $dao->add_captcha
;
273 $this->_ufGroup
= (array) $dao;
277 if (!CRM_Utils_Array
::value('is_active', $this->_ufGroup
)) {
278 CRM_Core_Error
::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(
283 $this->assign('ufGroupName', $this->_ufGroup
['name']);
285 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
287 // if we don't have a gid use the default, else just use that specific gid
288 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
289 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
290 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
292 elseif ($this->_mode
== self
::MODE_SEARCH
) {
293 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
294 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
298 $this->_skipPermission
,
299 CRM_Core_Permission
::SEARCH
303 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
306 $this->_skipPermission
,
308 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
310 $multiRecordFieldListing = FALSE;
311 //using selector for listing of multi-record fields
312 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
313 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
315 if ($this->_multiRecord
) {
316 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
317 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
320 $this->_recordId
= NULL;
321 $this->set('recordId', NULL);
323 //record id is necessary for _multiRecord view and update/edit action
324 if (!$this->_recordId
325 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
327 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
328 array(1 => $this->_gid
)
331 elseif (empty($this->_multiRecordFields
)) {
332 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
333 array(1 => $this->_gid
)
337 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
338 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles(array($fieldId));
339 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
340 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
342 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
343 //record exists check
344 foreach ($this->_multiRecordFields
as $key => $field) {
345 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
347 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
349 if (array_key_exists($this->_recordId
, $getValues)) {
350 $this->_recordExists
= TRUE;
353 $this->_recordExists
= FALSE;
354 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
355 CRM_Core_Session
::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', array(1 => $this->_recordId
)), ts('Record doesnot exist'), 'alert');
359 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
360 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
361 if ($this->_maxRecordLimit
) {
362 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
367 elseif (!empty($this->_multiRecordFields
)
368 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(
369 CRM_Core_Action
::DELETE
,
370 CRM_Core_Action
::UPDATE
,
373 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
374 //multi-record listing page
375 $multiRecordFieldListing = TRUE;
376 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
377 $cs = $this->get('cs');
378 $page->set('pageCheckSum', $cs);
379 $page->set('contactId', $this->_id
);
380 $page->set('profileId', $this->_gid
);
381 $page->set('action', CRM_Core_Action
::BROWSE
);
382 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
386 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
388 // is profile double-opt in?
389 if (!empty($this->_fields
['group']) &&
390 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
393 foreach ($this->_fields
as $name => $values) {
394 if (substr($name, 0, 6) == 'email-') {
400 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
401 $this->_session
->setStatus($status);
405 //transferring all the multi-record custom fields in _fields
406 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
407 $this->_fields
= $this->_multiRecordFields
;
408 $this->_multiRecordProfile
= TRUE;
410 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
411 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
412 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
416 if (!is_array($this->_fields
)) {
417 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
418 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
423 * Set default values for the form. Note that in edit/view mode
424 * the default values are retrieved from the database
427 public function setDefaultsValues() {
428 $this->_defaults
= array();
429 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
433 if ($this->_mode
!= self
::MODE_SEARCH
) {
434 // set default values for country / state to start with
435 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
438 if ($this->_id
&& !$this->_multiRecordProfile
) {
439 if ($this->_isContactActivityProfile
) {
440 $contactFields = $activityFields = array();
441 foreach ($this->_fields
as $fieldName => $field) {
442 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
443 $activityFields[$fieldName] = $field;
446 $contactFields[$fieldName] = $field;
450 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
451 if ($this->_activityId
) {
452 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
456 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
460 //set custom field defaults
461 if ($this->_multiRecordProfile
) {
462 foreach ($this->_multiRecordFields
as $key => $field) {
463 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
466 $defaultValues = array();
467 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
468 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
469 if ($this->_recordExists
== TRUE) {
470 $defaultValues = $defaultValues[$this->_recordId
];
473 $defaultValues = NULL;
477 if (!empty($defaultValues)) {
478 foreach ($defaultValues as $key => $value) {
479 $name = "custom_{$key}";
480 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
481 if ($htmlType != 'File') {
483 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
492 $this->_defaults
[$name] = "";
496 if ($htmlType == 'File') {
497 $entityId = $this->_id
;
498 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
501 $entityId = $this->_activityId
;
506 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key, $value);
510 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
512 $deleteExtra = ts("Are you sure you want to delete attached file?");
513 $fileId = $url['file_id'];
514 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId);
515 $deleteURL = CRM_Utils_System
::url('civicrm/file',
516 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
518 $text = ts("Delete Attached File");
519 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
521 // also delete the required rule that we've set on the form element
522 $this->removeFileRequiredRules($name);
529 foreach ($this->_fields
as $name => $field) {
530 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
531 $htmlType = $field['html_type'];
532 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
533 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
535 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
543 if ($htmlType == 'File') {
544 $entityId = $this->_id
;
545 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
546 $entityId = $this->_activityId
;
548 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
551 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
553 $deleteExtra = ts("Are you sure you want to delete attached file?");
554 $fileId = $url['file_id'];
555 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
556 $deleteURL = CRM_Utils_System
::url('civicrm/file',
557 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
559 $text = ts("Delete Attached File");
560 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
562 // also delete the required rule that we've set on the form element
563 $this->removeFileRequiredRules($field['name']);
569 if (isset($customFiles)) {
570 $this->assign('customFiles', $customFiles);
573 if ($this->_multiRecordProfile
) {
574 $this->setDefaults($this->_defaults
);
578 if (!empty($this->_defaults
['image_URL'])) {
579 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
580 $this->removeFileRequiredRules('image_URL');
583 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
584 !empty($this->_defaults
['contact_sub_type'])
586 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
587 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
591 $this->setDefaults($this->_defaults
);
595 * Build the form object.
598 public function buildQuickForm() {
599 $this->add('hidden', 'gid', $this->_gid
);
601 switch ($this->_mode
) {
602 case self
::MODE_CREATE
:
603 case self
::MODE_EDIT
:
604 case self
::MODE_REGISTER
:
605 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
608 case self
::MODE_SEARCH
:
609 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
615 //lets have single status message, CRM-4363
617 $statusMessage = NULL;
618 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
622 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
623 if (!$this->_recordExists
) {
624 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
627 $this->assign('deleteRecord', TRUE);
632 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
634 // we should not allow component and mix profiles in search mode
635 if ($this->_mode
!= self
::MODE_REGISTER
) {
636 //check for mix profile fields (eg: individual + other contact type)
637 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
638 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
639 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
640 if (!empty($errors)) {
641 $statusMessage = array_pop($errors);
646 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
651 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
654 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
655 $contactType = $contactTypes[0];
657 array_shift($contactTypes);
658 $contactSubtypes = $contactTypes;
660 $profileSubType = FALSE;
661 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
662 $profileSubType = $profileType;
663 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
667 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
668 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
669 ($profileType != $contactType))
672 if (!$statusMessage) {
673 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
674 array(1 => $profileSubType ?
$profileSubType : $profileType));
682 array("Membership", "Participant", "Contribution")
686 if (!$statusMessage) {
687 $statusMessage = ts('Profile is not configured for the selected action.');
692 //lets have single status message,
693 $this->assign('statusMessage', $statusMessage);
698 $this->assign('id', $this->_id
);
699 $this->assign('mode', $this->_mode
);
700 $this->assign('action', $this->_action
);
701 $this->assign('fields', $this->_fields
);
702 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
704 // should we restrict what we display
706 if ($this->_mode
== self
::MODE_EDIT
) {
708 // show all fields that are visible:
709 // if we are a admin OR the same user OR acl-user with access to the profile
710 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
712 CRM_Core_Permission
::check('administer users') ||
713 $this->_id
== $this->_currentUserID ||
714 $this->_isPermissionedChecksum ||
718 CRM_Core_Permission
::EDIT
,
721 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
729 // if false, user is not logged-in.
731 if (!$this->_currentUserID
) {
732 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
733 $primaryLocationType = $defaultLocationType->id
;
736 $this->assign('anonUser', $anonUser);
738 $addCaptcha = array();
739 $emailPresent = FALSE;
741 // add the form elements
742 foreach ($this->_fields
as $name => $field) {
743 // make sure that there is enough permission to expose this field
744 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
745 unset($this->_fields
[$name]);
749 // since the CMS manages the email field, suppress the email display if in
750 // register mode which occur within the CMS form
751 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
752 unset($this->_fields
[$name]);
756 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
758 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
760 if ($field['add_to_group_id']) {
761 $addToGroupId = $field['add_to_group_id'];
764 //build array for captcha
765 if ($field['add_captcha']) {
766 $addCaptcha[$field['group_id']] = $field['add_captcha'];
769 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
770 $emailPresent = TRUE;
771 $this->_mail
= $name;
775 // add captcha only for create mode.
776 if ($this->_mode
== self
::MODE_CREATE
) {
777 // suppress captcha for logged in users only
778 if ($this->_currentUserID
) {
779 $this->_isAddCaptcha
= FALSE;
781 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
782 $this->_isAddCaptcha
= TRUE;
786 $dao = new CRM_Core_DAO_UFGroup();
787 $dao->id
= $this->_gid
;
789 $dao->addSelect('is_update_dupe');
790 if ($dao->find(TRUE)) {
791 if ($dao->is_update_dupe
) {
792 $this->_isUpdateDupe
= $dao->is_update_dupe
;
798 $this->_isAddCaptcha
= FALSE;
801 //finally add captcha to form.
802 if ($this->_isAddCaptcha
) {
803 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
804 $captcha->add($this);
806 $this->assign("isCaptcha", $this->_isAddCaptcha
);
808 if ($this->_mode
!= self
::MODE_SEARCH
) {
809 if (isset($addToGroupId)) {
810 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
814 //let's do set defaults for the profile
815 $this->setDefaultsValues();
817 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
819 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
820 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
823 $this->assign('showCMS', FALSE);
826 $this->assign('groupId', $this->_gid
);
828 // if view mode pls freeze it with the done button.
829 if ($this->_action
& CRM_Core_Action
::VIEW
) {
833 if ($this->_context
== 'dialog') {
836 $this->_duplicateButtonName
,
837 ts('Save Matching Contact')
843 * Validate profile and provided activity Id.
845 * @param int $activityId
846 * @param int $contactId
851 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
854 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
858 $activityDetails = array();
859 $activityParams = array('id' => $activityId);
860 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
862 if (empty($activityDetails)) {
863 $errors[] = ts('Invalid Activity Id (aid).');
867 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
869 if ((!empty($profileActivityTypes['Activity']) &&
870 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
872 (!in_array($contactId, $activityDetails['assignee_contact']) &&
873 !in_array($contactId, $activityDetails['target_contact'])
876 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
885 * @param array $fields
886 * The input form values.
887 * @param array $files
888 * The uploaded files if any.
889 * @param CRM_Core_Form $form
893 * true if no errors, else array of errors
895 public static function formRule($fields, $files, $form) {
896 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
899 // if no values, return
900 if (empty($fields)) {
906 // hack we use a -1 in options to indicate that its registration
908 $form->_isUpdateDupe
= 1;
911 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
915 // don't check for duplicates during registration validation: CRM-375
916 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
918 if (!empty($fields['email-Primary'])) {
919 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
923 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
924 $fields['phone-Primary'] = $fields['phone-Primary-1'];
927 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
928 // If all profile fields is of Contact Type then consider
929 // profile is of Individual type(default).
931 $ctype = 'Individual';
934 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
936 $exceptions = array();
939 // for edit mode we need to allow our own record to be a dupe match!
940 $exceptions = array($form->_session
->get('userID'));
943 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
945 ($form->_context
=== 'dialog' ?
'Supervised' : 'Unsupervised'),
951 if ($form->_isUpdateDupe
== 2) {
952 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
954 elseif ($form->_isUpdateDupe
== 1) {
956 $form->_id
= $ids[0];
960 if ($form->_context
== 'dialog') {
961 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
963 $duplicateContactsLinks = '<div class="matching-contacts-found">';
964 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
965 'count' => count($contactLinks['rows']),
966 'plural' => '%count matching contacts were found.<br />',
968 if ($contactLinks['msg'] == 'view') {
969 $duplicateContactsLinks .= ts('You can View the existing contact.', array(
970 'count' => count($contactLinks['rows']),
971 'plural' => 'You can View the existing contacts.',
975 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array(
976 'count' => count($contactLinks['rows']),
977 'plural' => 'You can View or Edit the existing contacts.',
980 $duplicateContactsLinks .= '</div>';
981 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
983 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
985 $row .= ' <td class="matching-contacts-name"> ';
986 $row .= $contactLinks['rows'][$i]['display_name'];
988 $row .= ' <td class="matching-contacts-email"> ';
989 $row .= $contactLinks['rows'][$i]['primary_email'];
991 $row .= ' <td class="action-items"> ';
992 $row .= $contactLinks['rows'][$i]['view'] . ' ';
993 $row .= $contactLinks['rows'][$i]['edit'];
998 $duplicateContactsLinks .= $row . '</table>';
999 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1001 $errors['_qf_default'] = $duplicateContactsLinks;
1003 // let smarty know that there are duplicates
1004 $template = CRM_Core_Smarty
::singleton();
1005 $template->assign('isDuplicate', 1);
1008 $errors['_qf_default'] = ts('A record already exists with the same information.');
1014 foreach ($fields as $key => $value) {
1015 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1016 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1017 // Validate Country - State list
1018 $countryId = $fields["country-{$locTypeId}"];
1019 $stateProvinceId = $value;
1021 if ($stateProvinceId && $countryId) {
1022 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1023 $stateProvinceDAO->id
= $stateProvinceId;
1024 $stateProvinceDAO->find(TRUE);
1026 if ($stateProvinceDAO->country_id
!= $countryId) {
1027 // country mismatch hence display error
1028 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1029 $countries = CRM_Core_PseudoConstant
::country();
1030 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1035 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1036 // Validate County - State list
1037 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1040 if ($countyId && $stateProvinceId) {
1041 $countyDAO = new CRM_Core_DAO_County();
1042 $countyDAO->id
= $countyId;
1043 $countyDAO->find(TRUE);
1045 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1046 // state province mismatch hence display error
1047 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1048 $counties = CRM_Core_PseudoConstant
::county();
1049 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1054 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1055 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1056 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1057 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1058 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1059 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1065 return empty($errors) ?
TRUE : $errors;
1069 * Process the user submitted custom data values.
1072 public function postProcess() {
1073 $params = $this->controller
->exportValues($this->_name
);
1075 //if the delete record button is clicked
1076 if ($this->_deleteButtonName
) {
1077 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1078 $filterParams['id'] = $this->_customGroupId
;
1079 $returnProperties = array('is_multiple', 'table_name');
1080 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1081 if (!empty($returnValues['is_multiple'])) {
1082 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1083 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1085 1 => array($this->_recordId
, 'Integer'),
1086 2 => array($this->_id
, 'Integer'),
1088 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1089 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1095 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1096 if (!empty($params['image_URL'])) {
1097 CRM_Contact_BAO_Contact
::processImageParams($params);
1100 $greetingTypes = array(
1101 'addressee' => 'addressee_id',
1102 'email_greeting' => 'email_greeting_id',
1103 'postal_greeting' => 'postal_greeting_id',
1108 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1111 $details = $contactDetails[0][$this->_id
];
1113 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1114 CRM_Utils_Array
::value('postal_greeting_id', $details)
1118 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1119 //Though Profile type is contact we need
1120 //Individual/Household/Organization for setting Greetings.
1121 if ($profileType == 'Contact') {
1122 $profileType = 'Individual';
1123 //if we editing Household/Organization.
1125 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1128 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1129 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1132 foreach ($greetingTypes as $key => $value) {
1133 if (!array_key_exists($key, $params)) {
1134 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1139 $transaction = new CRM_Core_Transaction();
1141 //used to send subscribe mail to the group which user want.
1142 //if the profile double option in is enabled
1143 $mailingType = array();
1146 foreach ($params as $name => $values) {
1147 if (substr($name, 0, 6) == 'email-') {
1148 $result['email'] = $values;
1152 //array of group id, subscribed by contact
1153 $contactGroup = array();
1154 if (!empty($params['group']) &&
1155 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1157 $groupSubscribed = array();
1158 if (!empty($result['email'])) {
1160 $contactGroups = new CRM_Contact_DAO_GroupContact();
1161 $contactGroups->contact_id
= $this->_id
;
1162 $contactGroups->status
= 'Added';
1163 $contactGroups->find();
1164 $contactGroup = array();
1165 while ($contactGroups->fetch()) {
1166 $contactGroup[] = $contactGroups->group_id
;
1167 $groupSubscribed[$contactGroups->group_id
] = 1;
1170 foreach ($params['group'] as $key => $val) {
1172 unset($params['group'][$key]);
1175 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1176 $key, 'group_type', 'id'
1178 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1179 substr($groupTypes, 1, -1)
1181 //filter group of mailing type and unset it from params
1182 if (in_array(2, $groupType)) {
1183 //if group is already subscribed , ignore it
1184 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1185 if (!isset($groupExist)) {
1186 $mailingType[] = $key;
1187 unset($params['group'][$key]);
1194 $addToGroupId = CRM_Utils_Array
::value('add_to_group_id', $this->_ufGroup
);
1195 if (!empty($addToGroupId)) {
1196 //run same check whether group is a mailing list
1197 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1198 $addToGroupId, 'group_type', 'id'
1200 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1201 substr($groupTypes, 1, -1)
1203 //filter group of mailing type and unset it from params
1204 if (in_array(2, $groupType) && !empty($result['email']) &&
1205 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1207 if (!count($contactGroup)) {
1208 //array of group id, subscribed by contact
1209 $contactGroup = array();
1211 $contactGroups = new CRM_Contact_DAO_GroupContact();
1212 $contactGroups->contact_id
= $this->_id
;
1213 $contactGroups->status
= 'Added';
1214 $contactGroups->find();
1215 $contactGroup = array();
1216 while ($contactGroups->fetch()) {
1217 $contactGroup[] = $contactGroups->group_id
;
1218 $groupSubscribed[$contactGroups->group_id
] = 1;
1222 //if group is already subscribed , ignore it
1223 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1224 if (!isset($groupExist)) {
1225 $mailingType[] = $addToGroupId;
1226 $addToGroupId = NULL;
1230 // since we are directly adding contact to group lets unset it from mailing
1231 if ($key = array_search($addToGroupId, $mailingType)) {
1232 unset($mailingType[$key]);
1238 $params['group'] = $groupSubscribed;
1241 // commenting below code, since we potentially
1242 // triggered maximum name field formatting cases during CRM-4430.
1244 // $params['preserveDBName'] = true;
1246 $profileFields = $this->_fields
;
1247 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1248 $profileFields = $activityParams = array();
1249 foreach ($this->_fields
as $fieldName => $field) {
1250 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1251 if (isset($params[$fieldName])) {
1252 $activityParams[$fieldName] = $params[$fieldName];
1254 if (isset($params['activity_date_time'])) {
1255 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1257 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1258 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1262 $profileFields[$fieldName] = $field;
1266 if (!empty($activityParams)) {
1267 $activityParams['version'] = 3;
1268 $activityParams['id'] = $this->_activityId
;
1269 $activityParams['skipRecentView'] = TRUE;
1270 civicrm_api('Activity', 'create', $activityParams);
1274 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1275 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1278 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1288 //mailing type group
1289 if (!empty($mailingType)) {
1290 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1292 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1295 $ufGroups = array();
1297 $ufGroups[$this->_gid
] = 1;
1299 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1300 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1303 foreach ($ufGroups as $gId => $val) {
1304 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1305 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1306 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1310 //create CMS user (if CMS user option is selected in profile)
1311 if (!empty($params['cms_create_account']) &&
1312 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1314 $params['contactID'] = $this->_id
;
1315 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1316 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1317 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1318 $transaction->rollback();
1319 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1320 'reset=1&gid=' . $this->_gid
1325 $transaction->commit();
1329 * @param null $suffix
1331 * @return null|string
1333 public function checkTemplateFileExists($suffix = NULL) {
1335 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1336 $template = CRM_Core_Form
::getTemplate();
1337 if ($template->template_exists($templateFile)) {
1338 return $templateFile;
1341 // lets see if we have customized by name
1342 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1344 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1345 if ($template->template_exists($templateFile)) {
1346 return $templateFile;
1354 * Use the form name to create the tpl file name.
1358 public function getTemplateFileName() {
1359 $fileName = $this->checkTemplateFileExists();
1360 return $fileName ?
$fileName : parent
::getTemplateFileName();
1364 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1365 * i.e. we dont override
1369 public function overrideExtraTemplateFileName() {
1370 $fileName = $this->checkTemplateFileExists('extra.');
1371 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();