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 * The title of the category we are editing
91 * the fields needed to build this form
98 * to store contact details
105 * to store group_id of the group which is to be assigned to the contact
109 protected $_addToGroupID;
112 * Do we allow updates of the contact
116 public $_isUpdateDupe = 0;
118 public $_isAddCaptcha = FALSE;
120 protected $_isPermissionedChecksum = FALSE;
123 * THe context from which we came from, allows us to go there if redirect not set
130 * THe contact type for registration case
134 protected $_ctype = NULL;
136 protected $_defaults = NULL;
139 * Store profile ids if multiple profile ids are passed using comma separated.
140 * Currently lets implement this functionality only for dialog mode
142 protected $_profileIds = array();
145 * Contact profile having activity fields?
149 protected $_isContactActivityProfile = FALSE;
152 * Activity Id connected to the profile
156 protected $_activityId = NULL;
159 protected $_multiRecordFields = NULL;
161 protected $_recordId = NULL;
164 * action for multi record profile (create/edit/delete)
168 protected $_multiRecord = NULL;
170 protected $_multiRecordProfile = FALSE;
172 protected $_recordExists = TRUE;
174 protected $_customGroupTitle = NULL;
176 protected $_deleteButtonName = NULL;
178 protected $_customGroupId = NULL;
180 protected $_currentUserID = NULL;
181 protected $_session = NULL;
183 public $_stateCountryMap = array();
185 * pre processing work done here.
187 * gets session variables for table name, id of entity in table, type of entity and stores them.
195 function preProcess() {
196 $this->_id
= $this->get('id');
197 $this->_gid
= $this->get('gid');
198 $this->_profileIds
= $this->get('profileIds');
199 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
200 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
202 //unset from session when $_GET doesn't have it
203 //except when the form is submitted
205 if (!array_key_exists('multiRecord', $_GET)) {
206 $this->set('multiRecord', NULL);
208 if (!array_key_exists('recordId', $_GET)) {
209 $this->set('recordId', NULL);
213 $this->_session
= CRM_Core_Session
::singleton();
214 $this->_currentUserID
= $this->_session
->get('userID');
216 if ($this->_mode
== self
::MODE_EDIT
) {
217 //specifies the action being done on a multi record field
218 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
219 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ?
220 CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
221 if ($this->_multiRecord
) {
222 $this->set('multiRecord', $this->_multiRecord
);
225 if ($this->_multiRecord
&&
226 !in_array($this->_multiRecord
, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
))) {
227 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
230 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
232 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0, 'GET'));
234 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
236 foreach ($gids as $pfId) {
237 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
241 // check if we are rendering mixed profiles
242 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
243 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
246 // for now consider 1'st profile as primary profile and validate it
247 // i.e check for profile type etc.
248 // FIX ME: validations for other than primary
249 $this->_gid
= $this->_profileIds
[0];
250 $this->set('gid', $this->_gid
);
251 $this->set('profileIds', $this->_profileIds
);
255 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0, 'GET');
258 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
259 if (is_numeric($this->_activityId
)) {
260 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
261 if ($latestRevisionId) {
262 $this->_activityId
= $latestRevisionId;
265 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
267 //get values for ufGroupName, captch and dupe update.
269 $dao = new CRM_Core_DAO_UFGroup();
270 $dao->id
= $this->_gid
;
271 if ($dao->find(TRUE)) {
272 $this->_isUpdateDupe
= $dao->is_update_dupe
;
273 $this->_isAddCaptcha
= $dao->add_captcha
;
274 if (!empty($dao->name
)) {
275 $this->_ufGroupName
= $dao->name
;
280 $this->assign('ufGroupName', $this->_ufGroupName
);
282 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
284 // if we dont have a gid use the default, else just use that specific gid
285 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
286 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
287 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
289 elseif ($this->_mode
== self
::MODE_SEARCH
) {
290 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
291 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
295 $this->_skipPermission
,
296 CRM_Core_Permission
::SEARCH
300 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
303 $this->_skipPermission
,
305 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
307 $multiRecordFieldListing = FALSE;
308 //using selector for listing of multirecord fields
309 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
310 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
312 if ($this->_multiRecord
) {
313 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
314 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
316 $this->_recordId
= NULL;
317 $this->set('recordId', NULL);
319 //record id is neccessary for _multiRecord view and update/edit action
320 if (!$this->_recordId
321 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
322 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
323 array(1 => $this->_gid
)
325 } elseif (empty($this->_multiRecordFields
)) {
326 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
327 array(1 => $this->_gid
)
331 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
332 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles(array($fieldId));
333 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
334 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
336 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
337 //record exists check
338 foreach ($this->_multiRecordFields
as $key => $field) {
339 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
341 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
343 if (array_key_exists($this->_recordId
, $getValues)) {
344 $this->_recordExists
= TRUE;
346 $this->_recordExists
= FALSE;
347 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
348 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');
352 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
353 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
354 if ($this->_maxRecordLimit
) {
355 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
359 } elseif (!empty($this->_multiRecordFields
)
360 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(CRM_Core_Action
::DELETE
, CRM_Core_Action
::UPDATE
)) )) {
361 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js');
362 //multirecord listing page
363 $multiRecordFieldListing = TRUE;
364 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
365 $cs = $this->get('cs');
366 $page->set('pageCheckSum', $cs);
367 $page->set('contactId', $this->_id
);
368 $page->set('profileId', $this->_gid
);
369 $page->set('action', CRM_Core_Action
::BROWSE
);
370 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
374 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
376 // is profile double-opt in?
377 if (!empty($this->_fields
['group']) &&
378 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
381 foreach ($this->_fields
as $name => $values) {
382 if (substr($name, 0, 6) == 'email-') {
388 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
389 $this->_session
->setStatus($status);
393 //transfering all the multirecord custom fields in _fields
394 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
395 $this->_fields
= $this->_multiRecordFields
;
396 $this->_multiRecordProfile
= TRUE;
397 } elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
398 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
399 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
403 if (!is_array($this->_fields
)) {
404 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
405 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
410 * This function sets the default values for the form. Note that in edit/view mode
411 * the default values are retrieved from the database
417 function setDefaultsValues() {
418 $this->_defaults
= array();
419 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
423 if ($this->_mode
!= self
::MODE_SEARCH
) {
424 // set default values for country / state to start with
425 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
428 if ($this->_id
&& !$this->_multiRecordProfile
) {
429 if ($this->_isContactActivityProfile
) {
430 $contactFields = $activityFields = array();
431 foreach ($this->_fields
as $fieldName => $field) {
432 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
433 $activityFields[$fieldName] = $field;
436 $contactFields[$fieldName] = $field;
440 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
441 if ($this->_activityId
) {
442 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
446 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
450 //set custom field defaults
451 if ($this->_multiRecordProfile
) {
452 foreach ($this->_multiRecordFields
as $key => $field) {
453 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
456 $defaultValues = array( );
457 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
458 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
459 if ($this->_recordExists
== TRUE) {
460 $defaultValues = $defaultValues[$this->_recordId
];
462 $defaultValues = NULL;
466 if (!empty($defaultValues)) {
467 foreach ($defaultValues as $key => $value) {
468 $name = "custom_{$key}";
469 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
470 if ($htmlType != 'File') {
472 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
480 $this->_defaults
[$name] = "";
484 if ($htmlType == 'File') {
485 $entityId = $this->_id
;
486 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
489 $entityId = $this->_activityId
;
491 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key);
494 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
496 $deleteExtra = ts("Are you sure you want to delete attached file?");
497 $fileId = $url['file_id'];
498 $deleteURL = CRM_Utils_System
::url('civicrm/file',
499 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
501 $text = ts("Delete Attached File");
502 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
504 // also delete the required rule that we've set on the form element
505 $this->removeFileRequiredRules($name);
512 foreach ($this->_fields
as $name => $field) {
513 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
514 $htmlType = $field['html_type'];
515 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
516 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
518 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
526 if ($htmlType == 'File') {
527 $entityId = $this->_id
;
528 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
529 $entityId = $this->_activityId
;
531 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
534 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
536 $deleteExtra = ts("Are you sure you want to delete attached file?");
537 $fileId = $url['file_id'];
538 $deleteURL = CRM_Utils_System
::url('civicrm/file',
539 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
541 $text = ts("Delete Attached File");
542 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
544 // also delete the required rule that we've set on the form element
545 $this->removeFileRequiredRules($field['name']);
551 if (isset($customFiles)) {
552 $this->assign('customFiles', $customFiles);
555 if ($this->_multiRecordProfile
) {
556 $this->setDefaults($this->_defaults
);
560 if (!empty($this->_defaults
['image_URL'])) {
561 list($imageWidth, $imageHeight) = getimagesize($this->_defaults
['image_URL']);
562 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
563 $this->assign("imageWidth", $imageWidth);
564 $this->assign("imageHeight", $imageHeight);
565 $this->assign("imageThumbWidth", $imageThumbWidth);
566 $this->assign("imageThumbHeight", $imageThumbHeight);
567 $this->assign("imageURL", $this->_defaults
['image_URL']);
568 $this->removeFileRequiredRules('image_URL');
571 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
572 !empty($this->_defaults
['contact_sub_type'])
574 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
575 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
579 $this->setDefaults($this->_defaults
);
583 * Function to actually build the form
588 public function buildQuickForm() {
589 switch ($this->_mode
) {
590 case self
::MODE_CREATE
:
591 case self
::MODE_EDIT
:
592 case self
::MODE_REGISTER
:
593 CRM_Utils_Hook
::buildProfile($this->_ufGroupName
);
595 case self
::MODE_SEARCH
:
596 CRM_Utils_Hook
::searchProfile($this->_ufGroupName
);
601 //lets have single status message, CRM-4363
603 $statusMessage = NULL;
604 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
608 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
609 if (!$this->_recordExists
) {
610 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
613 $this->assign('deleteRecord', TRUE);
618 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
620 // we should not allow component and mix profiles in search mode
621 if ($this->_mode
!= self
::MODE_REGISTER
) {
622 //check for mix profile fields (eg: individual + other contact type)
623 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
624 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
625 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
626 if (!empty($errors)) {
627 $statusMessage = array_pop($errors);
632 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
637 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
640 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
641 $contactType = $contactTypes[0];
643 array_shift($contactTypes);
644 $contactSubtypes = $contactTypes;
646 $profileSubType = FALSE;
647 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
648 $profileSubType = $profileType;
649 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
653 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
654 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType,$contactSubtypes))) ||
655 ($profileType != $contactType))
658 if (!$statusMessage) {
660 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
661 array(1 => $profileSubType ?
$profileSubType : $profileType));
669 array("Membership", "Participant", "Contribution")
673 if (!$statusMessage) {
674 $statusMessage = ts('Profile is not configured for the selected action.');
679 //lets have sigle status message,
680 $this->assign('statusMessage', $statusMessage);
685 if (count($this->_submitValues
)) {
686 $locationTypeId = null;
687 foreach ($this->_fields
as $field) {
688 if (!empty($field['location_type_id'])) {
689 $locationTypeId = $field['location_type_id'];
691 if (array_key_exists("country-{$locationTypeId}", $this->_fields
) &&
692 array_key_exists("state_province-{$locationTypeId}", $this->_fields
) &&
693 !empty($this->_submitValues
["country-{$locationTypeId}"])) {
694 $this->_fields
["state_province-{$locationTypeId}"]['is_required'] =
695 CRM_Core_Payment_Form
::checkRequiredStateProvince($this, "country-{$locationTypeId}");
700 $this->assign('id', $this->_id
);
701 $this->assign('mode', $this->_mode
);
702 $this->assign('action', $this->_action
);
703 $this->assign('fields', $this->_fields
);
704 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
706 // should we restrict what we display
708 if ($this->_mode
== self
::MODE_EDIT
) {
710 // show all fields that are visibile:
711 // if we are a admin OR the same user OR acl-user with access to the profile
712 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
714 CRM_Core_Permission
::check('administer users') ||
715 $this->_id
== $this->_currentUserID ||
716 $this->_isPermissionedChecksum ||
720 CRM_Core_Permission
::EDIT
,
723 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
731 // if false, user is not logged-in.
733 if (!$this->_currentUserID
) {
734 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
735 $primaryLocationType = $defaultLocationType->id
;
738 $this->assign('anonUser', $anonUser);
740 $addCaptcha = array();
741 $emailPresent = FALSE;
743 // cache the state country fields. based on the results, we could use our javascript solution
744 // in create or register mode
745 $stateCountryMap = array();
747 // add the form elements
748 foreach ($this->_fields
as $name => $field) {
749 // make sure that there is enough permission to expose this field
750 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
751 unset($this->_fields
[$name]);
755 // since the CMS manages the email field, suppress the email display if in
756 // register mode which occur within the CMS form
757 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
758 unset($this->_fields
[$name]);
762 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
763 if ($prefixName == 'state_province' ||
$prefixName == 'country' ||
$prefixName == 'county') {
764 if (!array_key_exists($index, $stateCountryMap)) {
765 $stateCountryMap[$index] = array();
767 $stateCountryMap[$index][$prefixName] = $name;
770 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
772 if ($field['add_to_group_id']) {
773 $addToGroupId = $field['add_to_group_id'];
776 //build array for captcha
777 if ($field['add_captcha']) {
778 $addCaptcha[$field['group_id']] = $field['add_captcha'];
781 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
782 $emailPresent = TRUE;
783 $this->_mail
= $name;
787 // add captcha only for create mode.
788 if ($this->_mode
== self
::MODE_CREATE
) {
789 // suppress captcha for logged in users only
790 if ($this->_currentUserID
) {
791 $this->_isAddCaptcha
= FALSE;
793 else if (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
794 $this->_isAddCaptcha
= TRUE;
798 $dao = new CRM_Core_DAO_UFGroup();
799 $dao->id
= $this->_gid
;
801 $dao->addSelect('is_update_dupe');
802 if ($dao->find(TRUE)) {
803 if ($dao->is_update_dupe
) {
804 $this->_isUpdateDupe
= $dao->is_update_dupe
;
810 $this->_isAddCaptcha
= FALSE;
813 //finally add captcha to form.
814 if ($this->_isAddCaptcha
) {
815 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
816 $captcha->add($this);
818 $this->assign("isCaptcha", $this->_isAddCaptcha
);
820 if ($this->_mode
!= self
::MODE_SEARCH
) {
821 if (isset($addToGroupId)) {
822 $this->add('hidden', "add_to_group", $addToGroupId);
823 $this->_addToGroupID
= $addToGroupId;
827 // lets do the defaults, so we can use it for the below state country routines
828 $this->setDefaultsValues();
830 // also do state country js
831 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap, $this->_defaults
);
833 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
834 if ($this->_mode
== self
::MODE_CREATE
) {
835 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
838 $this->assign('showCMS', FALSE);
841 $this->assign('groupId', $this->_gid
);
843 // now fix all state country selectors
844 CRM_Core_BAO_Address
::fixAllStateSelects($this, $this->_defaults
);
846 // if view mode pls freeze it with the done button.
847 if ($this->_action
& CRM_Core_Action
::VIEW
) {
851 if ($this->_context
== 'dialog') {
854 $this->_duplicateButtonName
,
855 ts('Save Matching Contact')
861 * Function to validate profile and provided activity Id
863 * @params Integer $activityId Activity Id
864 * @params Integer $gid Profile Id
866 * @return Array $errors Errors ( if any ).
868 static function validateContactActivityProfile($activityId, $contactId, $gid) {
871 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
875 $activityDetails = array();
876 $activityParams = array('id' => $activityId);
877 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
879 if (empty($activityDetails)) {
880 $errors[] = 'Invalid Activity Id (aid).';
884 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
886 if ((!empty($profileActivityTypes['Activity']) &&
887 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
889 (!in_array($contactId, $activityDetails['assignee_contact']) &&
890 !in_array($contactId, $activityDetails['target_contact'])
893 $errors[] = 'This activity cannot be edited or viewed via this profile.';
902 * @param array $fields the input form values
903 * @param array $files the uploaded files if any
904 * @param object $form the form object
906 * @return true if no errors, else array of errors
910 static function formRule($fields, $files, $form) {
911 CRM_Utils_Hook
::validateProfile($form->_ufGroupName
);
914 // if no values, return
915 if (empty($fields)) {
921 // hack we use a -1 in options to indicate that its registration
923 $form->_isUpdateDupe
= 1;
926 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
930 // dont check for duplicates during registration validation: CRM-375
931 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
933 if (!empty($fields['email-Primary'])) {
934 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
938 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
939 $fields['phone-Primary'] = $fields['phone-Primary-1'];
942 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
943 // If all profile fields is of Contact Type then consider
944 // profile is of Individual type(default).
946 $ctype = 'Individual';
948 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $ctype);
949 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
951 $exceptions = array();
954 // for edit mode we need to allow our own record to be a dupe match!
955 $exceptions = array($form->_session
->get('userID'));
958 // for dialog mode we should always use fuzzy rule.
959 $ruleType = 'Unsupervised';
960 if ($form->_context
== 'dialog') {
961 $ruleType = 'Supervised';
964 $dedupeParams['check_permission'] = FALSE;
965 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams,
971 if ($form->_isUpdateDupe
== 2) {
972 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
974 elseif ($form->_isUpdateDupe
== 1) {
976 $form->_id
= $ids[0];
980 if ($form->_context
== 'dialog') {
981 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
983 $duplicateContactsLinks = '<div class="matching-contacts-found">';
984 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
985 if ($contactLinks['msg'] == 'view') {
986 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
989 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
991 $duplicateContactsLinks .= '</div>';
992 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
994 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++
) {
996 $row .= ' <td class="matching-contacts-name"> ';
997 $row .= $contactLinks['rows'][$i]['display_name'];
999 $row .= ' <td class="matching-contacts-email"> ';
1000 $row .= $contactLinks['rows'][$i]['primary_email'];
1002 $row .= ' <td class="action-items"> ';
1003 $row .= $contactLinks['rows'][$i]['view'] . ' ';
1004 $row .= $contactLinks['rows'][$i]['edit'];
1009 $duplicateContactsLinks .= $row . '</table>';
1010 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1012 $errors['_qf_default'] = $duplicateContactsLinks;
1014 // let smarty know that there are duplicates
1015 $template = CRM_Core_Smarty
::singleton();
1016 $template->assign('isDuplicate', 1);
1019 $errors['_qf_default'] = ts('A record already exists with the same information.');
1025 foreach ($fields as $key => $value) {
1026 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1027 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1028 // Validate Country - State list
1029 $countryId = $fields["country-{$locTypeId}"];
1030 $stateProvinceId = $value;
1032 if ($stateProvinceId && $countryId) {
1033 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1034 $stateProvinceDAO->id
= $stateProvinceId;
1035 $stateProvinceDAO->find(TRUE);
1037 if ($stateProvinceDAO->country_id
!= $countryId) {
1038 // country mismatch hence display error
1039 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1040 $countries = CRM_Core_PseudoConstant
::country();
1041 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1046 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1047 // Validate County - State list
1048 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1051 if ($countyId && $stateProvinceId) {
1052 $countyDAO = new CRM_Core_DAO_County();
1053 $countyDAO->id
= $countyId;
1054 $countyDAO->find(TRUE);
1056 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1057 // state province mismatch hence display error
1058 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1059 $counties = CRM_Core_PseudoConstant
::county();
1060 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1065 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1066 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1067 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1068 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1069 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1070 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1076 return empty($errors) ?
TRUE : $errors;
1080 * Process the user submitted custom data values.
1086 public function postProcess() {
1087 $params = $this->controller
->exportValues($this->_name
);
1089 //if the delete record button is clicked
1090 if ($this->_deleteButtonName
) {
1091 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1092 $filterParams['id'] = $this->_customGroupId
;
1093 $returnProperities = array('is_multiple', 'table_name');
1094 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperities);
1095 if (!empty($returnValues['is_multiple'])) {
1096 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1097 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1099 1 => array($this->_recordId
, 'Integer'),
1100 2 => array($this->_id
, 'Integer')
1102 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1103 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1109 CRM_Utils_Hook
::processProfile($this->_ufGroupName
);
1110 if (!empty($params['image_URL'])) {
1111 CRM_Contact_BAO_Contact
::processImageParams($params);
1114 $greetingTypes = array(
1115 'addressee' => 'addressee_id',
1116 'email_greeting' => 'email_greeting_id',
1117 'postal_greeting' => 'postal_greeting_id',
1122 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1125 $details = $contactDetails[0][$this->_id
];
1127 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1128 CRM_Utils_Array
::value('postal_greeting_id', $details)
1131 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1132 //Though Profile type is contact we need
1133 //Individual/Household/Organization for setting Greetings.
1134 if ($profileType == 'Contact') {
1135 $profileType = 'Individual';
1136 //if we editing Household/Organization.
1138 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1141 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1142 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1145 foreach ($greetingTypes as $key => $value) {
1146 if (!array_key_exists($key, $params)) {
1147 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1152 $transaction = new CRM_Core_Transaction();
1154 //used to send subcribe mail to the group which user want.
1155 //if the profile double option in is enabled
1156 $mailingType = array();
1157 $config = CRM_Core_Config
::singleton();
1160 foreach ($params as $name => $values) {
1161 if (substr($name, 0, 6) == 'email-') {
1162 $result['email'] = $values;
1166 //array of group id, subscribed by contact
1167 $contactGroup = array();
1168 if (!empty($params['group']) &&
1169 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1171 $groupSubscribed = array();
1172 if (!empty($result['email'])) {
1174 $contactGroups = new CRM_Contact_DAO_GroupContact();
1175 $contactGroups->contact_id
= $this->_id
;
1176 $contactGroups->status
= 'Added';
1177 $contactGroups->find();
1178 $contactGroup = array();
1179 while ($contactGroups->fetch()) {
1180 $contactGroup[] = $contactGroups->group_id
;
1181 $groupSubscribed[$contactGroups->group_id
] = 1;
1184 foreach ($params['group'] as $key => $val) {
1186 unset($params['group'][$key]);
1189 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1190 $key, 'group_type', 'id'
1192 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1193 substr($groupTypes, 1, -1)
1195 //filter group of mailing type and unset it from params
1196 if (in_array(2, $groupType)) {
1197 //if group is already subscribed , ignore it
1198 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1199 if (!isset($groupExist)) {
1200 $mailingType[] = $key;
1201 unset($params['group'][$key]);
1208 $addToGroupId = NULL;
1209 if (!empty($params['add_to_group'])) {
1210 $addToGroupId = $params['add_to_group'];
1212 //run same check whether group is a mailing list
1213 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1214 $addToGroupId, 'group_type', 'id'
1216 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1217 substr($groupTypes, 1, -1)
1219 //filter group of mailing type and unset it from params
1220 if (in_array(2, $groupType) && !empty($result['email']) &&
1221 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1223 if (!count($contactGroup)) {
1224 //array of group id, subscribed by contact
1225 $contactGroup = array();
1227 $contactGroups = new CRM_Contact_DAO_GroupContact();
1228 $contactGroups->contact_id
= $this->_id
;
1229 $contactGroups->status
= 'Added';
1230 $contactGroups->find();
1231 $contactGroup = array();
1232 while ($contactGroups->fetch()) {
1233 $contactGroup[] = $contactGroups->group_id
;
1234 $groupSubscribed[$contactGroups->group_id
] = 1;
1238 //if group is already subscribed , ignore it
1239 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1240 if (!isset($groupExist)) {
1241 $mailingType[] = $addToGroupId;
1242 $addToGroupId = NULL;
1246 // since we are directly adding contact to group lets unset it from mailing
1247 if ($key = array_search($addToGroupId, $mailingType)) {
1248 unset($mailingType[$key]);
1254 $params['group'] = $groupSubscribed;
1257 // commenting below code, since we potentially
1258 // triggered maximum name field formatting cases during CRM-4430.
1260 // $params['preserveDBName'] = true;
1262 $profileFields = $this->_fields
;
1263 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1264 $profileFields = $activityParams = array();
1265 foreach ($this->_fields
as $fieldName => $field) {
1266 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1267 if (isset($params[$fieldName])) {
1268 $activityParams[$fieldName] = $params[$fieldName];
1270 if (isset($params['activity_date_time'])) {
1271 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1273 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1274 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1278 $profileFields[$fieldName] = $field;
1282 if (!empty($activityParams)) {
1283 $activityParams['version'] = 3;
1284 $activityParams['id'] = $this->_activityId
;
1285 $activityParams['skipRecentView'] = TRUE;
1286 civicrm_api('Activity', 'create', $activityParams);
1290 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1291 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1294 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1304 //mailing type group
1305 if (!empty($mailingType)) {
1306 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1308 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1311 $ufGroups = array();
1313 $ufGroups[$this->_gid
] = 1;
1315 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1316 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1319 foreach ($ufGroups as $gId => $val) {
1320 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1321 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1322 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1326 //create CMS user (if CMS user option is selected in profile)
1327 if (!empty($params['cms_create_account']) &&
1328 $this->_mode
== self
::MODE_CREATE
1330 $params['contactID'] = $this->_id
;
1331 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1332 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1333 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1334 $transaction->rollback();
1335 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1336 'reset=1&gid=' . $this->_gid
1341 $transaction->commit();
1344 function checkTemplateFileExists($suffix = NULL) {
1346 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1347 $template = CRM_Core_Form
::getTemplate();
1348 if ($template->template_exists($templateFile)) {
1349 return $templateFile;
1352 // lets see if we have customized by name
1353 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1355 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1356 if ($template->template_exists($templateFile)) {
1357 return $templateFile;
1364 function getTemplateFileName() {
1365 $fileName = $this->checkTemplateFileExists();
1366 return $fileName ?
$fileName : parent
::getTemplateFileName();
1369 function overrideExtraTemplateFileName() {
1370 $fileName = $this->checkTemplateFileExists('extra.');
1371 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();