3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 passing in url
77 * The title of the category we are editing
84 * the fields needed to build this form
91 * to store contact details
98 * to store group_id of the group which is to be assigned to the contact
102 protected $_addToGroupID;
105 * Do we allow updates of the contact
109 public $_isUpdateDupe = 0;
111 public $_isAddCaptcha = FALSE;
113 protected $_isPermissionedChecksum = FALSE;
116 * THe context from which we came from, allows us to go there if redirect not set
123 * THe contact type for registration case
127 protected $_ctype = NULL;
129 protected $_defaults = NULL;
132 * Store profile ids if multiple profile ids are passed using comma separated.
133 * Currently lets implement this functionality only for dialog mode
135 protected $_profileIds = array();
138 * Contact profile having activity fields?
142 protected $_isContactActivityProfile = FALSE;
145 * Activity Id connected to the profile
149 protected $_activityId = NULL;
152 protected $_multiRecordFields = NULL;
154 protected $_recordId = NULL;
157 * action for multi record profile (create/edit/delete)
161 protected $_multiRecord = NULL;
163 protected $_multiRecordProfile = FALSE;
165 protected $_recordExists = TRUE;
167 protected $_customGroupTitle = NULL;
169 protected $_deleteButtonName = NULL;
171 protected $_customGroupId = NULL;
173 protected $_currentUserID = NULL;
174 protected $_session = NULL;
177 * pre processing work done here.
179 * gets session variables for table name, id of entity in table, type of entity and stores them.
187 function preProcess() {
188 $this->_id
= $this->get('id');
189 $this->_gid
= $this->get('gid');
190 $this->_profileIds
= $this->get('profileIds');
191 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
192 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
194 //unset from session when $_GET doesn't have it
195 //except when the form is submitted
197 if (!array_key_exists('multiRecord', $_GET)) {
198 $this->set('multiRecord', NULL);
200 if (!array_key_exists('recordId', $_GET)) {
201 $this->set('recordId', NULL);
205 $this->_session
= CRM_Core_Session
::singleton();
206 $this->_currentUserID
= $this->_session
->get('userID');
208 if ($this->_mode
== self
::MODE_EDIT
) {
209 //specifies the action being done on a multi record field
210 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
211 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ?
212 CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
213 if ($this->_multiRecord
) {
214 $this->set('multiRecord', $this->_multiRecord
);
217 if ($this->_multiRecord
&&
218 !in_array($this->_multiRecord
, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
))) {
219 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
222 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
224 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0, 'GET'));
226 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
228 foreach ($gids as $pfId) {
229 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
233 // check if we are rendering mixed profiles
234 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
235 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
238 // for now consider 1'st profile as primary profile and validate it
239 // i.e check for profile type etc.
240 // FIX ME: validations for other than primary
241 $this->_gid
= $this->_profileIds
[0];
242 $this->set('gid', $this->_gid
);
243 $this->set('profileIds', $this->_profileIds
);
247 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0, 'GET');
250 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
251 if (is_numeric($this->_activityId
)) {
252 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
253 if ($latestRevisionId) {
254 $this->_activityId
= $latestRevisionId;
257 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
259 //get values for captch and dupe update.
261 $dao = new CRM_Core_DAO_UFGroup();
262 $dao->id
= $this->_gid
;
263 if ($dao->find(TRUE)) {
264 $this->_isUpdateDupe
= $dao->is_update_dupe
;
265 $this->_isAddCaptcha
= $dao->add_captcha
;
270 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
272 // if we dont have a gid use the default, else just use that specific gid
273 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
274 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
275 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
277 elseif ($this->_mode
== self
::MODE_SEARCH
) {
278 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
279 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
283 $this->_skipPermission
,
284 CRM_Core_Permission
::SEARCH
288 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
291 $this->_skipPermission
,
293 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
295 $multiRecordFieldListing = FALSE;
296 //using selector for listing of multirecord fields
297 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
298 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
300 if ($this->_multiRecord
) {
301 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
302 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
304 $this->_recordId
= NULL;
305 $this->set('recordId', NULL);
307 //record id is neccessary for _multiRecord view and update/edit action
308 if (!$this->_recordId
309 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
310 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
311 array(1 => $this->_gid
)
313 } elseif (empty($this->_multiRecordFields
)) {
314 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
315 array(1 => $this->_gid
)
319 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
320 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles(array($fieldId));
321 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
322 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
324 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
325 //record exists check
326 foreach ($this->_multiRecordFields
as $key => $field) {
327 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
329 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
331 if (array_key_exists($this->_recordId
, $getValues)) {
332 $this->_recordExists
= TRUE;
334 $this->_recordExists
= FALSE;
335 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
336 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');
340 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
341 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
342 if ($this->_maxRecordLimit
) {
343 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
347 } elseif (!empty($this->_multiRecordFields
)
348 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(CRM_Core_Action
::DELETE
, CRM_Core_Action
::UPDATE
)) )) {
349 //multirecord listing page
350 $multiRecordFieldListing = TRUE;
351 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
352 $cs = $this->get('cs');
353 $page->set('pageCheckSum', $cs);
354 $page->set('contactId', $this->_id
);
355 $page->set('profileId', $this->_gid
);
356 $page->set('action', CRM_Core_Action
::BROWSE
);
357 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
361 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
363 // is profile double-opt in?
364 if (CRM_Utils_Array
::value('group', $this->_fields
) &&
365 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
368 foreach ($this->_fields
as $name => $values) {
369 if (substr($name, 0, 6) == 'email-') {
375 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
376 $this->_session
->setStatus($status);
380 //transfering all the multirecord custom fields in _fields
381 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
382 $this->_fields
= $this->_multiRecordFields
;
383 $this->_multiRecordProfile
= TRUE;
384 } elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
385 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
386 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
390 if (!is_array($this->_fields
)) {
391 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
392 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
397 * This function sets the default values for the form. Note that in edit/view mode
398 * the default values are retrieved from the database
404 function setDefaultsValues() {
405 $this->_defaults
= array();
406 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
410 if ($this->_mode
!= self
::MODE_SEARCH
) {
411 // set default values for country / state to start with
412 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
415 if ($this->_id
&& !$this->_multiRecordProfile
) {
416 if ($this->_isContactActivityProfile
) {
417 $contactFields = $activityFields = array();
418 foreach ($this->_fields
as $fieldName => $field) {
419 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
420 $activityFields[$fieldName] = $field;
423 $contactFields[$fieldName] = $field;
427 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
428 if ($this->_activityId
) {
429 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
433 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
437 //set custom field defaults
438 if ($this->_multiRecordProfile
) {
439 foreach ($this->_multiRecordFields
as $key => $field) {
440 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
443 $defaultValues = array( );
444 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
445 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
446 if ($this->_recordExists
== TRUE) {
447 $defaultValues = $defaultValues[$this->_recordId
];
449 $defaultValues = NULL;
453 if (!empty($defaultValues)) {
454 foreach ($defaultValues as $key => $value) {
455 $name = "custom_{$key}";
456 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
457 if ($htmlType != 'File') {
459 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
467 $this->_defaults
[$name] = "";
471 if ($htmlType == 'File') {
472 $entityId = $this->_id
;
473 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
476 $entityId = $this->_activityId
;
478 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key);
481 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
483 $deleteExtra = ts("Are you sure you want to delete attached file?");
484 $fileId = $url['file_id'];
485 $deleteURL = CRM_Utils_System
::url('civicrm/file',
486 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
488 $text = ts("Delete Attached File");
489 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
491 // also delete the required rule that we've set on the form element
492 $this->removeFileRequiredRules($name);
498 foreach ($this->_fields
as $name => $field) {
499 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
500 $htmlType = $field['html_type'];
501 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
502 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
504 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
512 if ($htmlType == 'File') {
513 $entityId = $this->_id
;
514 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
517 $entityId = $this->_activityId
;
519 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
522 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
524 $deleteExtra = ts("Are you sure you want to delete attached file?");
525 $fileId = $url['file_id'];
526 $deleteURL = CRM_Utils_System
::url('civicrm/file',
527 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
529 $text = ts("Delete Attached File");
530 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
532 // also delete the required rule that we've set on the form element
533 $this->removeFileRequiredRules($field['name']);
539 if (isset($customFiles)) {
540 $this->assign('customFiles', $customFiles);
543 if ($this->_multiRecordProfile
) {
544 $this->setDefaults($this->_defaults
);
548 if (CRM_Utils_Array
::value('image_URL', $this->_defaults
)) {
549 list($imageWidth, $imageHeight) = getimagesize($this->_defaults
['image_URL']);
550 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
551 $this->assign("imageWidth", $imageWidth);
552 $this->assign("imageHeight", $imageHeight);
553 $this->assign("imageThumbWidth", $imageThumbWidth);
554 $this->assign("imageThumbHeight", $imageThumbHeight);
555 $this->assign("imageURL", $this->_defaults
['image_URL']);
558 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
559 !empty($this->_defaults
['contact_sub_type'])
561 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
562 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
566 $this->setDefaults($this->_defaults
);
570 * Function to actually build the form
575 public function buildQuickForm() {
576 //lets have single status message, CRM-4363
578 $statusMessage = NULL;
579 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
583 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
584 if (!$this->_recordExists
) {
585 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
588 $this->assign('deleteRecord', TRUE);
593 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
595 // we should not allow component and mix profiles in search mode
596 if ($this->_mode
!= self
::MODE_REGISTER
) {
597 //check for mix profile fields (eg: individual + other contact type)
598 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
599 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
600 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
601 if (!empty($errors)) {
602 $statusMessage = array_pop($errors);
607 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
612 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
615 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
616 $contactType = $contactTypes[0];
618 array_shift($contactTypes);
619 $contactSubtypes = $contactTypes;
621 $profileSubType = FALSE;
622 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
623 $profileSubType = $profileType;
624 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
628 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
629 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType,$contactSubtypes))) ||
630 ($profileType != $contactType))
633 if (!$statusMessage) {
635 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
636 array(1 => $profileSubType ?
$profileSubType : $profileType));
644 array("Membership", "Participant", "Contribution")
648 if (!$statusMessage) {
649 $statusMessage = ts('Profile is not configured for the selected action.');
654 //lets have sigle status message,
655 $this->assign('statusMessage', $statusMessage);
660 $this->assign('id', $this->_id
);
661 $this->assign('mode', $this->_mode
);
662 $this->assign('action', $this->_action
);
663 $this->assign('fields', $this->_fields
);
664 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
666 // should we restrict what we display
668 if ($this->_mode
== self
::MODE_EDIT
) {
670 // show all fields that are visibile:
671 // if we are a admin OR the same user OR acl-user with access to the profile
672 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
674 CRM_Core_Permission
::check('administer users') ||
675 $this->_id
== $this->_currentUserID ||
676 $this->_isPermissionedChecksum ||
680 CRM_Core_Permission
::EDIT
,
683 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
691 // if false, user is not logged-in.
693 if (!$this->_currentUserID
) {
694 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
695 $primaryLocationType = $defaultLocationType->id
;
698 $this->assign('anonUser', $anonUser);
700 $addCaptcha = array();
701 $emailPresent = FALSE;
703 // cache the state country fields. based on the results, we could use our javascript solution
704 // in create or register mode
705 $stateCountryMap = array();
707 // add the form elements
708 foreach ($this->_fields
as $name => $field) {
709 // make sure that there is enough permission to expose this field
710 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
711 unset($this->_fields
[$name]);
715 // since the CMS manages the email field, suppress the email display if in
716 // register mode which occur within the CMS form
717 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
718 unset($this->_fields
[$name]);
722 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
723 if ($prefixName == 'state_province' ||
$prefixName == 'country' ||
$prefixName == 'county') {
724 if (!array_key_exists($index, $stateCountryMap)) {
725 $stateCountryMap[$index] = array();
727 $stateCountryMap[$index][$prefixName] = $name;
730 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
732 if ($field['add_to_group_id']) {
733 $addToGroupId = $field['add_to_group_id'];
736 //build array for captcha
737 if ($field['add_captcha']) {
738 $addCaptcha[$field['group_id']] = $field['add_captcha'];
741 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
742 $emailPresent = TRUE;
743 $this->_mail
= $name;
747 // add captcha only for create mode.
748 if ($this->_mode
== self
::MODE_CREATE
) {
749 // suppress captcha for logged in users only
750 if ($this->_currentUserID
) {
751 $this->_isAddCaptcha
= FALSE;
753 else if (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
754 $this->_isAddCaptcha
= TRUE;
758 $dao = new CRM_Core_DAO_UFGroup();
759 $dao->id
= $this->_gid
;
761 $dao->addSelect('is_update_dupe');
762 if ($dao->find(TRUE)) {
763 if ($dao->is_update_dupe
) {
764 $this->_isUpdateDupe
= $dao->is_update_dupe
;
770 $this->_isAddCaptcha
= FALSE;
773 //finally add captcha to form.
774 if ($this->_isAddCaptcha
) {
775 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
776 $captcha->add($this);
778 $this->assign("isCaptcha", $this->_isAddCaptcha
);
780 if ($this->_mode
!= self
::MODE_SEARCH
) {
781 if (isset($addToGroupId)) {
782 $this->add('hidden', "add_to_group", $addToGroupId);
783 $this->_addToGroupID
= $addToGroupId;
787 // lets do the defaults, so we can use it for the below state country routines
788 $this->setDefaultsValues();
790 // also do state country js
791 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap, $this->_defaults
);
793 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
794 if ($this->_mode
== self
::MODE_CREATE
) {
795 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
798 $this->assign('showCMS', FALSE);
801 $this->assign('groupId', $this->_gid
);
803 // now fix all state country selectors
804 CRM_Core_BAO_Address
::fixAllStateSelects($this, $this->_defaults
);
806 // if view mode pls freeze it with the done button.
807 if ($this->_action
& CRM_Core_Action
::VIEW
) {
811 if ($this->_context
== 'dialog') {
814 $this->_duplicateButtonName
,
815 ts('Save Matching Contact')
821 * Function to validate profile and provided activity Id
823 * @params Integer $activityId Activity Id
824 * @params Integer $gid Profile Id
826 * @return Array $errors Errors ( if any ).
828 static function validateContactActivityProfile($activityId, $contactId, $gid) {
831 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
835 $activityDetails = array();
836 $activityParams = array('id' => $activityId);
837 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
839 if (empty($activityDetails)) {
840 $errors[] = 'Invalid Activity Id (aid).';
844 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
846 if ((CRM_Utils_Array
::value('Activity', $profileActivityTypes) &&
847 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
849 (!in_array($contactId, $activityDetails['assignee_contact']) &&
850 !in_array($contactId, $activityDetails['target_contact'])
853 $errors[] = 'This activity cannot be edited or viewed via this profile.';
862 * @param array $fields the input form values
863 * @param array $files the uploaded files if any
864 * @param object $form the form object
866 * @return true if no errors, else array of errors
870 static function formRule($fields, $files, $form) {
872 // if no values, return
873 if (empty($fields)) {
879 // hack we use a -1 in options to indicate that its registration
881 $form->_isUpdateDupe
= 1;
884 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
888 // dont check for duplicates during registration validation: CRM-375
889 if (!$register && !CRM_Utils_Array
::value('_qf_Edit_upload_duplicate', $fields)) {
891 if (CRM_Utils_Array
::value('email-Primary', $fields)) {
892 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
896 if (CRM_Utils_Array
::value('phone-Primary-1', $fields) &&
897 !CRM_Utils_Array
::value('phone-Primary', $fields)
899 $fields['phone-Primary'] = $fields['phone-Primary-1'];
902 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
903 // If all profile fields is of Contact Type then consider
904 // profile is of Individual type(default).
906 $ctype = 'Individual';
908 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $ctype);
909 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
911 $exceptions = array();
914 // for edit mode we need to allow our own record to be a dupe match!
915 $exceptions = array($form->_session
->get('userID'));
918 // for dialog mode we should always use fuzzy rule.
919 $ruleType = 'Unsupervised';
920 if ($form->_context
== 'dialog') {
921 $ruleType = 'Supervised';
924 $dedupeParams['check_permission'] = FALSE;
925 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams,
931 if ($form->_isUpdateDupe
== 2) {
932 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
934 elseif ($form->_isUpdateDupe
== 1) {
936 $form->_id
= $ids[0];
940 if ($form->_context
== 'dialog') {
941 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
943 $duplicateContactsLinks = '<div class="matching-contacts-found">';
944 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
945 if ($contactLinks['msg'] == 'view') {
946 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
949 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
951 $duplicateContactsLinks .= '</div>';
952 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
954 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++
) {
956 $row .= ' <td class="matching-contacts-name"> ';
957 $row .= $contactLinks['rows'][$i]['display_name'];
959 $row .= ' <td class="matching-contacts-email"> ';
960 $row .= $contactLinks['rows'][$i]['primary_email'];
962 $row .= ' <td class="action-items"> ';
963 $row .= $contactLinks['rows'][$i]['view'] . ' ';
964 $row .= $contactLinks['rows'][$i]['edit'];
969 $duplicateContactsLinks .= $row . '</table>';
970 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
972 $errors['_qf_default'] = $duplicateContactsLinks;
974 // let smarty know that there are duplicates
975 $template = CRM_Core_Smarty
::singleton();
976 $template->assign('isDuplicate', 1);
979 $errors['_qf_default'] = ts('A record already exists with the same information.');
985 foreach ($fields as $key => $value) {
986 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
987 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
988 // Validate Country - State list
989 $countryId = $fields["country-{$locTypeId}"];
990 $stateProvinceId = $value;
992 if ($stateProvinceId && $countryId) {
993 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
994 $stateProvinceDAO->id
= $stateProvinceId;
995 $stateProvinceDAO->find(TRUE);
997 if ($stateProvinceDAO->country_id
!= $countryId) {
998 // country mismatch hence display error
999 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1000 $countries = CRM_Core_PseudoConstant
::country();
1001 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1006 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1007 // Validate County - State list
1008 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1011 if ($countyId && $stateProvinceId) {
1012 $countyDAO = new CRM_Core_DAO_County();
1013 $countyDAO->id
= $countyId;
1014 $countyDAO->find(TRUE);
1016 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1017 // state province mismatch hence display error
1018 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1019 $counties = CRM_Core_PseudoConstant
::county();
1020 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1025 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1026 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1027 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1028 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1029 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1030 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1036 return empty($errors) ?
TRUE : $errors;
1040 * Process the user submitted custom data values.
1046 public function postProcess() {
1047 $params = $this->controller
->exportValues($this->_name
);
1049 //if the delete record button is clicked
1050 if ($this->_deleteButtonName
) {
1051 if (CRM_Utils_Array
::value($this->_deleteButtonName
, $_POST) && $this->_recordId
) {
1052 $filterParams['id'] = $this->_customGroupId
;
1053 $returnProperities = array('is_multiple', 'table_name');
1054 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperities);
1055 if (CRM_Utils_Array
::value('is_multiple', $returnValues)) {
1056 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1057 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1059 1 => array($this->_recordId
, 'Integer'),
1060 2 => array($this->_id
, 'Integer')
1062 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1063 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1069 if (CRM_Utils_Array
::value('image_URL', $params)) {
1070 CRM_Contact_BAO_Contact
::processImageParams($params);
1073 $greetingTypes = array(
1074 'addressee' => 'addressee_id',
1075 'email_greeting' => 'email_greeting_id',
1076 'postal_greeting' => 'postal_greeting_id',
1081 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1084 $details = $contactDetails[0][$this->_id
];
1086 if (!(CRM_Utils_Array
::value('addressee_id', $details) ||
1087 CRM_Utils_Array
::value('email_greeting_id', $details) ||
1088 CRM_Utils_Array
::value('postal_greeting_id', $details)
1091 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1092 //Though Profile type is contact we need
1093 //Individual/Household/Organization for setting Greetings.
1094 if ($profileType == 'Contact') {
1095 $profileType = 'Individual';
1096 //if we editing Household/Organization.
1098 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1101 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1102 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1105 foreach ($greetingTypes as $key => $value) {
1106 if (!array_key_exists($key, $params)) {
1107 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1112 $transaction = new CRM_Core_Transaction();
1114 //used to send subcribe mail to the group which user want.
1115 //if the profile double option in is enabled
1116 $mailingType = array();
1117 $config = CRM_Core_Config
::singleton();
1120 foreach ($params as $name => $values) {
1121 if (substr($name, 0, 6) == 'email-') {
1122 $result['email'] = $values;
1126 //array of group id, subscribed by contact
1127 $contactGroup = array();
1128 if (CRM_Utils_Array
::value('group', $params) &&
1129 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1131 $groupSubscribed = array();
1132 if (CRM_Utils_Array
::value('email', $result)) {
1134 $contactGroups = new CRM_Contact_DAO_GroupContact();
1135 $contactGroups->contact_id
= $this->_id
;
1136 $contactGroups->status
= 'Added';
1137 $contactGroups->find();
1138 $contactGroup = array();
1139 while ($contactGroups->fetch()) {
1140 $contactGroup[] = $contactGroups->group_id
;
1141 $groupSubscribed[$contactGroups->group_id
] = 1;
1144 foreach ($params['group'] as $key => $val) {
1146 unset($params['group'][$key]);
1149 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1150 $key, 'group_type', 'id'
1152 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1153 substr($groupTypes, 1, -1)
1155 //filter group of mailing type and unset it from params
1156 if (in_array(2, $groupType)) {
1157 //if group is already subscribed , ignore it
1158 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1159 if (!isset($groupExist)) {
1160 $mailingType[] = $key;
1161 unset($params['group'][$key]);
1168 $addToGroupId = NULL;
1169 if (CRM_Utils_Array
::value('add_to_group', $params)) {
1170 $addToGroupId = $params['add_to_group'];
1172 //run same check whether group is a mailing list
1173 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1174 $addToGroupId, 'group_type', 'id'
1176 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1177 substr($groupTypes, 1, -1)
1179 //filter group of mailing type and unset it from params
1180 if (in_array(2, $groupType) &&
1181 CRM_Utils_Array
::value('email', $result) &&
1182 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1184 if (!count($contactGroup)) {
1185 //array of group id, subscribed by contact
1186 $contactGroup = array();
1188 $contactGroups = new CRM_Contact_DAO_GroupContact();
1189 $contactGroups->contact_id
= $this->_id
;
1190 $contactGroups->status
= 'Added';
1191 $contactGroups->find();
1192 $contactGroup = array();
1193 while ($contactGroups->fetch()) {
1194 $contactGroup[] = $contactGroups->group_id
;
1195 $groupSubscribed[$contactGroups->group_id
] = 1;
1199 //if group is already subscribed , ignore it
1200 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1201 if (!isset($groupExist)) {
1202 $mailingType[] = $addToGroupId;
1203 $addToGroupId = NULL;
1207 // since we are directly adding contact to group lets unset it from mailing
1208 if ($key = array_search($addToGroupId, $mailingType)) {
1209 unset($mailingType[$key]);
1215 $params['group'] = $groupSubscribed;
1218 // commenting below code, since we potentially
1219 // triggered maximum name field formatting cases during CRM-4430.
1221 // $params['preserveDBName'] = true;
1223 $profileFields = $this->_fields
;
1224 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1225 $profileFields = $activityParams = array();
1226 foreach ($this->_fields
as $fieldName => $field) {
1227 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1228 if (isset($params[$fieldName])) {
1229 $activityParams[$fieldName] = $params[$fieldName];
1231 if (isset($params['activity_date_time'])) {
1232 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1234 if (CRM_Utils_Array
::value($fieldName, $params) && isset($params["{$fieldName}_id"])) {
1235 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1239 $profileFields[$fieldName] = $field;
1243 if (!empty($activityParams)) {
1244 $activityParams['version'] = 3;
1245 $activityParams['id'] = $this->_activityId
;
1246 $activityParams['skipRecentView'] = TRUE;
1247 civicrm_api('Activity', 'create', $activityParams);
1251 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1252 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1255 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1265 //mailing type group
1266 if (!empty($mailingType)) {
1267 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1269 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1272 $ufGroups = array();
1274 $ufGroups[$this->_gid
] = 1;
1276 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1277 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1280 foreach ($ufGroups as $gId => $val) {
1281 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1282 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1283 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1287 //create CMS user (if CMS user option is selected in profile)
1288 if (CRM_Utils_Array
::value('cms_create_account', $params) &&
1289 $this->_mode
== self
::MODE_CREATE
1291 $params['contactID'] = $this->_id
;
1292 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1293 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1294 $transaction->rollback();
1295 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1296 'reset=1&gid=' . $this->_gid
1301 $transaction->commit();
1304 function checkTemplateFileExists($suffix = NULL) {
1306 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1307 $template = CRM_Core_Form
::getTemplate();
1308 if ($template->template_exists($templateFile)) {
1309 return $templateFile;
1312 // lets see if we have customized by name
1313 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1315 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1316 if ($template->template_exists($templateFile)) {
1317 return $templateFile;
1324 function getTemplateFileName() {
1325 $fileName = $this->checkTemplateFileExists();
1326 return $fileName ?
$fileName : parent
::getTemplateFileName();
1329 function overrideExtraTemplateFileName() {
1330 $fileName = $this->checkTemplateFileExists('extra.');
1331 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();