3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 * @var array details of the UFGroup used on this page
72 protected $_ufGroup = array('name' => 'unknown');
75 * The group id that we are passing in url
82 * The title of the category we are editing
89 * the fields needed to build this form
96 * to store contact details
103 * Do we allow updates of the contact
107 public $_isUpdateDupe = 0;
109 public $_isAddCaptcha = FALSE;
111 protected $_isPermissionedChecksum = FALSE;
114 * THe context from which we came from, allows us to go there if redirect not set
121 * THe contact type for registration case
125 protected $_ctype = NULL;
127 protected $_defaults = NULL;
130 * Store profile ids if multiple profile ids are passed using comma separated.
131 * Currently lets implement this functionality only for dialog mode
133 protected $_profileIds = array();
136 * Contact profile having activity fields?
140 protected $_isContactActivityProfile = FALSE;
143 * Activity Id connected to the profile
147 protected $_activityId = NULL;
150 protected $_multiRecordFields = NULL;
152 protected $_recordId = NULL;
155 * action for multi record profile (create/edit/delete)
159 protected $_multiRecord = NULL;
161 protected $_multiRecordProfile = FALSE;
163 protected $_recordExists = TRUE;
165 protected $_customGroupTitle = NULL;
167 protected $_deleteButtonName = NULL;
169 protected $_customGroupId = NULL;
171 protected $_currentUserID = NULL;
172 protected $_session = NULL;
175 * pre processing work done here.
177 * gets session variables for table name, id of entity in table, type of entity and stores them.
185 function preProcess() {
186 $this->_id
= $this->get('id');
187 $this->_profileIds
= $this->get('profileIds');
188 $this->_grid
= CRM_Utils_Request
::retrieve('grid', 'Integer', $this);
189 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
191 //unset from session when $_GET doesn't have it
192 //except when the form is submitted
194 if (!array_key_exists('multiRecord', $_GET)) {
195 $this->set('multiRecord', NULL);
197 if (!array_key_exists('recordId', $_GET)) {
198 $this->set('recordId', NULL);
202 $this->_session
= CRM_Core_Session
::singleton();
203 $this->_currentUserID
= $this->_session
->get('userID');
205 if ($this->_mode
== self
::MODE_EDIT
) {
206 //specifies the action being done on a multi record field
207 $multiRecordAction = CRM_Utils_Request
::retrieve('multiRecord', 'String', $this);
208 $this->_multiRecord
= (!is_numeric($multiRecordAction)) ?
209 CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
210 if ($this->_multiRecord
) {
211 $this->set('multiRecord', $this->_multiRecord
);
214 if ($this->_multiRecord
&&
215 !in_array($this->_multiRecord
, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::DELETE
))) {
216 CRM_Core_Error
::fatal(ts('Proper action not specified for this custom value record profile'));
219 $this->_duplicateButtonName
= $this->getButtonName('upload', 'duplicate');
221 $gids = explode(',', CRM_Utils_Request
::retrieve('gid', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 0));
223 if ((count($gids) > 1) && !$this->_profileIds
&& empty($this->_profileIds
)) {
225 foreach ($gids as $pfId) {
226 $this->_profileIds
[] = CRM_Utils_Type
::escape($pfId, 'Positive');
230 // check if we are rendering mixed profiles
231 if (CRM_Core_BAO_UFGroup
::checkForMixProfiles($this->_profileIds
)) {
232 CRM_Core_Error
::fatal(ts('You cannot combine profiles of multiple types.'));
235 // for now consider 1'st profile as primary profile and validate it
236 // i.e check for profile type etc.
237 // FIX ME: validations for other than primary
238 $this->_gid
= $this->_profileIds
[0];
239 $this->set('gid', $this->_gid
);
240 $this->set('profileIds', $this->_profileIds
);
244 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE, 0);
245 $this->set('gid', $this->_gid
);
248 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
249 if (is_numeric($this->_activityId
)) {
250 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
251 if ($latestRevisionId) {
252 $this->_activityId
= $latestRevisionId;
255 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
257 //get values for ufGroupName, captch and dupe update.
259 $dao = new CRM_Core_DAO_UFGroup();
260 $dao->id
= $this->_gid
;
261 if ($dao->find(TRUE)) {
262 $this->_isUpdateDupe
= $dao->is_update_dupe
;
263 $this->_isAddCaptcha
= $dao->add_captcha
;
264 $this->_ufGroup
= (array) $dao;
268 if (!CRM_Utils_Array
::value('is_active', $this->_ufGroup
)) {
269 CRM_Core_Error
::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(
274 $this->assign('ufGroupName', $this->_ufGroup
['name']);
276 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
278 // if we dont have a gid use the default, else just use that specific gid
279 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
280 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
281 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
283 elseif ($this->_mode
== self
::MODE_SEARCH
) {
284 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
285 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
289 $this->_skipPermission
,
290 CRM_Core_Permission
::SEARCH
294 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
297 $this->_skipPermission
,
299 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
301 $multiRecordFieldListing = FALSE;
302 //using selector for listing of multirecord fields
303 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
304 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
306 if ($this->_multiRecord
) {
307 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
308 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
310 $this->_recordId
= NULL;
311 $this->set('recordId', NULL);
313 //record id is neccessary for _multiRecord view and update/edit action
314 if (!$this->_recordId
315 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
316 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
317 array(1 => $this->_gid
)
319 } elseif (empty($this->_multiRecordFields
)) {
320 CRM_Core_Error
::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
321 array(1 => $this->_gid
)
325 $fieldId = CRM_Core_BAO_CustomField
::getKeyID(key($this->_multiRecordFields
));
326 $customGroupDetails = CRM_Core_BAO_CustomGroup
::getGroupTitles(array($fieldId));
327 $this->_customGroupTitle
= $customGroupDetails[$fieldId]['groupTitle'];
328 $this->_customGroupId
= $customGroupDetails[$fieldId]['groupID'];
330 if ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
) {
331 //record exists check
332 foreach ($this->_multiRecordFields
as $key => $field) {
333 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
335 $getValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
337 if (array_key_exists($this->_recordId
, $getValues)) {
338 $this->_recordExists
= TRUE;
340 $this->_recordExists
= FALSE;
341 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
342 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');
346 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
347 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
348 if ($this->_maxRecordLimit
) {
349 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
353 } elseif (!empty($this->_multiRecordFields
)
354 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(CRM_Core_Action
::DELETE
, CRM_Core_Action
::UPDATE
)) )) {
355 //multirecord listing page
356 $multiRecordFieldListing = TRUE;
357 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
358 $cs = $this->get('cs');
359 $page->set('pageCheckSum', $cs);
360 $page->set('contactId', $this->_id
);
361 $page->set('profileId', $this->_gid
);
362 $page->set('action', CRM_Core_Action
::BROWSE
);
363 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
367 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
369 // is profile double-opt in?
370 if (CRM_Utils_Array
::value('group', $this->_fields
) &&
371 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
374 foreach ($this->_fields
as $name => $values) {
375 if (substr($name, 0, 6) == 'email-') {
381 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
382 $this->_session
->setStatus($status);
386 //transfering all the multirecord custom fields in _fields
387 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
388 $this->_fields
= $this->_multiRecordFields
;
389 $this->_multiRecordProfile
= TRUE;
390 } elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
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'));
396 if (!is_array($this->_fields
)) {
397 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
398 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
403 * This function sets the default values for the form. Note that in edit/view mode
404 * the default values are retrieved from the database
410 function setDefaultsValues() {
411 $this->_defaults
= array();
412 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
416 if ($this->_mode
!= self
::MODE_SEARCH
) {
417 // set default values for country / state to start with
418 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
421 if ($this->_id
&& !$this->_multiRecordProfile
) {
422 if ($this->_isContactActivityProfile
) {
423 $contactFields = $activityFields = array();
424 foreach ($this->_fields
as $fieldName => $field) {
425 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
426 $activityFields[$fieldName] = $field;
429 $contactFields[$fieldName] = $field;
433 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
434 if ($this->_activityId
) {
435 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
439 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
443 //set custom field defaults
444 if ($this->_multiRecordProfile
) {
445 foreach ($this->_multiRecordFields
as $key => $field) {
446 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
449 $defaultValues = array( );
450 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
451 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
452 if ($this->_recordExists
== TRUE) {
453 $defaultValues = $defaultValues[$this->_recordId
];
455 $defaultValues = NULL;
459 if (!empty($defaultValues)) {
460 foreach ($defaultValues as $key => $value) {
461 $name = "custom_{$key}";
462 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
463 if ($htmlType != 'File') {
465 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
473 $this->_defaults
[$name] = "";
477 if ($htmlType == 'File') {
478 $entityId = $this->_id
;
479 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
482 $entityId = $this->_activityId
;
484 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key);
487 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
489 $deleteExtra = ts("Are you sure you want to delete attached file?");
490 $fileId = $url['file_id'];
491 $deleteURL = CRM_Utils_System
::url('civicrm/file',
492 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
494 $text = ts("Delete Attached File");
495 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
497 // also delete the required rule that we've set on the form element
498 $this->removeFileRequiredRules($name);
505 foreach ($this->_fields
as $name => $field) {
506 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
507 $htmlType = $field['html_type'];
508 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
509 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
511 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
519 if ($htmlType == 'File') {
520 $entityId = $this->_id
;
521 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
522 $entityId = $this->_activityId
;
524 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
527 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
529 $deleteExtra = ts("Are you sure you want to delete attached file?");
530 $fileId = $url['file_id'];
531 $deleteURL = CRM_Utils_System
::url('civicrm/file',
532 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
534 $text = ts("Delete Attached File");
535 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
537 // also delete the required rule that we've set on the form element
538 $this->removeFileRequiredRules($field['name']);
544 if (isset($customFiles)) {
545 $this->assign('customFiles', $customFiles);
548 if ($this->_multiRecordProfile
) {
549 $this->setDefaults($this->_defaults
);
553 if (CRM_Utils_Array
::value('image_URL', $this->_defaults
)) {
554 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String
::unstupifyUrl($this->_defaults
['image_URL']));
555 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
556 $this->assign("imageWidth", $imageWidth);
557 $this->assign("imageHeight", $imageHeight);
558 $this->assign("imageThumbWidth", $imageThumbWidth);
559 $this->assign("imageThumbHeight", $imageThumbHeight);
560 $this->assign("imageURL", $this->_defaults
['image_URL']);
561 $this->removeFileRequiredRules('image_URL');
564 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
565 !empty($this->_defaults
['contact_sub_type'])
567 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
568 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
572 $this->setDefaults($this->_defaults
);
576 * Function to actually build the form
581 public function buildQuickForm() {
582 $this->add('hidden', 'gid', $this->_gid
);
584 switch ($this->_mode
) {
585 case self
::MODE_CREATE
:
586 case self
::MODE_EDIT
:
587 case self
::MODE_REGISTER
:
588 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
590 case self
::MODE_SEARCH
:
591 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
596 //lets have single status message, CRM-4363
598 $statusMessage = NULL;
599 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
603 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
604 if (!$this->_recordExists
) {
605 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
608 $this->assign('deleteRecord', TRUE);
613 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
615 // we should not allow component and mix profiles in search mode
616 if ($this->_mode
!= self
::MODE_REGISTER
) {
617 //check for mix profile fields (eg: individual + other contact type)
618 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
619 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
620 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
621 if (!empty($errors)) {
622 $statusMessage = array_pop($errors);
627 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
632 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
635 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
636 $contactType = $contactTypes[0];
638 array_shift($contactTypes);
639 $contactSubtypes = $contactTypes;
641 $profileSubType = FALSE;
642 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
643 $profileSubType = $profileType;
644 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
648 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
649 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType,$contactSubtypes))) ||
650 ($profileType != $contactType))
653 if (!$statusMessage) {
655 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
656 array(1 => $profileSubType ?
$profileSubType : $profileType));
664 array("Membership", "Participant", "Contribution")
668 if (!$statusMessage) {
669 $statusMessage = ts('Profile is not configured for the selected action.');
674 //lets have sigle status message,
675 $this->assign('statusMessage', $statusMessage);
680 $this->assign('id', $this->_id
);
681 $this->assign('mode', $this->_mode
);
682 $this->assign('action', $this->_action
);
683 $this->assign('fields', $this->_fields
);
684 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
686 // should we restrict what we display
688 if ($this->_mode
== self
::MODE_EDIT
) {
690 // show all fields that are visibile:
691 // if we are a admin OR the same user OR acl-user with access to the profile
692 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
694 CRM_Core_Permission
::check('administer users') ||
695 $this->_id
== $this->_currentUserID ||
696 $this->_isPermissionedChecksum ||
700 CRM_Core_Permission
::EDIT
,
703 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
711 // if false, user is not logged-in.
713 if (!$this->_currentUserID
) {
714 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
715 $primaryLocationType = $defaultLocationType->id
;
718 $this->assign('anonUser', $anonUser);
720 $addCaptcha = array();
721 $emailPresent = FALSE;
723 // cache the state country fields. based on the results, we could use our javascript solution
724 // in create or register mode
725 $stateCountryMap = array();
727 // add the form elements
728 foreach ($this->_fields
as $name => $field) {
729 // make sure that there is enough permission to expose this field
730 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
731 unset($this->_fields
[$name]);
735 // since the CMS manages the email field, suppress the email display if in
736 // register mode which occur within the CMS form
737 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
738 unset($this->_fields
[$name]);
742 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
743 if ($prefixName == 'state_province' ||
$prefixName == 'country' ||
$prefixName == 'county') {
744 if (!array_key_exists($index, $stateCountryMap)) {
745 $stateCountryMap[$index] = array();
747 $stateCountryMap[$index][$prefixName] = $name;
750 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
752 if ($field['add_to_group_id']) {
753 $addToGroupId = $field['add_to_group_id'];
756 //build array for captcha
757 if ($field['add_captcha']) {
758 $addCaptcha[$field['group_id']] = $field['add_captcha'];
761 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
762 $emailPresent = TRUE;
763 $this->_mail
= $name;
767 // add captcha only for create mode.
768 if ($this->_mode
== self
::MODE_CREATE
) {
769 // suppress captcha for logged in users only
770 if ($this->_currentUserID
) {
771 $this->_isAddCaptcha
= FALSE;
773 else if (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
774 $this->_isAddCaptcha
= TRUE;
778 $dao = new CRM_Core_DAO_UFGroup();
779 $dao->id
= $this->_gid
;
781 $dao->addSelect('is_update_dupe');
782 if ($dao->find(TRUE)) {
783 if ($dao->is_update_dupe
) {
784 $this->_isUpdateDupe
= $dao->is_update_dupe
;
790 $this->_isAddCaptcha
= FALSE;
793 //finally add captcha to form.
794 if ($this->_isAddCaptcha
) {
795 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
796 $captcha->add($this);
798 $this->assign("isCaptcha", $this->_isAddCaptcha
);
800 if ($this->_mode
!= self
::MODE_SEARCH
) {
801 if (isset($addToGroupId)) {
802 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
806 // lets do the defaults, so we can use it for the below state country routines
807 $this->setDefaultsValues();
809 // also do state country js
810 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap, $this->_defaults
);
812 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
813 if ($this->_mode
== self
::MODE_CREATE
) {
814 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
817 $this->assign('showCMS', FALSE);
820 $this->assign('groupId', $this->_gid
);
822 // now fix all state country selectors
823 CRM_Core_BAO_Address
::fixAllStateSelects($this, $this->_defaults
);
825 // if view mode pls freeze it with the done button.
826 if ($this->_action
& CRM_Core_Action
::VIEW
) {
830 if ($this->_context
== 'dialog') {
833 $this->_duplicateButtonName
,
834 ts('Save Matching Contact')
840 * Function to validate profile and provided activity Id
842 * @params Integer $activityId Activity Id
843 * @params Integer $gid Profile Id
845 * @return Array $errors Errors ( if any ).
847 static function validateContactActivityProfile($activityId, $contactId, $gid) {
850 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
854 $activityDetails = array();
855 $activityParams = array('id' => $activityId);
856 CRM_Activity_BAO_Activity
::retrieve($activityParams, $activityDetails);
858 if (empty($activityDetails)) {
859 $errors[] = 'Invalid Activity Id (aid).';
863 $profileActivityTypes = CRM_Core_BAO_UFGroup
::groupTypeValues($gid, 'Activity');
865 if ((CRM_Utils_Array
::value('Activity', $profileActivityTypes) &&
866 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
868 (!in_array($contactId, $activityDetails['assignee_contact']) &&
869 !in_array($contactId, $activityDetails['target_contact'])
872 $errors[] = 'This activity cannot be edited or viewed via this profile.';
881 * @param array $fields the input form values
882 * @param array $files the uploaded files if any
883 * @param object $form the form object
885 * @return true if no errors, else array of errors
889 static function formRule($fields, $files, $form) {
890 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
893 // if no values, return
894 if (empty($fields)) {
900 // hack we use a -1 in options to indicate that its registration
902 $form->_isUpdateDupe
= 1;
905 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
909 // dont check for duplicates during registration validation: CRM-375
910 if (!$register && !CRM_Utils_Array
::value('_qf_Edit_upload_duplicate', $fields)) {
912 if (CRM_Utils_Array
::value('email-Primary', $fields)) {
913 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
917 if (CRM_Utils_Array
::value('phone-Primary-1', $fields) &&
918 !CRM_Utils_Array
::value('phone-Primary', $fields)
920 $fields['phone-Primary'] = $fields['phone-Primary-1'];
923 $ctype = CRM_Core_BAO_UFGroup
::getContactType($form->_gid
);
924 // If all profile fields is of Contact Type then consider
925 // profile is of Individual type(default).
927 $ctype = 'Individual';
929 $dedupeParams = CRM_Dedupe_Finder
::formatParams($fields, $ctype);
930 if ($form->_mode
== CRM_Profile_Form
::MODE_CREATE
) {
932 $exceptions = array();
935 // for edit mode we need to allow our own record to be a dupe match!
936 $exceptions = array($form->_session
->get('userID'));
939 // for dialog mode we should always use fuzzy rule.
940 $ruleType = 'Unsupervised';
941 if ($form->_context
== 'dialog') {
942 $ruleType = 'Supervised';
945 $dedupeParams['check_permission'] = FALSE;
946 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams,
952 if ($form->_isUpdateDupe
== 2) {
953 CRM_Core_Session
::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
955 elseif ($form->_isUpdateDupe
== 1) {
957 $form->_id
= $ids[0];
961 if ($form->_context
== 'dialog') {
962 $contactLinks = CRM_Contact_BAO_Contact_Utils
::formatContactIDSToLinks($ids, TRUE, TRUE);
964 $duplicateContactsLinks = '<div class="matching-contacts-found">';
965 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
966 if ($contactLinks['msg'] == 'view') {
967 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
970 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
972 $duplicateContactsLinks .= '</div>';
973 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
975 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++
) {
977 $row .= ' <td class="matching-contacts-name"> ';
978 $row .= $contactLinks['rows'][$i]['display_name'];
980 $row .= ' <td class="matching-contacts-email"> ';
981 $row .= $contactLinks['rows'][$i]['primary_email'];
983 $row .= ' <td class="action-items"> ';
984 $row .= $contactLinks['rows'][$i]['view'] . ' ';
985 $row .= $contactLinks['rows'][$i]['edit'];
990 $duplicateContactsLinks .= $row . '</table>';
991 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
993 $errors['_qf_default'] = $duplicateContactsLinks;
995 // let smarty know that there are duplicates
996 $template = CRM_Core_Smarty
::singleton();
997 $template->assign('isDuplicate', 1);
1000 $errors['_qf_default'] = ts('A record already exists with the same information.');
1006 foreach ($fields as $key => $value) {
1007 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1008 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1009 // Validate Country - State list
1010 $countryId = $fields["country-{$locTypeId}"];
1011 $stateProvinceId = $value;
1013 if ($stateProvinceId && $countryId) {
1014 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1015 $stateProvinceDAO->id
= $stateProvinceId;
1016 $stateProvinceDAO->find(TRUE);
1018 if ($stateProvinceDAO->country_id
!= $countryId) {
1019 // country mismatch hence display error
1020 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1021 $countries = CRM_Core_PseudoConstant
::country();
1022 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1027 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1028 // Validate County - State list
1029 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1032 if ($countyId && $stateProvinceId) {
1033 $countyDAO = new CRM_Core_DAO_County();
1034 $countyDAO->id
= $countyId;
1035 $countyDAO->find(TRUE);
1037 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1038 // state province mismatch hence display error
1039 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1040 $counties = CRM_Core_PseudoConstant
::county();
1041 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1046 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1047 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1048 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1049 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1050 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1051 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1057 return empty($errors) ?
TRUE : $errors;
1061 * Process the user submitted custom data values.
1067 public function postProcess() {
1068 $params = $this->controller
->exportValues($this->_name
);
1070 //if the delete record button is clicked
1071 if ($this->_deleteButtonName
) {
1072 if (CRM_Utils_Array
::value($this->_deleteButtonName
, $_POST) && $this->_recordId
) {
1073 $filterParams['id'] = $this->_customGroupId
;
1074 $returnProperities = array('is_multiple', 'table_name');
1075 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperities);
1076 if (CRM_Utils_Array
::value('is_multiple', $returnValues)) {
1077 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1078 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1080 1 => array($this->_recordId
, 'Integer'),
1081 2 => array($this->_id
, 'Integer')
1083 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1084 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1090 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1091 if (CRM_Utils_Array
::value('image_URL', $params)) {
1092 CRM_Contact_BAO_Contact
::processImageParams($params);
1095 $greetingTypes = array(
1096 'addressee' => 'addressee_id',
1097 'email_greeting' => 'email_greeting_id',
1098 'postal_greeting' => 'postal_greeting_id',
1103 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1106 $details = $contactDetails[0][$this->_id
];
1108 if (!(CRM_Utils_Array
::value('addressee_id', $details) ||
1109 CRM_Utils_Array
::value('email_greeting_id', $details) ||
1110 CRM_Utils_Array
::value('postal_greeting_id', $details)
1113 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1114 //Though Profile type is contact we need
1115 //Individual/Household/Organization for setting Greetings.
1116 if ($profileType == 'Contact') {
1117 $profileType = 'Individual';
1118 //if we editing Household/Organization.
1120 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1123 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1124 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1127 foreach ($greetingTypes as $key => $value) {
1128 if (!array_key_exists($key, $params)) {
1129 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1134 $transaction = new CRM_Core_Transaction();
1136 //used to send subcribe mail to the group which user want.
1137 //if the profile double option in is enabled
1138 $mailingType = array();
1139 $config = CRM_Core_Config
::singleton();
1142 foreach ($params as $name => $values) {
1143 if (substr($name, 0, 6) == 'email-') {
1144 $result['email'] = $values;
1148 //array of group id, subscribed by contact
1149 $contactGroup = array();
1150 if (CRM_Utils_Array
::value('group', $params) &&
1151 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1153 $groupSubscribed = array();
1154 if (CRM_Utils_Array
::value('email', $result)) {
1156 $contactGroups = new CRM_Contact_DAO_GroupContact();
1157 $contactGroups->contact_id
= $this->_id
;
1158 $contactGroups->status
= 'Added';
1159 $contactGroups->find();
1160 $contactGroup = array();
1161 while ($contactGroups->fetch()) {
1162 $contactGroup[] = $contactGroups->group_id
;
1163 $groupSubscribed[$contactGroups->group_id
] = 1;
1166 foreach ($params['group'] as $key => $val) {
1168 unset($params['group'][$key]);
1171 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1172 $key, 'group_type', 'id'
1174 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1175 substr($groupTypes, 1, -1)
1177 //filter group of mailing type and unset it from params
1178 if (in_array(2, $groupType)) {
1179 //if group is already subscribed , ignore it
1180 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1181 if (!isset($groupExist)) {
1182 $mailingType[] = $key;
1183 unset($params['group'][$key]);
1190 $addToGroupId = CRM_Utils_Array
::value('add_to_group_id', $this->_ufGroup
);
1191 if ($addToGroupId) {
1192 //run same check whether group is a mailing list
1193 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1194 $addToGroupId, 'group_type', 'id'
1196 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1197 substr($groupTypes, 1, -1)
1199 //filter group of mailing type and unset it from params
1200 if (in_array(2, $groupType) &&
1201 CRM_Utils_Array
::value('email', $result) &&
1202 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1204 if (!count($contactGroup)) {
1205 //array of group id, subscribed by contact
1206 $contactGroup = array();
1208 $contactGroups = new CRM_Contact_DAO_GroupContact();
1209 $contactGroups->contact_id
= $this->_id
;
1210 $contactGroups->status
= 'Added';
1211 $contactGroups->find();
1212 $contactGroup = array();
1213 while ($contactGroups->fetch()) {
1214 $contactGroup[] = $contactGroups->group_id
;
1215 $groupSubscribed[$contactGroups->group_id
] = 1;
1219 //if group is already subscribed , ignore it
1220 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1221 if (!isset($groupExist)) {
1222 $mailingType[] = $addToGroupId;
1223 $addToGroupId = NULL;
1227 // since we are directly adding contact to group lets unset it from mailing
1228 if ($key = array_search($addToGroupId, $mailingType)) {
1229 unset($mailingType[$key]);
1235 $params['group'] = $groupSubscribed;
1238 // commenting below code, since we potentially
1239 // triggered maximum name field formatting cases during CRM-4430.
1241 // $params['preserveDBName'] = true;
1243 $profileFields = $this->_fields
;
1244 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1245 $profileFields = $activityParams = array();
1246 foreach ($this->_fields
as $fieldName => $field) {
1247 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1248 if (isset($params[$fieldName])) {
1249 $activityParams[$fieldName] = $params[$fieldName];
1251 if (isset($params['activity_date_time'])) {
1252 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1254 if (CRM_Utils_Array
::value($fieldName, $params) && isset($params["{$fieldName}_id"])) {
1255 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1259 $profileFields[$fieldName] = $field;
1263 if (!empty($activityParams)) {
1264 $activityParams['version'] = 3;
1265 $activityParams['id'] = $this->_activityId
;
1266 $activityParams['skipRecentView'] = TRUE;
1267 civicrm_api('Activity', 'create', $activityParams);
1271 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1272 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1275 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1285 //mailing type group
1286 if (!empty($mailingType)) {
1287 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1289 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1292 $ufGroups = array();
1294 $ufGroups[$this->_gid
] = 1;
1296 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1297 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1300 foreach ($ufGroups as $gId => $val) {
1301 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1302 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1303 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1307 //create CMS user (if CMS user option is selected in profile)
1308 if (CRM_Utils_Array
::value('cms_create_account', $params) &&
1309 $this->_mode
== self
::MODE_CREATE
1311 $params['contactID'] = $this->_id
;
1312 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1313 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1314 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1315 $transaction->rollback();
1316 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1317 'reset=1&gid=' . $this->_gid
1322 $transaction->commit();
1325 function checkTemplateFileExists($suffix = NULL) {
1327 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1328 $template = CRM_Core_Form
::getTemplate();
1329 if ($template->template_exists($templateFile)) {
1330 return $templateFile;
1333 // lets see if we have customized by name
1334 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1336 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1337 if ($template->template_exists($templateFile)) {
1338 return $templateFile;
1345 function getTemplateFileName() {
1346 $fileName = $this->checkTemplateFileExists();
1347 return $fileName ?
$fileName : parent
::getTemplateFileName();
1350 function overrideExtraTemplateFileName() {
1351 $fileName = $this->checkTemplateFileExists('extra.');
1352 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();