3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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', 'String', $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 $deleteURL = CRM_Utils_System
::url('civicrm/file',
515 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
517 $text = ts("Delete Attached File");
518 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
520 // also delete the required rule that we've set on the form element
521 $this->removeFileRequiredRules($name);
528 foreach ($this->_fields
as $name => $field) {
529 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
530 $htmlType = $field['html_type'];
531 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
532 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
534 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
542 if ($htmlType == 'File') {
543 $entityId = $this->_id
;
544 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
545 $entityId = $this->_activityId
;
547 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
550 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
552 $deleteExtra = ts("Are you sure you want to delete attached file?");
553 $fileId = $url['file_id'];
554 $deleteURL = CRM_Utils_System
::url('civicrm/file',
555 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
557 $text = ts("Delete Attached File");
558 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
560 // also delete the required rule that we've set on the form element
561 $this->removeFileRequiredRules($field['name']);
567 if (isset($customFiles)) {
568 $this->assign('customFiles', $customFiles);
571 if ($this->_multiRecordProfile
) {
572 $this->setDefaults($this->_defaults
);
576 if (!empty($this->_defaults
['image_URL'])) {
577 $this->assign("imageURL", CRM_Utils_File
::getImageURL($this->_defaults
['image_URL']));
578 $this->removeFileRequiredRules('image_URL');
581 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
582 !empty($this->_defaults
['contact_sub_type'])
584 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
585 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
589 $this->setDefaults($this->_defaults
);
593 * Build the form object.
596 public function buildQuickForm() {
597 $this->add('hidden', 'gid', $this->_gid
);
599 switch ($this->_mode
) {
600 case self
::MODE_CREATE
:
601 case self
::MODE_EDIT
:
602 case self
::MODE_REGISTER
:
603 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
606 case self
::MODE_SEARCH
:
607 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
613 //lets have single status message, CRM-4363
615 $statusMessage = NULL;
616 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
620 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
621 if (!$this->_recordExists
) {
622 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
625 $this->assign('deleteRecord', TRUE);
630 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
632 // we should not allow component and mix profiles in search mode
633 if ($this->_mode
!= self
::MODE_REGISTER
) {
634 //check for mix profile fields (eg: individual + other contact type)
635 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
636 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
637 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
638 if (!empty($errors)) {
639 $statusMessage = array_pop($errors);
644 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
649 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
652 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
653 $contactType = $contactTypes[0];
655 array_shift($contactTypes);
656 $contactSubtypes = $contactTypes;
658 $profileSubType = FALSE;
659 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
660 $profileSubType = $profileType;
661 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
665 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
666 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
667 ($profileType != $contactType))
670 if (!$statusMessage) {
671 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
672 array(1 => $profileSubType ?
$profileSubType : $profileType));
680 array("Membership", "Participant", "Contribution")
684 if (!$statusMessage) {
685 $statusMessage = ts('Profile is not configured for the selected action.');
690 //lets have single status message,
691 $this->assign('statusMessage', $statusMessage);
696 $this->assign('id', $this->_id
);
697 $this->assign('mode', $this->_mode
);
698 $this->assign('action', $this->_action
);
699 $this->assign('fields', $this->_fields
);
700 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
702 // should we restrict what we display
704 if ($this->_mode
== self
::MODE_EDIT
) {
706 // show all fields that are visible:
707 // if we are a admin OR the same user OR acl-user with access to the profile
708 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
710 CRM_Core_Permission
::check('administer users') ||
711 $this->_id
== $this->_currentUserID ||
712 $this->_isPermissionedChecksum ||
716 CRM_Core_Permission
::EDIT
,
719 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
727 // if false, user is not logged-in.
729 if (!$this->_currentUserID
) {
730 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
731 $primaryLocationType = $defaultLocationType->id
;
734 $this->assign('anonUser', $anonUser);
736 $addCaptcha = array();
737 $emailPresent = FALSE;
739 // add the form elements
740 foreach ($this->_fields
as $name => $field) {
741 // make sure that there is enough permission to expose this field
742 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
743 unset($this->_fields
[$name]);
747 // since the CMS manages the email field, suppress the email display if in
748 // register mode which occur within the CMS form
749 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
750 unset($this->_fields
[$name]);
754 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
756 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
758 if ($field['add_to_group_id']) {
759 $addToGroupId = $field['add_to_group_id'];
762 //build array for captcha
763 if ($field['add_captcha']) {
764 $addCaptcha[$field['group_id']] = $field['add_captcha'];
767 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
768 $emailPresent = TRUE;
769 $this->_mail
= $name;
773 // add captcha only for create mode.
774 if ($this->_mode
== self
::MODE_CREATE
) {
775 // suppress captcha for logged in users only
776 if ($this->_currentUserID
) {
777 $this->_isAddCaptcha
= FALSE;
779 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
780 $this->_isAddCaptcha
= TRUE;
784 $dao = new CRM_Core_DAO_UFGroup();
785 $dao->id
= $this->_gid
;
787 $dao->addSelect('is_update_dupe');
788 if ($dao->find(TRUE)) {
789 if ($dao->is_update_dupe
) {
790 $this->_isUpdateDupe
= $dao->is_update_dupe
;
796 $this->_isAddCaptcha
= FALSE;
799 //finally add captcha to form.
800 if ($this->_isAddCaptcha
) {
801 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
802 $captcha->add($this);
804 $this->assign("isCaptcha", $this->_isAddCaptcha
);
806 if ($this->_mode
!= self
::MODE_SEARCH
) {
807 if (isset($addToGroupId)) {
808 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
812 //let's do set defaults for the profile
813 $this->setDefaultsValues();
815 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
817 if ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
) {
818 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
821 $this->assign('showCMS', FALSE);
824 $this->assign('groupId', $this->_gid
);
826 // if view mode pls freeze it with the done button.
827 if ($this->_action
& CRM_Core_Action
::VIEW
) {
831 if ($this->_context
== 'dialog') {
834 $this->_duplicateButtonName
,
835 ts('Save Matching Contact')
841 * Validate profile and provided activity Id.
843 * @param int $activityId
844 * @param int $contactId
849 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
852 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
856 $activityDetails = array();
857 $activityParams = array('id' => $activityId);
858 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
860 if (empty($activityDetails)) {
861 $errors[] = 'Invalid Activity Id (aid).';
865 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
867 if ((!empty($profileActivityTypes['Activity']) &&
868 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
870 (!in_array($contactId, $activityDetails['assignee_contact']) &&
871 !in_array($contactId, $activityDetails['target_contact'])
874 $errors[] = 'This activity cannot be edited or viewed via this profile.';
883 * @param array $fields
884 * The input form values.
885 * @param array $files
886 * The uploaded files if any.
887 * @param CRM_Core_Form $form
891 * true if no errors, else array of errors
893 public static function formRule($fields, $files, $form) {
894 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
897 // if no values, return
898 if (empty($fields)) {
904 // hack we use a -1 in options to indicate that its registration
906 $form->_isUpdateDupe
= 1;
909 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
913 // don't check for duplicates during registration validation: CRM-375
914 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
916 if (!empty($fields['email-Primary'])) {
917 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
921 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
922 $fields['phone-Primary'] = $fields['phone-Primary-1'];
925 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
926 // If all profile fields is of Contact Type then consider
927 // profile is of Individual type(default).
929 $ctype = 'Individual';
931 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $ctype);
932 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
934 $exceptions = array();
937 // for edit mode we need to allow our own record to be a dupe match!
938 $exceptions = array($form->_session
->get('userID'));
941 // for dialog mode we should always use fuzzy rule.
942 $ruleType = 'Unsupervised';
943 if ($form->_context
== 'dialog') {
944 $ruleType = 'Supervised';
947 $dedupeParams['check_permission'] = FALSE;
948 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams,
955 if ($form->_isUpdateDupe
== 2) {
956 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
958 elseif ($form->_isUpdateDupe
== 1) {
960 $form->_id
= $ids[0];
964 if ($form->_context
== 'dialog') {
965 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
967 $duplicateContactsLinks = '<div class="matching-contacts-found">';
968 $duplicateContactsLinks .= ts('One matching contact was found. ', array(
969 'count' => count($contactLinks['rows']),
970 'plural' => '%count matching contacts were found.<br />',
972 if ($contactLinks['msg'] == 'view') {
973 $duplicateContactsLinks .= ts('You can View the existing contact.', array(
974 'count' => count($contactLinks['rows']),
975 'plural' => 'You can View the existing contacts.',
979 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array(
980 'count' => count($contactLinks['rows']),
981 'plural' => 'You can View or Edit the existing contacts.',
984 $duplicateContactsLinks .= '</div>';
985 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
987 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
989 $row .= ' <td class="matching-contacts-name"> ';
990 $row .= $contactLinks['rows'][$i]['display_name'];
992 $row .= ' <td class="matching-contacts-email"> ';
993 $row .= $contactLinks['rows'][$i]['primary_email'];
995 $row .= ' <td class="action-items"> ';
996 $row .= $contactLinks['rows'][$i]['view'] . ' ';
997 $row .= $contactLinks['rows'][$i]['edit'];
1002 $duplicateContactsLinks .= $row . '</table>';
1003 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1005 $errors['_qf_default'] = $duplicateContactsLinks;
1007 // let smarty know that there are duplicates
1008 $template = CRM_Core_Smarty
::singleton();
1009 $template->assign('isDuplicate', 1);
1012 $errors['_qf_default'] = ts('A record already exists with the same information.');
1018 foreach ($fields as $key => $value) {
1019 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1020 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1021 // Validate Country - State list
1022 $countryId = $fields["country-{$locTypeId}"];
1023 $stateProvinceId = $value;
1025 if ($stateProvinceId && $countryId) {
1026 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1027 $stateProvinceDAO->id
= $stateProvinceId;
1028 $stateProvinceDAO->find(TRUE);
1030 if ($stateProvinceDAO->country_id
!= $countryId) {
1031 // country mismatch hence display error
1032 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1033 $countries = CRM_Core_PseudoConstant
::country();
1034 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1039 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1040 // Validate County - State list
1041 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1044 if ($countyId && $stateProvinceId) {
1045 $countyDAO = new CRM_Core_DAO_County();
1046 $countyDAO->id
= $countyId;
1047 $countyDAO->find(TRUE);
1049 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1050 // state province mismatch hence display error
1051 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1052 $counties = CRM_Core_PseudoConstant
::county();
1053 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1058 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1059 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1060 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1061 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1062 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1063 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1069 return empty($errors) ?
TRUE : $errors;
1073 * Process the user submitted custom data values.
1076 public function postProcess() {
1077 $params = $this->controller
->exportValues($this->_name
);
1079 //if the delete record button is clicked
1080 if ($this->_deleteButtonName
) {
1081 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1082 $filterParams['id'] = $this->_customGroupId
;
1083 $returnProperties = array('is_multiple', 'table_name');
1084 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1085 if (!empty($returnValues['is_multiple'])) {
1086 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1087 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1089 1 => array($this->_recordId
, 'Integer'),
1090 2 => array($this->_id
, 'Integer'),
1092 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1093 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1099 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1100 if (!empty($params['image_URL'])) {
1101 CRM_Contact_BAO_Contact
::processImageParams($params);
1104 $greetingTypes = array(
1105 'addressee' => 'addressee_id',
1106 'email_greeting' => 'email_greeting_id',
1107 'postal_greeting' => 'postal_greeting_id',
1112 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1115 $details = $contactDetails[0][$this->_id
];
1117 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1118 CRM_Utils_Array
::value('postal_greeting_id', $details)
1122 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1123 //Though Profile type is contact we need
1124 //Individual/Household/Organization for setting Greetings.
1125 if ($profileType == 'Contact') {
1126 $profileType = 'Individual';
1127 //if we editing Household/Organization.
1129 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1132 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1133 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1136 foreach ($greetingTypes as $key => $value) {
1137 if (!array_key_exists($key, $params)) {
1138 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1143 $transaction = new CRM_Core_Transaction();
1145 //used to send subscribe mail to the group which user want.
1146 //if the profile double option in is enabled
1147 $mailingType = array();
1150 foreach ($params as $name => $values) {
1151 if (substr($name, 0, 6) == 'email-') {
1152 $result['email'] = $values;
1156 //array of group id, subscribed by contact
1157 $contactGroup = array();
1158 if (!empty($params['group']) &&
1159 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1161 $groupSubscribed = array();
1162 if (!empty($result['email'])) {
1164 $contactGroups = new CRM_Contact_DAO_GroupContact();
1165 $contactGroups->contact_id
= $this->_id
;
1166 $contactGroups->status
= 'Added';
1167 $contactGroups->find();
1168 $contactGroup = array();
1169 while ($contactGroups->fetch()) {
1170 $contactGroup[] = $contactGroups->group_id
;
1171 $groupSubscribed[$contactGroups->group_id
] = 1;
1174 foreach ($params['group'] as $key => $val) {
1176 unset($params['group'][$key]);
1179 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1180 $key, 'group_type', 'id'
1182 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1183 substr($groupTypes, 1, -1)
1185 //filter group of mailing type and unset it from params
1186 if (in_array(2, $groupType)) {
1187 //if group is already subscribed , ignore it
1188 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1189 if (!isset($groupExist)) {
1190 $mailingType[] = $key;
1191 unset($params['group'][$key]);
1198 $addToGroupId = CRM_Utils_Array
::value('add_to_group_id', $this->_ufGroup
);
1199 if (!empty($addToGroupId)) {
1200 //run same check whether group is a mailing list
1201 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1202 $addToGroupId, 'group_type', 'id'
1204 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1205 substr($groupTypes, 1, -1)
1207 //filter group of mailing type and unset it from params
1208 if (in_array(2, $groupType) && !empty($result['email']) &&
1209 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1211 if (!count($contactGroup)) {
1212 //array of group id, subscribed by contact
1213 $contactGroup = array();
1215 $contactGroups = new CRM_Contact_DAO_GroupContact();
1216 $contactGroups->contact_id
= $this->_id
;
1217 $contactGroups->status
= 'Added';
1218 $contactGroups->find();
1219 $contactGroup = array();
1220 while ($contactGroups->fetch()) {
1221 $contactGroup[] = $contactGroups->group_id
;
1222 $groupSubscribed[$contactGroups->group_id
] = 1;
1226 //if group is already subscribed , ignore it
1227 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1228 if (!isset($groupExist)) {
1229 $mailingType[] = $addToGroupId;
1230 $addToGroupId = NULL;
1234 // since we are directly adding contact to group lets unset it from mailing
1235 if ($key = array_search($addToGroupId, $mailingType)) {
1236 unset($mailingType[$key]);
1242 $params['group'] = $groupSubscribed;
1245 // commenting below code, since we potentially
1246 // triggered maximum name field formatting cases during CRM-4430.
1248 // $params['preserveDBName'] = true;
1250 $profileFields = $this->_fields
;
1251 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1252 $profileFields = $activityParams = array();
1253 foreach ($this->_fields
as $fieldName => $field) {
1254 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1255 if (isset($params[$fieldName])) {
1256 $activityParams[$fieldName] = $params[$fieldName];
1258 if (isset($params['activity_date_time'])) {
1259 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1261 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1262 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1266 $profileFields[$fieldName] = $field;
1270 if (!empty($activityParams)) {
1271 $activityParams['version'] = 3;
1272 $activityParams['id'] = $this->_activityId
;
1273 $activityParams['skipRecentView'] = TRUE;
1274 civicrm_api('Activity', 'create', $activityParams);
1278 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1279 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1282 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1292 //mailing type group
1293 if (!empty($mailingType)) {
1294 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1296 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1299 $ufGroups = array();
1301 $ufGroups[$this->_gid
] = 1;
1303 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1304 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1307 foreach ($ufGroups as $gId => $val) {
1308 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1309 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1310 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1314 //create CMS user (if CMS user option is selected in profile)
1315 if (!empty($params['cms_create_account']) &&
1316 ($this->_mode
== self
::MODE_CREATE ||
$this->_mode
== self
::MODE_EDIT
)
1318 $params['contactID'] = $this->_id
;
1319 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1320 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1321 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1322 $transaction->rollback();
1323 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1324 'reset=1&gid=' . $this->_gid
1329 $transaction->commit();
1333 * @param null $suffix
1335 * @return null|string
1337 public function checkTemplateFileExists($suffix = NULL) {
1339 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1340 $template = CRM_Core_Form
::getTemplate();
1341 if ($template->template_exists($templateFile)) {
1342 return $templateFile;
1345 // lets see if we have customized by name
1346 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1348 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1349 if ($template->template_exists($templateFile)) {
1350 return $templateFile;
1358 * Use the form name to create the tpl file name.
1362 public function getTemplateFileName() {
1363 $fileName = $this->checkTemplateFileExists();
1364 return $fileName ?
$fileName : parent
::getTemplateFileName();
1368 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1369 * i.e. we dont override
1373 public function overrideExtraTemplateFileName() {
1374 $fileName = $this->checkTemplateFileExists('extra.');
1375 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();