3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * @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 * Name of button for saving matching contacts
85 protected $_duplicateButtonName;
87 * The title of the category we are editing
94 * The fields needed to build this form
101 * store contact details
108 * Do we allow updates of the contact
112 public $_isUpdateDupe = 0;
114 public $_isAddCaptcha = FALSE;
116 protected $_isPermissionedChecksum = FALSE;
119 * THe context from which we came from, allows us to go there if redirect not set
126 * THe contact type for registration case
130 protected $_ctype = NULL;
132 protected $_defaults = NULL;
135 * Store profile ids if multiple profile ids are passed using comma separated.
136 * Currently lets implement this functionality only for dialog mode
138 protected $_profileIds = array();
141 * Contact profile having activity fields?
145 protected $_isContactActivityProfile = FALSE;
148 * Activity Id connected to the profile
152 protected $_activityId = NULL;
155 protected $_multiRecordFields = NULL;
157 protected $_recordId = NULL;
160 * Action for multi record profile (create/edit/delete)
164 protected $_multiRecord = NULL;
166 protected $_multiRecordProfile = FALSE;
168 protected $_recordExists = TRUE;
170 protected $_customGroupTitle = NULL;
172 protected $_deleteButtonName = NULL;
174 protected $_customGroupId = NULL;
176 protected $_currentUserID = NULL;
177 protected $_session = NULL;
180 * Pre processing work done here.
182 * gets session variables for table name, id of entity in table, type of entity and stores them.
188 public function preProcess() {
189 $this->_id
= $this->get('id');
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)) ? CRM_Core_Action
::resolve($multiRecordAction) : $multiRecordAction;
212 if ($this->_multiRecord
) {
213 $this->set('multiRecord', $this->_multiRecord
);
216 if ($this->_multiRecord
&&
217 !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));
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);
248 $this->set('gid', $this->_gid
);
251 $this->_activityId
= CRM_Utils_Request
::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
252 if (is_numeric($this->_activityId
)) {
253 $latestRevisionId = CRM_Activity_BAO_Activity
::getLatestActivityId($this->_activityId
);
254 if ($latestRevisionId) {
255 $this->_activityId
= $latestRevisionId;
258 $this->_isContactActivityProfile
= CRM_Core_BAO_UFField
::checkContactActivityProfileType($this->_gid
);
260 //get values for ufGroupName, captch and dupe update.
262 $dao = new CRM_Core_DAO_UFGroup();
263 $dao->id
= $this->_gid
;
264 if ($dao->find(TRUE)) {
265 $this->_isUpdateDupe
= $dao->is_update_dupe
;
266 $this->_isAddCaptcha
= $dao->add_captcha
;
267 $this->_ufGroup
= (array) $dao;
271 if (!CRM_Utils_Array
::value('is_active', $this->_ufGroup
)) {
272 CRM_Core_Error
::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(
277 $this->assign('ufGroupName', $this->_ufGroup
['name']);
279 $gids = empty($this->_profileIds
) ?
$this->_gid
: $this->_profileIds
;
281 // if we dont have a gid use the default, else just use that specific gid
282 if (($this->_mode
== self
::MODE_REGISTER ||
$this->_mode
== self
::MODE_CREATE
) && !$this->_gid
) {
283 $this->_ctype
= CRM_Utils_Request
::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
284 $this->_fields
= CRM_Core_BAO_UFGroup
::getRegistrationFields($this->_action
, $this->_mode
, $this->_ctype
);
286 elseif ($this->_mode
== self
::MODE_SEARCH
) {
287 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields($this->_action
,
288 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
292 $this->_skipPermission
,
293 CRM_Core_Permission
::SEARCH
297 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($gids, FALSE, NULL,
300 $this->_skipPermission
,
302 ($this->_action
== CRM_Core_Action
::ADD
) ? CRM_Core_Permission
::CREATE
: CRM_Core_Permission
::EDIT
304 $multiRecordFieldListing = FALSE;
305 //using selector for listing of multirecord fields
306 if ($this->_mode
== self
::MODE_EDIT
&& $this->_gid
) {
307 CRM_Core_BAO_UFGroup
::shiftMultiRecordFields($this->_fields
, $this->_multiRecordFields
);
309 if ($this->_multiRecord
) {
310 if ($this->_multiRecord
!= CRM_Core_Action
::ADD
) {
311 $this->_recordId
= CRM_Utils_Request
::retrieve('recordId', 'Positive', $this);
314 $this->_recordId
= NULL;
315 $this->set('recordId', NULL);
317 //record id is neccessary for _multiRecord view and update/edit action
318 if (!$this->_recordId
319 && ($this->_multiRecord
== CRM_Core_Action
::UPDATE ||
$this->_multiRecord
== CRM_Core_Action
::DELETE
)
321 CRM_Core_Error
::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
322 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;
347 $this->_recordExists
= FALSE;
348 if ($this->_multiRecord
& CRM_Core_Action
::UPDATE
) {
349 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');
353 if ($this->_multiRecord
& CRM_Core_Action
::ADD
) {
354 $this->_maxRecordLimit
= CRM_Core_BAO_CustomGroup
::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id
);
355 if ($this->_maxRecordLimit
) {
356 CRM_Core_Session
::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
361 elseif (!empty($this->_multiRecordFields
)
362 && (!$this->_multiRecord ||
!in_array($this->_multiRecord
, array(
363 CRM_Core_Action
::DELETE
,
364 CRM_Core_Action
::UPDATE
,
367 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
368 //multirecord listing page
369 $multiRecordFieldListing = TRUE;
370 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
371 $cs = $this->get('cs');
372 $page->set('pageCheckSum', $cs);
373 $page->set('contactId', $this->_id
);
374 $page->set('profileId', $this->_gid
);
375 $page->set('action', CRM_Core_Action
::BROWSE
);
376 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
380 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
382 // is profile double-opt in?
383 if (!empty($this->_fields
['group']) &&
384 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
387 foreach ($this->_fields
as $name => $values) {
388 if (substr($name, 0, 6) == 'email-') {
394 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
395 $this->_session
->setStatus($status);
399 //transferring all the multi-record custom fields in _fields
400 if ($this->_multiRecord
&& !empty($this->_multiRecordFields
)) {
401 $this->_fields
= $this->_multiRecordFields
;
402 $this->_multiRecordProfile
= TRUE;
404 elseif ($this->_multiRecord
&& empty($this->_multiRecordFields
)) {
405 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
406 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
410 if (!is_array($this->_fields
)) {
411 CRM_Core_Session
::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
412 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm', 'reset=1'));
417 * Set default values for the form. Note that in edit/view mode
418 * the default values are retrieved from the database
423 public function setDefaultsValues() {
424 $this->_defaults
= array();
425 if ($this->_multiRecordProfile
&& ($this->_multiRecord
== CRM_Core_Action
::DELETE
)) {
429 if ($this->_mode
!= self
::MODE_SEARCH
) {
430 // set default values for country / state to start with
431 CRM_Core_BAO_UFGroup
::setRegisterDefaults($this->_fields
, $this->_defaults
);
434 if ($this->_id
&& !$this->_multiRecordProfile
) {
435 if ($this->_isContactActivityProfile
) {
436 $contactFields = $activityFields = array();
437 foreach ($this->_fields
as $fieldName => $field) {
438 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
439 $activityFields[$fieldName] = $field;
442 $contactFields[$fieldName] = $field;
446 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $contactFields, $this->_defaults
, TRUE);
447 if ($this->_activityId
) {
448 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $this->_activityId
, 'Activity', $this->_defaults
, TRUE);
452 CRM_Core_BAO_UFGroup
::setProfileDefaults($this->_id
, $this->_fields
, $this->_defaults
, TRUE);
456 //set custom field defaults
457 if ($this->_multiRecordProfile
) {
458 foreach ($this->_multiRecordFields
as $key => $field) {
459 $fieldIds[] = CRM_Core_BAO_CustomField
::getKeyID($key);
462 $defaultValues = array();
463 if ($this->_multiRecord
&& $this->_multiRecord
== CRM_Core_Action
::UPDATE
) {
464 $defaultValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($this->_id
, NULL, $fieldIds, TRUE);
465 if ($this->_recordExists
== TRUE) {
466 $defaultValues = $defaultValues[$this->_recordId
];
469 $defaultValues = NULL;
473 if (!empty($defaultValues)) {
474 foreach ($defaultValues as $key => $value) {
475 $name = "custom_{$key}";
476 $htmlType = $this->_multiRecordFields
[$name]['html_type'];
477 if ($htmlType != 'File') {
479 CRM_Core_BAO_CustomField
::setProfileDefaults($key,
488 $this->_defaults
[$name] = "";
492 if ($htmlType == 'File') {
493 $entityId = $this->_id
;
494 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' &&
497 $entityId = $this->_activityId
;
499 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $key);
502 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
504 $deleteExtra = ts("Are you sure you want to delete attached file?");
505 $fileId = $url['file_id'];
506 $deleteURL = CRM_Utils_System
::url('civicrm/file',
507 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
509 $text = ts("Delete Attached File");
510 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
512 // also delete the required rule that we've set on the form element
513 $this->removeFileRequiredRules($name);
520 foreach ($this->_fields
as $name => $field) {
521 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
522 $htmlType = $field['html_type'];
523 if ((!isset($this->_defaults
[$name]) ||
$htmlType == 'File') &&
524 (CRM_Utils_Array
::value('field_type', $field) != 'Activity')
526 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID,
534 if ($htmlType == 'File') {
535 $entityId = $this->_id
;
536 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity' && $this->_activityId
) {
537 $entityId = $this->_activityId
;
539 $url = CRM_Core_BAO_CustomField
::getFileURL($entityId, $customFieldID);
542 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
544 $deleteExtra = ts("Are you sure you want to delete attached file?");
545 $fileId = $url['file_id'];
546 $deleteURL = CRM_Utils_System
::url('civicrm/file',
547 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
549 $text = ts("Delete Attached File");
550 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&confirmed=1'; else return false;\">$text</a>";
552 // also delete the required rule that we've set on the form element
553 $this->removeFileRequiredRules($field['name']);
559 if (isset($customFiles)) {
560 $this->assign('customFiles', $customFiles);
563 if ($this->_multiRecordProfile
) {
564 $this->setDefaults($this->_defaults
);
568 if (!empty($this->_defaults
['image_URL'])) {
569 list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String
::unstupifyUrl($this->_defaults
['image_URL']));
570 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
571 $this->assign("imageWidth", $imageWidth);
572 $this->assign("imageHeight", $imageHeight);
573 $this->assign("imageThumbWidth", $imageThumbWidth);
574 $this->assign("imageThumbHeight", $imageThumbHeight);
575 $this->assign("imageURL", $this->_defaults
['image_URL']);
576 $this->removeFileRequiredRules('image_URL');
579 if (array_key_exists('contact_sub_type', $this->_defaults
) &&
580 !empty($this->_defaults
['contact_sub_type'])
582 $this->_defaults
['contact_sub_type'] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
583 trim($this->_defaults
['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
)
587 $this->setDefaults($this->_defaults
);
591 * Build the form object
595 public function buildQuickForm() {
596 $this->add('hidden', 'gid', $this->_gid
);
598 switch ($this->_mode
) {
599 case self
::MODE_CREATE
:
600 case self
::MODE_EDIT
:
601 case self
::MODE_REGISTER
:
602 CRM_Utils_Hook
::buildProfile($this->_ufGroup
['name']);
605 case self
::MODE_SEARCH
:
606 CRM_Utils_Hook
::searchProfile($this->_ufGroup
['name']);
612 //lets have single status message, CRM-4363
614 $statusMessage = NULL;
615 if (($this->_multiRecord
& CRM_Core_Action
::ADD
) && $this->_maxRecordLimit
) {
619 if (($this->_multiRecord
& CRM_Core_Action
::DELETE
)) {
620 if (!$this->_recordExists
) {
621 CRM_Core_Session
::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId
)), ts('Record doesnot exists'), 'alert');
624 $this->assign('deleteRecord', TRUE);
629 CRM_Core_BAO_Address
::checkContactSharedAddressFields($this->_fields
, $this->_id
);
631 // we should not allow component and mix profiles in search mode
632 if ($this->_mode
!= self
::MODE_REGISTER
) {
633 //check for mix profile fields (eg: individual + other contact type)
634 if (CRM_Core_BAO_UFField
::checkProfileType($this->_gid
)) {
635 if (($this->_mode
& self
::MODE_EDIT
) && $this->_isContactActivityProfile
) {
636 $errors = self
::validateContactActivityProfile($this->_activityId
, $this->_id
, $this->_gid
);
637 if (!empty($errors)) {
638 $statusMessage = array_pop($errors);
643 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
648 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
651 $contactTypes = CRM_Contact_BAO_Contact
::getContactTypes($this->_id
);
652 $contactType = $contactTypes[0];
654 array_shift($contactTypes);
655 $contactSubtypes = $contactTypes;
657 $profileSubType = FALSE;
658 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
659 $profileSubType = $profileType;
660 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
664 ($profileType != 'Contact' && !$this->_isContactActivityProfile
) &&
665 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
666 ($profileType != $contactType))
669 if (!$statusMessage) {
670 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
671 array(1 => $profileSubType ?
$profileSubType : $profileType));
679 array("Membership", "Participant", "Contribution")
683 if (!$statusMessage) {
684 $statusMessage = ts('Profile is not configured for the selected action.');
689 //lets have single status message,
690 $this->assign('statusMessage', $statusMessage);
695 $this->assign('id', $this->_id
);
696 $this->assign('mode', $this->_mode
);
697 $this->assign('action', $this->_action
);
698 $this->assign('fields', $this->_fields
);
699 $this->assign('fieldset', (isset($this->_fieldset
)) ?
$this->_fieldset
: "");
701 // should we restrict what we display
703 if ($this->_mode
== self
::MODE_EDIT
) {
705 // show all fields that are visibile:
706 // if we are a admin OR the same user OR acl-user with access to the profile
707 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
709 CRM_Core_Permission
::check('administer users') ||
710 $this->_id
== $this->_currentUserID ||
711 $this->_isPermissionedChecksum ||
715 CRM_Core_Permission
::EDIT
,
718 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id')
726 // if false, user is not logged-in.
728 if (!$this->_currentUserID
) {
729 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
730 $primaryLocationType = $defaultLocationType->id
;
733 $this->assign('anonUser', $anonUser);
735 $addCaptcha = array();
736 $emailPresent = FALSE;
738 // add the form elements
739 foreach ($this->_fields
as $name => $field) {
740 // make sure that there is enough permission to expose this field
741 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
742 unset($this->_fields
[$name]);
746 // since the CMS manages the email field, suppress the email display if in
747 // register mode which occur within the CMS form
748 if ($this->_mode
== self
::MODE_REGISTER
&& substr($name, 0, 5) == 'email') {
749 unset($this->_fields
[$name]);
753 list($prefixName, $index) = CRM_Utils_System
::explode('-', $name, 2);
755 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, $this->_mode
);
757 if ($field['add_to_group_id']) {
758 $addToGroupId = $field['add_to_group_id'];
761 //build array for captcha
762 if ($field['add_captcha']) {
763 $addCaptcha[$field['group_id']] = $field['add_captcha'];
766 if (($name == 'email-Primary') ||
($name == 'email-' . isset($primaryLocationType) ?
$primaryLocationType : "")) {
767 $emailPresent = TRUE;
768 $this->_mail
= $name;
772 // add captcha only for create mode.
773 if ($this->_mode
== self
::MODE_CREATE
) {
774 // suppress captcha for logged in users only
775 if ($this->_currentUserID
) {
776 $this->_isAddCaptcha
= FALSE;
778 elseif (!$this->_isAddCaptcha
&& !empty($addCaptcha)) {
779 $this->_isAddCaptcha
= TRUE;
783 $dao = new CRM_Core_DAO_UFGroup();
784 $dao->id
= $this->_gid
;
786 $dao->addSelect('is_update_dupe');
787 if ($dao->find(TRUE)) {
788 if ($dao->is_update_dupe
) {
789 $this->_isUpdateDupe
= $dao->is_update_dupe
;
795 $this->_isAddCaptcha
= FALSE;
798 //finally add captcha to form.
799 if ($this->_isAddCaptcha
) {
800 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
801 $captcha->add($this);
803 $this->assign("isCaptcha", $this->_isAddCaptcha
);
805 if ($this->_mode
!= self
::MODE_SEARCH
) {
806 if (isset($addToGroupId)) {
807 $this->_ufGroup
['add_to_group_id'] = $addToGroupId;
811 //let's do set defaults for the profile
812 $this->setDefaultsValues();
814 $action = CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, NULL);
815 if ($this->_mode
== self
::MODE_CREATE
) {
816 CRM_Core_BAO_CMSUser
::buildForm($this, $this->_gid
, $emailPresent, $action);
819 $this->assign('showCMS', FALSE);
822 $this->assign('groupId', $this->_gid
);
824 // if view mode pls freeze it with the done button.
825 if ($this->_action
& CRM_Core_Action
::VIEW
) {
829 if ($this->_context
== 'dialog') {
832 $this->_duplicateButtonName
,
833 ts('Save Matching Contact')
839 * Validate profile and provided activity Id
841 * @param int $activityId
842 * @param int $contactId
847 public 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 ((!empty($profileActivityTypes['Activity']) &&
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
882 * The input form values.
883 * @param array $files
884 * The uploaded files if any.
885 * @param CRM_Core_Form $form
889 * true if no errors, else array of errors
891 public static function formRule($fields, $files, $form) {
892 CRM_Utils_Hook
::validateProfile($form->_ufGroup
['name']);
895 // if no values, return
896 if (empty($fields)) {
902 // hack we use a -1 in options to indicate that its registration
904 $form->_isUpdateDupe
= 1;
907 if ($form->_mode
== CRM_Profile_Form
::MODE_REGISTER
) {
911 // dont check for duplicates during registration validation: CRM-375
912 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
914 if (!empty($fields['email-Primary'])) {
915 $fields['email'] = CRM_Utils_Array
::value('email-Primary', $fields);
919 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
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(
966 'count' => count($contactLinks['rows']),
967 'plural' => '%count matching contacts were found.<br />',
969 if ($contactLinks['msg'] == 'view') {
970 $duplicateContactsLinks .= ts('You can View the existing contact.', array(
971 'count' => count($contactLinks['rows']),
972 'plural' => 'You can View the existing contacts.',
976 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array(
977 'count' => count($contactLinks['rows']),
978 'plural' => 'You can View or Edit the existing contacts.',
981 $duplicateContactsLinks .= '</div>';
982 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
984 for ($i = 0; $i < count($contactLinks['rows']); $i++
) {
986 $row .= ' <td class="matching-contacts-name"> ';
987 $row .= $contactLinks['rows'][$i]['display_name'];
989 $row .= ' <td class="matching-contacts-email"> ';
990 $row .= $contactLinks['rows'][$i]['primary_email'];
992 $row .= ' <td class="action-items"> ';
993 $row .= $contactLinks['rows'][$i]['view'] . ' ';
994 $row .= $contactLinks['rows'][$i]['edit'];
999 $duplicateContactsLinks .= $row . '</table>';
1000 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1002 $errors['_qf_default'] = $duplicateContactsLinks;
1004 // let smarty know that there are duplicates
1005 $template = CRM_Core_Smarty
::singleton();
1006 $template->assign('isDuplicate', 1);
1009 $errors['_qf_default'] = ts('A record already exists with the same information.');
1015 foreach ($fields as $key => $value) {
1016 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System
::explode('-', $key, 3);
1017 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1018 // Validate Country - State list
1019 $countryId = $fields["country-{$locTypeId}"];
1020 $stateProvinceId = $value;
1022 if ($stateProvinceId && $countryId) {
1023 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1024 $stateProvinceDAO->id
= $stateProvinceId;
1025 $stateProvinceDAO->find(TRUE);
1027 if ($stateProvinceDAO->country_id
!= $countryId) {
1028 // country mismatch hence display error
1029 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1030 $countries = CRM_Core_PseudoConstant
::country();
1031 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id
] . ".";
1036 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1037 // Validate County - State list
1038 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1041 if ($countyId && $stateProvinceId) {
1042 $countyDAO = new CRM_Core_DAO_County();
1043 $countyDAO->id
= $countyId;
1044 $countyDAO->find(TRUE);
1046 if ($countyDAO->state_province_id
!= $stateProvinceId) {
1047 // state province mismatch hence display error
1048 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
1049 $counties = CRM_Core_PseudoConstant
::county();
1050 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id
] . ".";
1055 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1056 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1057 $customizedValue = CRM_Core_OptionGroup
::getValue($greeting, 'Customized', 'name');
1058 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1059 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1060 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1066 return empty($errors) ?
TRUE : $errors;
1070 * Process the user submitted custom data values.
1075 public function postProcess() {
1076 $params = $this->controller
->exportValues($this->_name
);
1078 //if the delete record button is clicked
1079 if ($this->_deleteButtonName
) {
1080 if (!empty($_POST[$this->_deleteButtonName
]) && $this->_recordId
) {
1081 $filterParams['id'] = $this->_customGroupId
;
1082 $returnProperties = array('is_multiple', 'table_name');
1083 CRM_Core_DAO
::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1084 if (!empty($returnValues['is_multiple'])) {
1085 if ($tableName = CRM_Utils_Array
::value('table_name', $returnValues)) {
1086 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1088 1 => array($this->_recordId
, 'Integer'),
1089 2 => array($this->_id
, 'Integer'),
1091 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
1092 CRM_Core_Session
::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1098 CRM_Utils_Hook
::processProfile($this->_ufGroup
['name']);
1099 if (!empty($params['image_URL'])) {
1100 CRM_Contact_BAO_Contact
::processImageParams($params);
1103 $greetingTypes = array(
1104 'addressee' => 'addressee_id',
1105 'email_greeting' => 'email_greeting_id',
1106 'postal_greeting' => 'postal_greeting_id',
1111 $contactDetails = CRM_Contact_BAO_Contact
::getHierContactDetails($this->_id
,
1114 $details = $contactDetails[0][$this->_id
];
1116 if (!(!empty($details['addressee_id']) ||
!empty($details['email_greeting_id']) ||
1117 CRM_Utils_Array
::value('postal_greeting_id', $details)
1121 $profileType = CRM_Core_BAO_UFField
::getProfileType($this->_gid
);
1122 //Though Profile type is contact we need
1123 //Individual/Household/Organization for setting Greetings.
1124 if ($profileType == 'Contact') {
1125 $profileType = 'Individual';
1126 //if we editing Household/Organization.
1128 $profileType = CRM_Contact_BAO_Contact
::getContactType($this->_id
);
1131 if (CRM_Contact_BAO_ContactType
::isaSubType($profileType)) {
1132 $profileType = CRM_Contact_BAO_ContactType
::getBasicType($profileType);
1135 foreach ($greetingTypes as $key => $value) {
1136 if (!array_key_exists($key, $params)) {
1137 $params[$key] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($profileType, $key);
1142 $transaction = new CRM_Core_Transaction();
1144 //used to send subscribe mail to the group which user want.
1145 //if the profile double option in is enabled
1146 $mailingType = array();
1149 foreach ($params as $name => $values) {
1150 if (substr($name, 0, 6) == 'email-') {
1151 $result['email'] = $values;
1155 //array of group id, subscribed by contact
1156 $contactGroup = array();
1157 if (!empty($params['group']) &&
1158 CRM_Core_BAO_UFGroup
::isProfileDoubleOptin()
1160 $groupSubscribed = array();
1161 if (!empty($result['email'])) {
1163 $contactGroups = new CRM_Contact_DAO_GroupContact();
1164 $contactGroups->contact_id
= $this->_id
;
1165 $contactGroups->status
= 'Added';
1166 $contactGroups->find();
1167 $contactGroup = array();
1168 while ($contactGroups->fetch()) {
1169 $contactGroup[] = $contactGroups->group_id
;
1170 $groupSubscribed[$contactGroups->group_id
] = 1;
1173 foreach ($params['group'] as $key => $val) {
1175 unset($params['group'][$key]);
1178 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1179 $key, 'group_type', 'id'
1181 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1182 substr($groupTypes, 1, -1)
1184 //filter group of mailing type and unset it from params
1185 if (in_array(2, $groupType)) {
1186 //if group is already subscribed , ignore it
1187 $groupExist = CRM_Utils_Array
::key($key, $contactGroup);
1188 if (!isset($groupExist)) {
1189 $mailingType[] = $key;
1190 unset($params['group'][$key]);
1197 $addToGroupId = CRM_Utils_Array
::value('add_to_group_id', $this->_ufGroup
);
1198 if (!empty($addToGroupId)) {
1199 //run same check whether group is a mailing list
1200 $groupTypes = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
1201 $addToGroupId, 'group_type', 'id'
1203 $groupType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1204 substr($groupTypes, 1, -1)
1206 //filter group of mailing type and unset it from params
1207 if (in_array(2, $groupType) && !empty($result['email']) &&
1208 CRM_Core_BAO_UFGroup
::isProfileAddToGroupDoubleOptin()
1210 if (!count($contactGroup)) {
1211 //array of group id, subscribed by contact
1212 $contactGroup = array();
1214 $contactGroups = new CRM_Contact_DAO_GroupContact();
1215 $contactGroups->contact_id
= $this->_id
;
1216 $contactGroups->status
= 'Added';
1217 $contactGroups->find();
1218 $contactGroup = array();
1219 while ($contactGroups->fetch()) {
1220 $contactGroup[] = $contactGroups->group_id
;
1221 $groupSubscribed[$contactGroups->group_id
] = 1;
1225 //if group is already subscribed , ignore it
1226 $groupExist = CRM_Utils_Array
::key($addToGroupId, $contactGroup);
1227 if (!isset($groupExist)) {
1228 $mailingType[] = $addToGroupId;
1229 $addToGroupId = NULL;
1233 // since we are directly adding contact to group lets unset it from mailing
1234 if ($key = array_search($addToGroupId, $mailingType)) {
1235 unset($mailingType[$key]);
1241 $params['group'] = $groupSubscribed;
1244 // commenting below code, since we potentially
1245 // triggered maximum name field formatting cases during CRM-4430.
1247 // $params['preserveDBName'] = true;
1249 $profileFields = $this->_fields
;
1250 if (($this->_mode
& self
::MODE_EDIT
) && $this->_activityId
&& $this->_isContactActivityProfile
) {
1251 $profileFields = $activityParams = array();
1252 foreach ($this->_fields
as $fieldName => $field) {
1253 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
1254 if (isset($params[$fieldName])) {
1255 $activityParams[$fieldName] = $params[$fieldName];
1257 if (isset($params['activity_date_time'])) {
1258 $activityParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1260 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1261 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1265 $profileFields[$fieldName] = $field;
1269 if (!empty($activityParams)) {
1270 $activityParams['version'] = 3;
1271 $activityParams['id'] = $this->_activityId
;
1272 $activityParams['skipRecentView'] = TRUE;
1273 civicrm_api('Activity', 'create', $activityParams);
1277 if ($this->_multiRecord
&& $this->_recordId
&& $this->_multiRecordFields
&& $this->_recordExists
) {
1278 $params['customRecordValues'][$this->_recordId
] = array_keys($this->_multiRecordFields
);
1281 $this->_id
= CRM_Contact_BAO_Contact
::createProfileContact(
1291 //mailing type group
1292 if (!empty($mailingType)) {
1293 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1295 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($mailingType, $result, $this->_id
, 'profile');
1298 $ufGroups = array();
1300 $ufGroups[$this->_gid
] = 1;
1302 elseif ($this->_mode
== self
::MODE_REGISTER
) {
1303 $ufGroups = CRM_Core_BAO_UFGroup
::getModuleUFGroup('User Registration');
1306 foreach ($ufGroups as $gId => $val) {
1307 if ($notify = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1308 $values = CRM_Core_BAO_UFGroup
::checkFieldsEmptyValues($gId, $this->_id
, NULL);
1309 CRM_Core_BAO_UFGroup
::commonSendMail($this->_id
, $values);
1313 //create CMS user (if CMS user option is selected in profile)
1314 if (!empty($params['cms_create_account']) &&
1315 $this->_mode
== self
::MODE_CREATE
1317 $params['contactID'] = $this->_id
;
1318 if (!CRM_Core_BAO_CMSUser
::create($params, $this->_mail
)) {
1319 CRM_Core_Session
::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1320 CRM_Core_Error
::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1321 $transaction->rollback();
1322 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/profile/create',
1323 'reset=1&gid=' . $this->_gid
1328 $transaction->commit();
1332 * @param null $suffix
1334 * @return null|string
1336 public function checkTemplateFileExists($suffix = NULL) {
1338 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1339 $template = CRM_Core_Form
::getTemplate();
1340 if ($template->template_exists($templateFile)) {
1341 return $templateFile;
1344 // lets see if we have customized by name
1345 $ufGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid
, 'name');
1347 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1348 if ($template->template_exists($templateFile)) {
1349 return $templateFile;
1357 * Use the form name to create the tpl file name
1364 public function getTemplateFileName() {
1365 $fileName = $this->checkTemplateFileExists();
1366 return $fileName ?
$fileName : parent
::getTemplateFileName();
1370 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1371 * i.e. we dont override
1378 public function overrideExtraTemplateFileName() {
1379 $fileName = $this->checkTemplateFileExists('extra.');
1380 return $fileName ?
$fileName : parent
::overrideExtraTemplateFileName();