3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class generates form components for custom data
39 * It delegates the work to lower level subclasses and integrates the changes
40 * back in. It also uses a lot of functionality with the CRM API's, so any change
41 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
44 class CRM_Profile_Form
extends CRM_Core_Form
{
53 protected $_skipPermission = FALSE;
56 * The contact id that we are editing
63 * The group id that we are editing
70 * The group id that we are editing
74 protected $_ufGroupName = 'unknown';
77 * The group id that we are passing in url
84 * Name of button for saving matching contacts
87 protected $_duplicateButtonName;
89 * The title of the category we are editing
96 * the fields needed to build this form
103 * to store contact details
110 * to store group_id of the group which is to be assigned to the contact
114 protected $_addToGroupID;
117 * Do we allow updates of the contact
121 public $_isUpdateDupe = 0;
123 public $_isAddCaptcha = FALSE;
125 protected $_isPermissionedChecksum = FALSE;
128 * THe context from which we came from, allows us to go there if redirect not set
135 * THe contact type for registration case
139 protected $_ctype = NULL;
141 protected $_defaults = NULL;
144 * Store profile ids if multiple profile ids are passed using comma separated.
145 * Currently lets implement this functionality only for dialog mode
147 protected $_profileIds = array();
150 * Contact profile having activity fields?
154 protected $_isContactActivityProfile = FALSE;
157 * Activity Id connected to the profile
161 protected $_activityId = NULL;
164 protected $_multiRecordFields = NULL;
166 protected $_recordId = NULL;
169 * action for multi record profile (create/edit/delete)
173 protected $_multiRecord = NULL;
175 protected $_multiRecordProfile = FALSE;
177 protected $_recordExists = TRUE;
179 protected $_customGroupTitle = NULL;
181 protected $_deleteButtonName = NULL;
183 protected $_customGroupId = NULL;
185 protected $_currentUserID = NULL;
186 protected $_session = NULL;
188 public $_stateCountryMap = array();
190 * pre processing work done here.
192 * gets session variables for table name, id of entity in table, type of entity and stores them.
200 function preProcess() {
201 $this->_id
= $this->get('id');
202 $this->_gid
= $this->get('gid');
203 $this->_profileIds
= $this->get('profileIds');
204 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
205 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
207 //unset from session when $_GET doesn't have it
208 //except when the form is submitted
210 if (!array_key_exists('multiRecord', $_GET)) {
211 $this->set('multiRecord', NULL);
213 if (!array_key_exists('recordId', $_GET)) {
214 $this->set('recordId', NULL);
218 $this->_session
= CRM_Core_Session
::singleton();
219 $this->_currentUserID
= $this->_session
->get('userID');
221 if ($this->_mode
== self
::MODE_EDIT
) {
222 //specifies the action being done on a multi record field
223 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
224 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ?
225 CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
226 if ($this->_multiRecord
) {
227 $this->set('multiRecord', $this->_multiRecord
);
230 if ($this->_multiRecord
&&
231 !in_array($this->_multiRecord
, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
))) {
232 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
235 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
237 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0, 'GET'));
239 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
241 foreach ($gids as $pfId) {
242 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
246 // check if we are rendering mixed profiles
247 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
248 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
251 // for now consider 1'st profile as primary profile and validate it
252 // i.e check for profile type etc.
253 // FIX ME: validations for other than primary
254 $this->_gid
= $this->_profileIds
[0];
255 $this->set('gid', $this->_gid
);
256 $this->set('profileIds', $this->_profileIds
);
260 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0, 'GET');
263 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
264 if (is_numeric($this->_activityId
)) {
265 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
266 if ($latestRevisionId) {
267 $this->_activityId
= $latestRevisionId;
270 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
272 //get values for ufGroupName, captch and dupe update.
274 $dao = new CRM_Core_DAO_UFGroup();
275 $dao->id
= $this->_gid
;
276 if ($dao->find(TRUE)) {
277 $this->_isUpdateDupe
= $dao->is_update_dupe
;
278 $this->_isAddCaptcha
= $dao->add_captcha
;
279 if (!empty($dao->name
)) {
280 $this->_ufGroupName
= $dao->name
;
285 $this->assign('ufGroupName', $this->_ufGroupName
);
287 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
289 // if we dont have a gid use the default, else just use that specific gid
290 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
291 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
292 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
294 elseif ($this->_mode
== self
::MODE_SEARCH
) {
295 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
296 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
300 $this->_skipPermission
,
301 CRM_Core_Permission
::SEARCH
305 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
308 $this->_skipPermission
,
310 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
312 $multiRecordFieldListing = FALSE;
313 //using selector for listing of multirecord fields
314 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
315 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
317 if ($this->_multiRecord
) {
318 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
319 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
321 $this->_recordId
= NULL;
322 $this->set('recordId', NULL);
324 //record id is neccessary for _multiRecord view and update/edit action
325 if (!$this->_recordId
326 && ($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
)
330 } elseif (empty($this->_multiRecordFields
)) {
331 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
332 array(1 => $this->_gid
)
336 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
337 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles(array($fieldId));
338 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
339 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
341 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
342 //record exists check
343 foreach ($this->_multiRecordFields
as $key => $field) {
344 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
346 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
348 if (array_key_exists($this->_recordId
, $getValues)) {
349 $this->_recordExists
= TRUE;
351 $this->_recordExists
= FALSE;
352 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
353 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');
357 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
358 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
359 if ($this->_maxRecordLimit
) {
360 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
364 } elseif (!empty($this->_multiRecordFields
)
365 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(CRM_Core_Action
::DELETE
, CRM_Core_Action
::UPDATE
)) )) {
366 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js');
367 //multirecord listing page
368 $multiRecordFieldListing = TRUE;
369 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
370 $cs = $this->get('cs');
371 $page->set('pageCheckSum', $cs);
372 $page->set('contactId', $this->_id
);
373 $page->set('profileId', $this->_gid
);
374 $page->set('action', CRM_Core_Action
::BROWSE
);
375 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
379 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
381 // is profile double-opt in?
382 if (!empty($this->_fields
['group']) &&
383 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
386 foreach ($this->_fields
as $name => $values) {
387 if (substr($name, 0, 6) == 'email-') {
393 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
394 $this->_session
->setStatus($status);
398 //transferring all the multi-record custom fields in _fields
399 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
400 $this->_fields
= $this->_multiRecordFields
;
401 $this->_multiRecordProfile
= TRUE;
402 } elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
403 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
404 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
408 if (!is_array($this->_fields
)) {
409 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
410 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
415 * This function sets the default values for the form. Note that in edit/view mode
416 * the default values are retrieved from the database
422 function setDefaultsValues() {
423 $this->_defaults
= array();
424 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
428 if ($this->_mode
!= self
::MODE_SEARCH
) {
429 // set default values for country / state to start with
430 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
433 if ($this->_id
&& !$this->_multiRecordProfile
) {
434 if ($this->_isContactActivityProfile
) {
435 $contactFields = $activityFields = array();
436 foreach ($this->_fields
as $fieldName => $field) {
437 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
438 $activityFields[$fieldName] = $field;
441 $contactFields[$fieldName] = $field;
445 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
446 if ($this->_activityId
) {
447 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
451 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
455 //set custom field defaults
456 if ($this->_multiRecordProfile
) {
457 foreach ($this->_multiRecordFields
as $key => $field) {
458 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
461 $defaultValues = array( );
462 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
463 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
464 if ($this->_recordExists
== TRUE) {
465 $defaultValues = $defaultValues[$this->_recordId
];
467 $defaultValues = NULL;
471 if (!empty($defaultValues)) {
472 foreach ($defaultValues as $key => $value) {
473 $name = "custom_{$key}";
474 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
475 if ($htmlType != 'File') {
477 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
485 $this->_defaults
[$name] = "";
489 if ($htmlType == 'File') {
490 $entityId = $this->_id
;
491 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
494 $entityId = $this->_activityId
;
496 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key);
499 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
501 $deleteExtra = ts("Are you sure you want to delete attached file?");
502 $fileId = $url['file_id'];
503 $deleteURL = CRM_Utils_System
::url('civicrm/file',
504 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
506 $text = ts("Delete Attached File");
507 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
509 // also delete the required rule that we've set on the form element
510 $this->removeFileRequiredRules($name);
517 foreach ($this->_fields
as $name => $field) {
518 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
519 $htmlType = $field['html_type'];
520 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
521 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
523 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
531 if ($htmlType == 'File') {
532 $entityId = $this->_id
;
533 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
534 $entityId = $this->_activityId
;
536 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
539 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
541 $deleteExtra = ts("Are you sure you want to delete attached file?");
542 $fileId = $url['file_id'];
543 $deleteURL = CRM_Utils_System
::url('civicrm/file',
544 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
546 $text = ts("Delete Attached File");
547 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
549 // also delete the required rule that we've set on the form element
550 $this->removeFileRequiredRules($field['name']);
556 if (isset($customFiles)) {
557 $this->assign('customFiles', $customFiles);
560 if ($this->_multiRecordProfile
) {
561 $this->setDefaults($this->_defaults
);
565 if (!empty($this->_defaults
['image_URL'])) {
566 list($imageWidth, $imageHeight) = getimagesize($this->_defaults
['image_URL']);
567 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
568 $this->assign("imageWidth", $imageWidth);
569 $this->assign("imageHeight", $imageHeight);
570 $this->assign("imageThumbWidth", $imageThumbWidth);
571 $this->assign("imageThumbHeight", $imageThumbHeight);
572 $this->assign("imageURL", $this->_defaults
['image_URL']);
573 $this->removeFileRequiredRules('image_URL');
576 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
577 !empty($this->_defaults
['contact_sub_type'])
579 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
580 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
584 $this->setDefaults($this->_defaults
);
588 * Function to actually build the form
593 public function buildQuickForm() {
594 switch ($this->_mode
) {
595 case self
::MODE_CREATE
:
596 case self
::MODE_EDIT
:
597 case self
::MODE_REGISTER
:
598 CRM_Utils_Hook
::buildProfile($this->_ufGroupName
);
600 case self
::MODE_SEARCH
:
601 CRM_Utils_Hook
::searchProfile($this->_ufGroupName
);
606 //lets have single status message, CRM-4363
608 $statusMessage = NULL;
609 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
613 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
614 if (!$this->_recordExists
) {
615 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
618 $this->assign('deleteRecord', TRUE);
623 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
625 // we should not allow component and mix profiles in search mode
626 if ($this->_mode
!= self
::MODE_REGISTER
) {
627 //check for mix profile fields (eg: individual + other contact type)
628 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
629 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
630 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
631 if (!empty($errors)) {
632 $statusMessage = array_pop($errors);
637 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
642 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
645 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
646 $contactType = $contactTypes[0];
648 array_shift($contactTypes);
649 $contactSubtypes = $contactTypes;
651 $profileSubType = FALSE;
652 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
653 $profileSubType = $profileType;
654 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
658 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
659 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType,$contactSubtypes))) ||
660 ($profileType != $contactType))
663 if (!$statusMessage) {
665 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
666 array(1 => $profileSubType ?
$profileSubType : $profileType));
674 array("Membership", "Participant", "Contribution")
678 if (!$statusMessage) {
679 $statusMessage = ts('Profile is not configured for the selected action.');
684 //lets have single status message,
685 $this->assign('statusMessage', $statusMessage);
690 if (count($this->_submitValues
)) {
691 $locationTypeId = null;
692 foreach ($this->_fields
as $field) {
693 if (!empty($field['location_type_id'])) {
694 $locationTypeId = $field['location_type_id'];
696 if (array_key_exists("country-{$locationTypeId}", $this->_fields
) &&
697 array_key_exists("state_province-{$locationTypeId}", $this->_fields
) &&
698 !empty($this->_submitValues
["country-{$locationTypeId}"])) {
699 $this->_fields
["state_province-{$locationTypeId}"]['is_required'] =
700 CRM_Core_Payment_Form
::checkRequiredStateProvince($this, "country-{$locationTypeId}");
705 $this->assign('id', $this->_id
);
706 $this->assign('mode', $this->_mode
);
707 $this->assign('action', $this->_action
);
708 $this->assign('fields', $this->_fields
);
709 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
711 // should we restrict what we display
713 if ($this->_mode
== self
::MODE_EDIT
) {
715 // show all fields that are visibile:
716 // if we are a admin OR the same user OR acl-user with access to the profile
717 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
719 CRM_Core_Permission
::check('administer users') ||
720 $this->_id
== $this->_currentUserID ||
721 $this->_isPermissionedChecksum ||
725 CRM_Core_Permission
::EDIT
,
728 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
736 // if false, user is not logged-in.
738 if (!$this->_currentUserID
) {
739 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
740 $primaryLocationType = $defaultLocationType->id
;
743 $this->assign('anonUser', $anonUser);
745 $addCaptcha = array();
746 $emailPresent = FALSE;
748 // cache the state country fields. based on the results, we could use our javascript solution
749 // in create or register mode
750 $stateCountryMap = array();
752 // add the form elements
753 foreach ($this->_fields
as $name => $field) {
754 // make sure that there is enough permission to expose this field
755 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
756 unset($this->_fields
[$name]);
760 // since the CMS manages the email field, suppress the email display if in
761 // register mode which occur within the CMS form
762 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
763 unset($this->_fields
[$name]);
767 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
768 if ($prefixName == 'state_province' ||
$prefixName == 'country' ||
$prefixName == 'county') {
769 if (!array_key_exists($index, $stateCountryMap)) {
770 $stateCountryMap[$index] = array();
772 $stateCountryMap[$index][$prefixName] = $name;
775 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
777 if ($field['add_to_group_id']) {
778 $addToGroupId = $field['add_to_group_id'];
781 //build array for captcha
782 if ($field['add_captcha']) {
783 $addCaptcha[$field['group_id']] = $field['add_captcha'];
786 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
787 $emailPresent = TRUE;
788 $this->_mail
= $name;
792 // add captcha only for create mode.
793 if ($this->_mode
== self
::MODE_CREATE
) {
794 // suppress captcha for logged in users only
795 if ($this->_currentUserID
) {
796 $this->_isAddCaptcha
= FALSE;
798 else if (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
799 $this->_isAddCaptcha
= TRUE;
803 $dao = new CRM_Core_DAO_UFGroup();
804 $dao->id
= $this->_gid
;
806 $dao->addSelect('is_update_dupe');
807 if ($dao->find(TRUE)) {
808 if ($dao->is_update_dupe
) {
809 $this->_isUpdateDupe
= $dao->is_update_dupe
;
815 $this->_isAddCaptcha
= FALSE;
818 //finally add captcha to form.
819 if ($this->_isAddCaptcha
) {
820 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
821 $captcha->add($this);
823 $this->assign("isCaptcha", $this->_isAddCaptcha
);
825 if ($this->_mode
!= self
::MODE_SEARCH
) {
826 if (isset($addToGroupId)) {
827 $this->add('hidden', "add_to_group", $addToGroupId);
828 $this->_addToGroupID
= $addToGroupId;
832 // lets do the defaults, so we can use it for the below state country routines
833 $this->setDefaultsValues();
835 // also do state country js
836 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap, $this->_defaults
);
838 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
839 if ($this->_mode
== self
::MODE_CREATE
) {
840 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
843 $this->assign('showCMS', FALSE);
846 $this->assign('groupId', $this->_gid
);
848 // now fix all state country selectors
849 CRM_Core_BAO_Address
::fixAllStateSelects($this, $this->_defaults
);
851 // if view mode pls freeze it with the done button.
852 if ($this->_action
& CRM_Core_Action
::VIEW
) {
856 if ($this->_context
== 'dialog') {
859 $this->_duplicateButtonName
,
860 ts('Save Matching Contact')
866 * Function to validate profile and provided activity Id
868 * @params Integer $activityId Activity Id
869 * @params Integer $gid Profile Id
871 * @return Array $errors Errors ( if any ).
880 static function validateContactActivityProfile($activityId, $contactId, $gid) {
883 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
887 $activityDetails = array();
888 $activityParams = array('id' => $activityId);
889 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
891 if (empty($activityDetails)) {
892 $errors[] = 'Invalid Activity Id (aid).';
896 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
898 if ((!empty($profileActivityTypes['Activity']) &&
899 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
901 (!in_array($contactId, $activityDetails['assignee_contact']) &&
902 !in_array($contactId, $activityDetails['target_contact'])
905 $errors[] = 'This activity cannot be edited or viewed via this profile.';
914 * @param array $fields the input form values
915 * @param array $files the uploaded files if any
916 * @param object $form the form object
918 * @return true if no errors, else array of errors
922 static function formRule($fields, $files, $form) {
923 CRM_Utils_Hook
::validateProfile($form->_ufGroupName
);
926 // if no values, return
927 if (empty($fields)) {
933 // hack we use a -1 in options to indicate that its registration
935 $form->_isUpdateDupe
= 1;
938 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
942 // dont check for duplicates during registration validation: CRM-375
943 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
945 if (!empty($fields['email-Primary'])) {
946 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
950 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
951 $fields['phone-Primary'] = $fields['phone-Primary-1'];
954 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
955 // If all profile fields is of Contact Type then consider
956 // profile is of Individual type(default).
958 $ctype = 'Individual';
960 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $ctype);
961 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
963 $exceptions = array();
966 // for edit mode we need to allow our own record to be a dupe match!
967 $exceptions = array($form->_session
->get('userID'));
970 // for dialog mode we should always use fuzzy rule.
971 $ruleType = 'Unsupervised';
972 if ($form->_context
== 'dialog') {
973 $ruleType = 'Supervised';
976 $dedupeParams['check_permission'] = FALSE;
977 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams,
983 if ($form->_isUpdateDupe
== 2) {
984 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
986 elseif ($form->_isUpdateDupe
== 1) {
988 $form->_id
= $ids[0];
992 if ($form->_context
== 'dialog') {
993 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
995 $duplicateContactsLinks = '<div class="matching-contacts-found">';
996 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
997 if ($contactLinks['msg'] == 'view') {
998 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
1001 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
1003 $duplicateContactsLinks .= '</div>';
1004 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1006 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++
) {
1008 $row .= ' <td class="matching-contacts-name"> ';
1009 $row .= $contactLinks['rows'][$i]['display_name'];
1011 $row .= ' <td class="matching-contacts-email"> ';
1012 $row .= $contactLinks['rows'][$i]['primary_email'];
1014 $row .= ' <td class="action-items"> ';
1015 $row .= $contactLinks['rows'][$i]['view'] . ' ';
1016 $row .= $contactLinks['rows'][$i]['edit'];
1021 $duplicateContactsLinks .= $row . '</table>';
1022 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1024 $errors['_qf_default'] = $duplicateContactsLinks;
1026 // let smarty know that there are duplicates
1027 $template = CRM_Core_Smarty
::singleton();
1028 $template->assign('isDuplicate', 1);
1031 $errors['_qf_default'] = ts('A record already exists with the same information.');
1037 foreach ($fields as $key => $value) {
1038 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1039 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1040 // Validate Country - State list
1041 $countryId = $fields["country-{$locTypeId}"];
1042 $stateProvinceId = $value;
1044 if ($stateProvinceId && $countryId) {
1045 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1046 $stateProvinceDAO->id
= $stateProvinceId;
1047 $stateProvinceDAO->find(TRUE);
1049 if ($stateProvinceDAO->country_id
!= $countryId) {
1050 // country mismatch hence display error
1051 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1052 $countries = CRM_Core_PseudoConstant
::country();
1053 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1058 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1059 // Validate County - State list
1060 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1063 if ($countyId && $stateProvinceId) {
1064 $countyDAO = new CRM_Core_DAO_County();
1065 $countyDAO->id
= $countyId;
1066 $countyDAO->find(TRUE);
1068 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1069 // state province mismatch hence display error
1070 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1071 $counties = CRM_Core_PseudoConstant
::county();
1072 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1077 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1078 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1079 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1080 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1081 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1082 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1088 return empty($errors) ?
TRUE : $errors;
1092 * Process the user submitted custom data values.
1098 public function postProcess() {
1099 $params = $this->controller
->exportValues($this->_name
);
1101 //if the delete record button is clicked
1102 if ($this->_deleteButtonName
) {
1103 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1104 $filterParams['id'] = $this->_customGroupId
;
1105 $returnProperties = array('is_multiple', 'table_name');
1106 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1107 if (!empty($returnValues['is_multiple'])) {
1108 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1109 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1111 1 => array($this->_recordId
, 'Integer'),
1112 2 => array($this->_id
, 'Integer')
1114 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1115 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1121 CRM_Utils_Hook
::processProfile($this->_ufGroupName
);
1122 if (!empty($params['image_URL'])) {
1123 CRM_Contact_BAO_Contact
::processImageParams($params);
1126 $greetingTypes = array(
1127 'addressee' => 'addressee_id',
1128 'email_greeting' => 'email_greeting_id',
1129 'postal_greeting' => 'postal_greeting_id',
1134 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1137 $details = $contactDetails[0][$this->_id
];
1139 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1140 CRM_Utils_Array
::value('postal_greeting_id', $details)
1143 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1144 //Though Profile type is contact we need
1145 //Individual/Household/Organization for setting Greetings.
1146 if ($profileType == 'Contact') {
1147 $profileType = 'Individual';
1148 //if we editing Household/Organization.
1150 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1153 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1154 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1157 foreach ($greetingTypes as $key => $value) {
1158 if (!array_key_exists($key, $params)) {
1159 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1164 $transaction = new CRM_Core_Transaction();
1166 //used to send subscribe mail to the group which user want.
1167 //if the profile double option in is enabled
1168 $mailingType = array();
1171 foreach ($params as $name => $values) {
1172 if (substr($name, 0, 6) == 'email-') {
1173 $result['email'] = $values;
1177 //array of group id, subscribed by contact
1178 $contactGroup = array();
1179 if (!empty($params['group']) &&
1180 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1182 $groupSubscribed = array();
1183 if (!empty($result['email'])) {
1185 $contactGroups = new CRM_Contact_DAO_GroupContact();
1186 $contactGroups->contact_id
= $this->_id
;
1187 $contactGroups->status
= 'Added';
1188 $contactGroups->find();
1189 $contactGroup = array();
1190 while ($contactGroups->fetch()) {
1191 $contactGroup[] = $contactGroups->group_id
;
1192 $groupSubscribed[$contactGroups->group_id
] = 1;
1195 foreach ($params['group'] as $key => $val) {
1197 unset($params['group'][$key]);
1200 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1201 $key, 'group_type', 'id'
1203 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1204 substr($groupTypes, 1, -1)
1206 //filter group of mailing type and unset it from params
1207 if (in_array(2, $groupType)) {
1208 //if group is already subscribed , ignore it
1209 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1210 if (!isset($groupExist)) {
1211 $mailingType[] = $key;
1212 unset($params['group'][$key]);
1219 $addToGroupId = NULL;
1220 if (!empty($params['add_to_group'])) {
1221 $addToGroupId = $params['add_to_group'];
1223 //run same check whether group is a mailing list
1224 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1225 $addToGroupId, 'group_type', 'id'
1227 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1228 substr($groupTypes, 1, -1)
1230 //filter group of mailing type and unset it from params
1231 if (in_array(2, $groupType) && !empty($result['email']) &&
1232 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1234 if (!count($contactGroup)) {
1235 //array of group id, subscribed by contact
1236 $contactGroup = array();
1238 $contactGroups = new CRM_Contact_DAO_GroupContact();
1239 $contactGroups->contact_id
= $this->_id
;
1240 $contactGroups->status
= 'Added';
1241 $contactGroups->find();
1242 $contactGroup = array();
1243 while ($contactGroups->fetch()) {
1244 $contactGroup[] = $contactGroups->group_id
;
1245 $groupSubscribed[$contactGroups->group_id
] = 1;
1249 //if group is already subscribed , ignore it
1250 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1251 if (!isset($groupExist)) {
1252 $mailingType[] = $addToGroupId;
1253 $addToGroupId = NULL;
1257 // since we are directly adding contact to group lets unset it from mailing
1258 if ($key = array_search($addToGroupId, $mailingType)) {
1259 unset($mailingType[$key]);
1265 $params['group'] = $groupSubscribed;
1268 // commenting below code, since we potentially
1269 // triggered maximum name field formatting cases during CRM-4430.
1271 // $params['preserveDBName'] = true;
1273 $profileFields = $this->_fields
;
1274 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1275 $profileFields = $activityParams = array();
1276 foreach ($this->_fields
as $fieldName => $field) {
1277 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1278 if (isset($params[$fieldName])) {
1279 $activityParams[$fieldName] = $params[$fieldName];
1281 if (isset($params['activity_date_time'])) {
1282 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1284 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1285 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1289 $profileFields[$fieldName] = $field;
1293 if (!empty($activityParams)) {
1294 $activityParams['version'] = 3;
1295 $activityParams['id'] = $this->_activityId
;
1296 $activityParams['skipRecentView'] = TRUE;
1297 civicrm_api('Activity', 'create', $activityParams);
1301 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1302 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1305 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1315 //mailing type group
1316 if (!empty($mailingType)) {
1317 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1319 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1322 $ufGroups = array();
1324 $ufGroups[$this->_gid
] = 1;
1326 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1327 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1330 foreach ($ufGroups as $gId => $val) {
1331 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1332 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1333 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1337 //create CMS user (if CMS user option is selected in profile)
1338 if (!empty($params['cms_create_account']) &&
1339 $this->_mode
== self
::MODE_CREATE
1341 $params['contactID'] = $this->_id
;
1342 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1343 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1344 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1345 $transaction->rollback();
1346 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1347 'reset=1&gid=' . $this->_gid
1352 $transaction->commit();
1356 * @param null $suffix
1358 * @return null|string
1360 function checkTemplateFileExists($suffix = NULL) {
1362 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1363 $template = CRM_Core_Form
::getTemplate();
1364 if ($template->template_exists($templateFile)) {
1365 return $templateFile;
1368 // lets see if we have customized by name
1369 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1371 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1372 if ($template->template_exists($templateFile)) {
1373 return $templateFile;
1381 * Use the form name to create the tpl file name
1389 function getTemplateFileName() {
1390 $fileName = $this->checkTemplateFileExists();
1391 return $fileName ?
$fileName : parent
::getTemplateFileName();
1395 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1396 * i.e. we dont override
1404 function overrideExtraTemplateFileName() {
1405 $fileName = $this->checkTemplateFileExists('extra.');
1406 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();