Merge pull request #19067 from eileenmcnaughton/weight
[civicrm-core.git] / CRM / Member / Form / Membership.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for offline membership form.
20 */
21 class CRM_Member_Form_Membership extends CRM_Member_Form {
22
23 protected $_memType = NULL;
24
25 public $_mode;
26
27 public $_contributeMode = 'direct';
28
29 protected $_recurMembershipTypes;
30
31 protected $_memTypeSelected;
32
33 /**
34 * Display name of the member.
35 *
36 * @var string
37 */
38 protected $_memberDisplayName = NULL;
39
40 /**
41 * email of the person paying for the membership (used for receipts)
42 * @var string
43 */
44 protected $_memberEmail = NULL;
45
46 /**
47 * Contact ID of the member.
48 *
49 * @var int
50 */
51 public $_contactID = NULL;
52
53 /**
54 * Display name of the person paying for the membership (used for receipts)
55 *
56 * @var string
57 */
58 protected $_contributorDisplayName = NULL;
59
60 /**
61 * Email of the person paying for the membership (used for receipts).
62 *
63 * @var string
64 */
65 protected $_contributorEmail;
66
67 /**
68 * email of the person paying for the membership (used for receipts)
69 *
70 * @var int
71 */
72 protected $_contributorContactID = NULL;
73
74 /**
75 * ID of the person the receipt is to go to.
76 *
77 * @var int
78 */
79 protected $_receiptContactId = NULL;
80
81 /**
82 * Keep a class variable for ALL membership IDs so
83 * postProcess hook function can do something with it
84 *
85 * @var array
86 */
87 protected $_membershipIDs = [];
88
89 /**
90 * Set entity fields to be assigned to the form.
91 */
92 protected function setEntityFields() {
93 $this->entityFields = [
94 'join_date' => [
95 'name' => 'join_date',
96 'description' => ts('Member Since'),
97 ],
98 'start_date' => [
99 'name' => 'start_date',
100 'description' => ts('Start Date'),
101 ],
102 'end_date' => [
103 'name' => 'end_date',
104 'description' => ts('End Date'),
105 ],
106 ];
107 }
108
109 /**
110 * Set the delete message.
111 *
112 * We do this from the constructor in order to do a translation.
113 */
114 public function setDeleteMessage() {
115 $this->deleteMessage = '<span class="font-red bold">'
116 . ts('WARNING: Deleting this membership will also delete any related payment (contribution) records.' . ts('This action cannot be undone.')
117 . '</span><p>'
118 . ts('Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.')
119 . '</p><p>'
120 . ts("Click 'Delete' if you want to continue.") . '</p>');
121 }
122
123 /**
124 * Overriding this entity trait function as not yet tested.
125 *
126 * We continue to rely on legacy handling.
127 */
128 public function addCustomDataToForm() {}
129
130 /**
131 * Overriding this entity trait function as not yet tested.
132 *
133 * We continue to rely on legacy handling.
134 */
135 public function addFormButtons() {}
136
137 /**
138 * Get selected membership type from the form values.
139 *
140 * @param array $priceSet
141 * @param array $params
142 *
143 * @return array
144 * @throws \CRM_Core_Exception
145 */
146 public static function getSelectedMemberships($priceSet, $params) {
147 $memTypeSelected = [];
148 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
149 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
150 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
151 }
152 else {
153 foreach ($priceFieldIDS as $priceFieldId) {
154 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
155 $memTypeSelected[$id] = $id;
156 }
157 }
158 }
159 return $memTypeSelected;
160 }
161
162 /**
163 * Extract price set fields and values from $params.
164 *
165 * @param array $params
166 * @param array $priceSet
167 *
168 * @return array
169 */
170 public static function getPriceFieldIDs($params, $priceSet) {
171 $priceFieldIDS = [];
172 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
173 foreach ($priceSet['fields'] as $fieldId => $field) {
174 if (!empty($params['price_' . $fieldId])) {
175 if (is_array($params['price_' . $fieldId])) {
176 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
177 if ($isSet) {
178 $priceFieldIDS[] = $priceFldVal;
179 }
180 }
181 }
182 elseif (!$field['is_enter_qty']) {
183 $priceFieldIDS[] = $params['price_' . $fieldId];
184 }
185 }
186 }
187 }
188 return $priceFieldIDS;
189 }
190
191 /**
192 * Form preProcess function.
193 *
194 * @throws \CRM_Core_Exception
195 * @throws \CiviCRM_API3_Exception
196 */
197 public function preProcess() {
198 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
199 $this->assign('formClass', 'membership');
200 parent::preProcess();
201
202 // get price set id.
203 $this->_priceSetId = $_GET['priceSetId'] ?? NULL;
204 $this->set('priceSetId', $this->_priceSetId);
205 $this->assign('priceSetId', $this->_priceSetId);
206
207 if ($this->_action & CRM_Core_Action::DELETE) {
208 $contributionID = CRM_Member_BAO_Membership::getMembershipContributionId($this->_id);
209 // check delete permission for contribution
210 if ($this->_id && $contributionID && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
211 CRM_Core_Error::statusBounce(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
212 }
213 }
214
215 if ($this->_action & CRM_Core_Action::ADD) {
216 if ($this->_contactID) {
217 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
218 $contactMemberships = [];
219 $memParams = ['contact_id' => $this->_contactID];
220 CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
221 $cMemTypes = [];
222 foreach ($contactMemberships as $mem) {
223 $cMemTypes[] = $mem['membership_type_id'];
224 }
225 if (count($cMemTypes) > 0) {
226 foreach ($cMemTypes as $memTypeID) {
227 $memberorgs[$memTypeID] = CRM_Member_BAO_MembershipType::getMembershipType($memTypeID)['member_of_contact_id'];
228 }
229 $mems_by_org = [];
230 foreach ($contactMemberships as $mem) {
231 $mem['member_of_contact_id'] = $memberorgs[$mem['membership_type_id']] ?? NULL;
232 if (!empty($mem['membership_end_date'])) {
233 $mem['membership_end_date'] = CRM_Utils_Date::customFormat($mem['membership_end_date']);
234 }
235 $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
236 $mem['membership_type_id'],
237 'name', 'id'
238 );
239 $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
240 $mem['status_id'],
241 'label', 'id'
242 );
243 $mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
244 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
245 . ($this->_mode ? '&mode=live' : '')
246 );
247 $mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view',
248 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
249 );
250 $mems_by_org[$mem['member_of_contact_id']] = $mem;
251 }
252 $this->assign('existingContactMemberships', $mems_by_org);
253 }
254 }
255 else {
256 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
257 $resources = CRM_Core_Resources::singleton();
258 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
259 $passthru = [
260 'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
261 'memtypes' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'membership_type_id'),
262 'statuses' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'status_id'),
263 ];
264 $resources->addSetting(['existingMems' => $passthru]);
265 }
266 }
267
268 if (!$this->_memType) {
269 $params = CRM_Utils_Request::exportValues();
270 if (!empty($params['membership_type_id'][1])) {
271 $this->_memType = $params['membership_type_id'][1];
272 }
273 }
274
275 // Add custom data to form
276 CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
277 $this->setPageTitle(ts('Membership'));
278 }
279
280 /**
281 * Set default values for the form.
282 */
283 public function setDefaultValues() {
284
285 if ($this->_priceSetId) {
286 return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
287 }
288
289 $defaults = parent::setDefaultValues();
290
291 //setting default join date and receive date
292 if ($this->_action == CRM_Core_Action::ADD) {
293 $defaults['receive_date'] = date('Y-m-d H:i:s');
294 }
295
296 $defaults['num_terms'] = 1;
297
298 if (!empty($defaults['id'])) {
299 $contributionId = CRM_Core_DAO::singleValueQuery("
300 SELECT contribution_id
301 FROM civicrm_membership_payment
302 WHERE membership_id = $this->_id
303 ORDER BY contribution_id
304 DESC limit 1");
305
306 if ($contributionId) {
307 $defaults['record_contribution'] = $contributionId;
308 }
309 }
310 else {
311 if ($this->_contactID) {
312 $defaults['contact_id'] = $this->_contactID;
313 }
314 }
315
316 //set Soft Credit Type to Gift by default
317 $scTypes = CRM_Core_OptionGroup::values('soft_credit_type');
318 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
319
320 //CRM-13420
321 if (empty($defaults['payment_instrument_id'])) {
322 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
323 }
324
325 // User must explicitly choose to send a receipt in both add and update mode.
326 $defaults['send_receipt'] = 0;
327
328 if ($this->_action & CRM_Core_Action::UPDATE) {
329 // in this mode by default uncheck this checkbox
330 unset($defaults['record_contribution']);
331 }
332
333 $subscriptionCancelled = FALSE;
334 if (!empty($defaults['id'])) {
335 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
336 }
337
338 $alreadyAutoRenew = FALSE;
339 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
340 $defaults['auto_renew'] = 1;
341 $alreadyAutoRenew = TRUE;
342 }
343 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
344
345 $this->assign('member_is_test', $defaults['member_is_test'] ?? NULL);
346 $this->assign('membership_status_id', $defaults['status_id'] ?? NULL);
347 $this->assign('is_pay_later', !empty($defaults['is_pay_later']));
348
349 if ($this->_mode) {
350 $defaults = $this->getBillingDefaults($defaults);
351 }
352
353 //setting default join date if there is no join date
354 if (empty($defaults['join_date'])) {
355 $defaults['join_date'] = date('Y-m-d');
356 }
357
358 if (!empty($defaults['membership_end_date'])) {
359 $this->assign('endDate', $defaults['membership_end_date']);
360 }
361
362 return $defaults;
363 }
364
365 /**
366 * Build the form object.
367 *
368 * @throws \CRM_Core_Exception
369 */
370 public function buildQuickForm() {
371
372 $this->buildQuickEntityForm();
373 $this->assign('currency_symbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
374 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
375 // build price set form.
376 $buildPriceSet = FALSE;
377 if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
378 if (!empty($_POST['price_set_id'])) {
379 $buildPriceSet = TRUE;
380 }
381 $getOnlyPriceSetElements = TRUE;
382 if (!$this->_priceSetId) {
383 $this->_priceSetId = $_POST['price_set_id'];
384 $getOnlyPriceSetElements = FALSE;
385 }
386
387 $this->set('priceSetId', $this->_priceSetId);
388 CRM_Price_BAO_PriceSet::buildPriceSet($this);
389
390 $optionsMembershipTypes = [];
391 foreach ($this->_priceSet['fields'] as $pField) {
392 if (empty($pField['options'])) {
393 continue;
394 }
395 foreach ($pField['options'] as $opId => $opValues) {
396 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
397 }
398 }
399
400 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
401
402 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
403 $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
404
405 // get only price set form elements.
406 if ($getOnlyPriceSetElements) {
407 return;
408 }
409 }
410
411 // use to build form during form rule.
412 $this->assign('buildPriceSet', $buildPriceSet);
413
414 if ($this->_action & CRM_Core_Action::ADD) {
415 $buildPriceSet = FALSE;
416 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
417 if (!empty($priceSets)) {
418 $buildPriceSet = TRUE;
419 }
420
421 if ($buildPriceSet) {
422 $this->add('select', 'price_set_id', ts('Choose price set'),
423 [
424 '' => ts('Choose price set'),
425 ] + $priceSets,
426 NULL, ['onchange' => "buildAmount( this.value );"]
427 );
428 }
429 $this->assign('hasPriceSets', $buildPriceSet);
430 }
431
432 if ($this->_action & CRM_Core_Action::DELETE) {
433 $this->addButtons([
434 [
435 'type' => 'next',
436 'name' => ts('Delete'),
437 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
438 'isDefault' => TRUE,
439 ],
440 [
441 'type' => 'cancel',
442 'name' => ts('Cancel'),
443 ],
444 ]);
445 return;
446 }
447
448 $contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
449 if ($this->_context !== 'standalone') {
450 $contactField->freeze();
451 }
452
453 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
454
455 // Throw status bounce when no Membership type or priceset is present
456 if (empty($this->allMembershipTypeDetails) && empty($priceSets)
457 ) {
458 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
459 }
460 // retrieve all memberships
461 $allMembershipInfo = [];
462 foreach ($this->allMembershipTypeDetails as $key => $values) {
463 if ($this->_mode && empty($values['minimum_fee'])) {
464 continue;
465 }
466 else {
467 $memberOfContactId = $values['member_of_contact_id'] ?? NULL;
468 if (empty($selMemTypeOrg[$memberOfContactId])) {
469 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
470 $memberOfContactId,
471 'display_name',
472 'id'
473 );
474
475 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
476 }
477 if (empty($selOrgMemType[$memberOfContactId][$key])) {
478 $selOrgMemType[$memberOfContactId][$key] = $values['name'] ?? NULL;
479 }
480 }
481 $totalAmount = $values['minimum_fee'] ?? NULL;
482 //CRM-18827 - override the default value if total_amount is submitted
483 if (!empty($this->_submitValues['total_amount'])) {
484 $totalAmount = CRM_Utils_Rule::cleanMoney($this->_submitValues['total_amount']);
485 }
486 // build membership info array, which is used when membership type is selected to:
487 // - set the payment information block
488 // - set the max related block
489 $allMembershipInfo[$key] = [
490 'financial_type_id' => $values['financial_type_id'] ?? NULL,
491 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
492 'total_amount_numeric' => $totalAmount,
493 'auto_renew' => $values['auto_renew'] ?? NULL,
494 'has_related' => isset($values['relationship_type_id']),
495 'max_related' => $values['max_related'] ?? NULL,
496 ];
497 }
498
499 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
500
501 // show organization by default, if only one organization in
502 // the list
503 if (count($selMemTypeOrg) == 2) {
504 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
505 }
506 //sort membership organization and type, CRM-6099
507 natcasesort($selMemTypeOrg);
508 foreach ($selOrgMemType as $index => $orgMembershipType) {
509 natcasesort($orgMembershipType);
510 $selOrgMemType[$index] = $orgMembershipType;
511 }
512
513 $memTypeJs = [
514 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
515 ];
516
517 if (!empty($this->_recurPaymentProcessors)) {
518 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
519 }
520
521 $this->add('text', 'max_related', ts('Max related'),
522 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
523 );
524
525 $sel = &$this->addElement('hierselect',
526 'membership_type_id',
527 ts('Membership Organization and Type'),
528 $memTypeJs
529 );
530
531 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
532
533 if ($this->_action & CRM_Core_Action::ADD) {
534 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
535 }
536
537 $this->add('text', 'source', ts('Source'),
538 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
539 );
540
541 //CRM-7362 --add campaigns.
542 $campaignId = NULL;
543 if ($this->_id) {
544 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
545 }
546 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
547
548 if (!$this->_mode) {
549 $this->add('select', 'status_id', ts('Membership Status'),
550 ['' => ts('- select -')] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
551 );
552
553 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
554 CRM_Member_StatusOverrideTypes::getSelectOptions()
555 );
556
557 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => date('Y-m-d'), 'time' => FALSE]);
558
559 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
560
561 $this->add('text', 'total_amount', ts('Amount'));
562 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
563
564 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
565
566 $this->add('select', 'payment_instrument_id',
567 ts('Payment Method'),
568 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
569 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
570 );
571 $this->add('text', 'trxn_id', ts('Transaction ID'));
572 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
573 'objectExists', [
574 'CRM_Contribute_DAO_Contribution',
575 $this->_id,
576 'trxn_id',
577 ]
578 );
579
580 $this->add('select', 'contribution_status_id',
581 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('membership')
582 );
583 $this->add('text', 'check_number', ts('Check Number'),
584 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
585 );
586 }
587 else {
588 //add field for amount to allow an amount to be entered that differs from minimum
589 $this->add('text', 'total_amount', ts('Amount'));
590 }
591 $this->add('select', 'financial_type_id',
592 ts('Financial Type'),
593 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
594 );
595
596 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
597
598 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
599 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
600
601 $this->addElement('checkbox',
602 'send_receipt',
603 ts('Send Confirmation and Receipt?'), NULL,
604 ['onclick' => "showEmailOptions()"]
605 );
606
607 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
608
609 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
610
611 // Retrieve the name and email of the contact - this will be the TO for receipt email
612 if ($this->_contactID) {
613 list($this->_memberDisplayName,
614 $this->_memberEmail
615 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
616
617 $this->assign('emailExists', $this->_memberEmail);
618 $this->assign('displayName', $this->_memberDisplayName);
619 }
620
621 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
622 $this->assign('cancelAutoRenew',
623 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
624 );
625 }
626
627 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
628
629 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
630 $mailingInfo = Civi::settings()->get('mailing_backend');
631 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
632
633 parent::buildQuickForm();
634 }
635
636 /**
637 * Validation.
638 *
639 * @param array $params
640 * (ref.) an assoc array of name/value pairs.
641 *
642 * @param array $files
643 * @param CRM_Member_Form_Membership $self
644 *
645 * @return bool|array
646 * mixed true or array of errors
647 *
648 * @throws \CRM_Core_Exception
649 * @throws CiviCRM_API3_Exception
650 */
651 public static function formRule($params, $files, $self) {
652 $errors = [];
653
654 $priceSetId = self::getPriceSetID($params);
655 $priceSetDetails = self::getPriceSetDetails($params);
656
657 $selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
658
659 if (!empty($params['price_set_id'])) {
660 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
661
662 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
663
664 if (!empty($priceFieldIDS)) {
665 $ids = implode(',', $priceFieldIDS);
666
667 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
668 foreach ($count as $occurrence) {
669 if ($occurrence > 1) {
670 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
671 }
672 }
673 }
674 // Return error if empty $self->_memTypeSelected
675 if (empty($errors) && empty($selectedMemberships)) {
676 $errors['_qf_default'] = ts('Select at least one membership option.');
677 }
678 if (!$self->_mode && empty($params['record_contribution'])) {
679 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
680 }
681 }
682 else {
683 if (empty($params['membership_type_id'][1])) {
684 $errors['membership_type_id'] = ts('Please select a membership type.');
685 }
686 $numterms = $params['num_terms'] ?? NULL;
687 if ($numterms && intval($numterms) != $numterms) {
688 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
689 }
690
691 if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
692 $errors['financial_type_id'] = ts('Please enter the financial Type.');
693 }
694 }
695
696 if (!empty($errors) && (count($selectedMemberships) > 1)) {
697 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
698 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
699 foreach ($duplicateMemberOfContacts as $countDuplicate) {
700 if ($countDuplicate > 1) {
701 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
702 }
703 }
704 }
705
706 if (!empty($errors)) {
707 return $errors;
708 }
709
710 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
711 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
712 }
713
714 if (!empty($params['is_different_contribution_contact'])) {
715 if (empty($params['soft_credit_type_id'])) {
716 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
717 }
718 if (empty($params['soft_credit_contact_id'])) {
719 $errors['soft_credit_contact_id'] = ts('Please select a contact');
720 }
721 }
722
723 if (!empty($params['payment_processor_id'])) {
724 // validate payment instrument (e.g. credit card number)
725 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
726 }
727
728 $joinDate = NULL;
729 if (!empty($params['join_date'])) {
730
731 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
732
733 foreach ($selectedMemberships as $memType) {
734 $startDate = NULL;
735 if (!empty($params['start_date'])) {
736 $startDate = CRM_Utils_Date::processDate($params['start_date']);
737 }
738
739 // if end date is set, ensure that start date is also set
740 // and that end date is later than start date
741 $endDate = NULL;
742 if (!empty($params['end_date'])) {
743 $endDate = CRM_Utils_Date::processDate($params['end_date']);
744 }
745
746 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipType($memType);
747 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) === 'rolling') {
748 if ($startDate < $joinDate) {
749 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
750 }
751 }
752
753 if ($endDate) {
754 if ($membershipDetails['duration_unit'] === 'lifetime') {
755 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
756 // process to update status based on end-date. The user must change the status now.
757 $result = civicrm_api3('MembershipStatus', 'get', [
758 'sequential' => 1,
759 'is_current_member' => 0,
760 ]);
761 $tmp_statuses = $result['values'];
762 $status_ids = [];
763 foreach ($tmp_statuses as $cur_stat) {
764 $status_ids[] = $cur_stat['id'];
765 }
766
767 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
768 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
769 }
770
771 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
772 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
773 }
774 }
775 else {
776 if (!$startDate) {
777 $errors['start_date'] = ts('Start date must be set if end date is set.');
778 }
779 if ($endDate < $startDate) {
780 $errors['end_date'] = ts('End date must be the same or later than start date.');
781 }
782 }
783 }
784
785 // Default values for start and end dates if not supplied on the form.
786 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
787 $joinDate,
788 $startDate,
789 $endDate
790 );
791
792 if (!$startDate) {
793 $startDate = CRM_Utils_Array::value('start_date',
794 $defaultDates
795 );
796 }
797 if (!$endDate) {
798 $endDate = CRM_Utils_Array::value('end_date',
799 $defaultDates
800 );
801 }
802
803 //CRM-3724, check for availability of valid membership status.
804 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
805 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
806 $endDate,
807 $joinDate,
808 'now',
809 TRUE,
810 $memType,
811 $params
812 );
813 if (empty($calcStatus)) {
814 $url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
815 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
816 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', [1 => $url]);
817 if (!$self->_mode) {
818 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
819 }
820 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
821 }
822 }
823 }
824 }
825 else {
826 $errors['join_date'] = ts('Please enter the Member Since.');
827 }
828
829 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
830 $errors['status_id'] = ts('Please enter the Membership status.');
831 }
832
833 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
834 if (empty($params['status_override_end_date'])) {
835 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
836 }
837 }
838
839 //total amount condition arise when membership type having no
840 //minimum fee
841 if (isset($params['record_contribution'])) {
842 if (CRM_Utils_System::isNull($params['total_amount'])) {
843 $errors['total_amount'] = ts('Please enter the contribution.');
844 }
845 }
846
847 return empty($errors) ? TRUE : $errors;
848 }
849
850 /**
851 * Process the form submission.
852 *
853 * @throws \CRM_Core_Exception
854 * @throws \CiviCRM_API3_Exception
855 */
856 public function postProcess() {
857 if ($this->_action & CRM_Core_Action::DELETE) {
858 CRM_Member_BAO_Membership::del($this->_id);
859 return;
860 }
861 // get the submitted form values.
862 $this->_params = $this->controller->exportValues($this->_name);
863 $this->prepareStatusOverrideValues();
864
865 $this->submit();
866
867 $this->setUserContext();
868 }
869
870 /**
871 * Prepares the values related to status override.
872 */
873 private function prepareStatusOverrideValues() {
874 $this->setOverrideDateValue();
875 $this->convertIsOverrideValue();
876 }
877
878 /**
879 * Sets status override end date to empty value if
880 * the selected override option is not 'until date'.
881 */
882 private function setOverrideDateValue() {
883 if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
884 $this->_params['status_override_end_date'] = '';
885 }
886 }
887
888 /**
889 * Convert the value of selected (status override?)
890 * option to TRUE if it indicate an overridden status
891 * or FALSE otherwise.
892 */
893 private function convertIsOverrideValue() {
894 $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override'] ?? CRM_Member_StatusOverrideTypes::NO);
895 }
896
897 /**
898 * Send email receipt.
899 *
900 * @param CRM_Core_Form $form
901 * Form object.
902 * @param array $formValues
903 * @param object $membership
904 * Object.
905 * @param array $customValues
906 *
907 * @return bool
908 * true if mail was sent successfully
909 * @throws \CRM_Core_Exception
910 *
911 * @deprecated
912 * This function is shared with Batch_Entry which has limited overlap
913 * & needs rationalising.
914 *
915 */
916 public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
917 // retrieve 'from email id' for acknowledgement
918 $receiptFrom = $formValues['from_email_address'] ?? NULL;
919
920 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
921 if (!empty($formValues['payment_instrument_id'])) {
922 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
923 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
924 }
925
926 $form->assign('customValues', $customValues);
927
928 if ($form->_mode) {
929 // @todo move this outside shared code as Batch entry just doesn't
930 $form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
931 $form->_params,
932 $form->_bltID
933 ));
934
935 $valuesForForm = CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($form->_params);
936 $form->assignVariables($valuesForForm, ['credit_card_exp_date', 'credit_card_type', 'credit_card_number']);
937
938 $form->assign('contributeMode', 'direct');
939 $form->assign('isAmountzero', 0);
940 $form->assign('is_pay_later', 0);
941 $form->assign('isPrimary', 1);
942 }
943
944 $form->assign('module', 'Membership');
945 $form->assign('contactID', $formValues['contact_id']);
946
947 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
948
949 if (!empty($formValues['contribution_id'])) {
950 $form->assign('contributionID', $formValues['contribution_id']);
951 }
952
953 if (!empty($formValues['contribution_status_id'])) {
954 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
955 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
956 }
957
958 if (!empty($formValues['is_renew'])) {
959 $form->assign('receiptType', 'membership renewal');
960 }
961 else {
962 $form->assign('receiptType', 'membership signup');
963 }
964 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
965 $form->assign('formValues', $formValues);
966
967 if (empty($lineItem)) {
968 $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date));
969 if (!CRM_Utils_System::isNull($membership->end_date)) {
970 $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date));
971 }
972 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
973 }
974
975 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
976 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
977 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
978 // in this case the form is being called statically from the batch editing screen
979 // having one class in the form layer call another statically is not greate
980 // & we should aim to move this function to the BAO layer in future.
981 // however, we can assume that the contact_id passed in by the batch
982 // function will be the recipient
983 list($form->_contributorDisplayName, $form->_contributorEmail)
984 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
985 if (empty($form->_receiptContactId) || $isBatchProcess) {
986 $form->_receiptContactId = $formValues['contact_id'];
987 }
988 }
989 // @todo determine isEmailPdf in calling function.
990 $template = CRM_Core_Smarty::singleton();
991 $taxAmt = $template->get_template_vars('dataArray');
992 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
993 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
994 $invoicing = $prefixValue['invoicing'] ?? NULL;
995 if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
996 $isEmailPdf = TRUE;
997 }
998 else {
999 $isEmailPdf = FALSE;
1000 }
1001
1002 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1003 [
1004 'groupName' => 'msg_tpl_workflow_membership',
1005 'valueName' => 'membership_offline_receipt',
1006 'contactId' => $form->_receiptContactId,
1007 'from' => $receiptFrom,
1008 'toName' => $form->_contributorDisplayName,
1009 'toEmail' => $form->_contributorEmail,
1010 'PDFFilename' => ts('receipt') . '.pdf',
1011 'isEmailPdf' => $isEmailPdf,
1012 'contributionId' => $formValues['contribution_id'],
1013 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
1014 ]
1015 );
1016
1017 return TRUE;
1018 }
1019
1020 /**
1021 * Submit function.
1022 *
1023 * This is also accessed by unit tests.
1024 *
1025 * @throws \CRM_Core_Exception
1026 * @throws \CiviCRM_API3_Exception
1027 */
1028 public function submit() {
1029 $isTest = ($this->_mode === 'test') ? 1 : 0;
1030 $this->storeContactFields($this->_params);
1031 $this->beginPostProcess();
1032 $endDate = NULL;
1033 $membershipTypes = $membership = $calcDate = [];
1034 $membershipType = NULL;
1035 $paymentInstrumentID = $this->_paymentProcessor['object']->getPaymentInstrumentID();
1036 $params = $softParams = $ids = [];
1037
1038 $mailSend = FALSE;
1039 $this->processBillingAddress();
1040 $formValues = $this->_params;
1041 $formValues = $this->setPriceSetParameters($formValues);
1042
1043 if ($this->_id) {
1044 $ids['membership'] = $params['id'] = $this->_id;
1045 }
1046
1047 // Set variables that we normally get from context.
1048 // In form mode these are set in preProcess.
1049 //TODO: set memberships, fixme
1050 $this->setContextVariables($formValues);
1051
1052 $this->_memTypeSelected = self::getSelectedMemberships(
1053 $this->_priceSet,
1054 $formValues
1055 );
1056 if (empty($formValues['financial_type_id'])) {
1057 $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
1058 }
1059
1060 $membershipTypeValues = [];
1061 foreach ($this->_memTypeSelected as $memType) {
1062 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1063 }
1064
1065 //take the required membership recur values.
1066 if ($this->_mode && !empty($formValues['auto_renew'])) {
1067 $params['is_recur'] = $formValues['is_recur'] = TRUE;
1068
1069 $count = 0;
1070 foreach ($this->_memTypeSelected as $memType) {
1071 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
1072 $this->allMembershipTypeDetails, []
1073 );
1074 if (!$recurMembershipTypeValues['auto_renew']) {
1075 continue;
1076 }
1077 foreach ([
1078 'frequency_interval' => 'duration_interval',
1079 'frequency_unit' => 'duration_unit',
1080 ] as $mapVal => $mapParam) {
1081 $membershipTypeValues[$memType][$mapVal] = $recurMembershipTypeValues[$mapParam];
1082
1083 if (!$count) {
1084 $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
1085 $recurMembershipTypeValues
1086 );
1087 }
1088 }
1089 $count++;
1090 }
1091 }
1092
1093 $isQuickConfig = $this->_priceSet['is_quick_config'];
1094
1095 $termsByType = [];
1096
1097 $lineItem = [$this->_priceSetId => []];
1098
1099 // BEGIN Fix for dev/core/issues/860
1100 // Prepare fee block and call buildAmount hook - based on CRM_Price_BAO_PriceSet::buildPriceSet().
1101 CRM_Utils_Hook::buildAmount('membership', $this, $this->_priceSet['fields']);
1102 // END Fix for dev/core/issues/860
1103
1104 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1105 $formValues, $lineItem[$this->_priceSetId], $this->_priceSetId);
1106
1107 if (!empty($formValues['tax_amount'])) {
1108 $params['tax_amount'] = $formValues['tax_amount'];
1109 }
1110 $params['total_amount'] = $formValues['amount'] ?? NULL;
1111 if (!empty($lineItem[$this->_priceSetId])) {
1112 foreach ($lineItem[$this->_priceSetId] as &$li) {
1113 if (!empty($li['membership_type_id'])) {
1114 if (!empty($li['membership_num_terms'])) {
1115 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1116 }
1117 }
1118
1119 ///CRM-11529 for quick config backoffice transactions
1120 //when financial_type_id is passed in form, update the
1121 //lineitems with the financial type selected in form
1122 $submittedFinancialType = $formValues['financial_type_id'] ?? NULL;
1123 if ($isQuickConfig && $submittedFinancialType) {
1124 $li['financial_type_id'] = $submittedFinancialType;
1125 }
1126 }
1127 }
1128
1129 $params['contact_id'] = $this->_contactID;
1130
1131 $fields = [
1132 'status_id',
1133 'source',
1134 'is_override',
1135 'status_override_end_date',
1136 'campaign_id',
1137 ];
1138
1139 foreach ($fields as $f) {
1140 $params[$f] = $formValues[$f] ?? NULL;
1141 }
1142
1143 // fix for CRM-3724
1144 // when is_override false ignore is_admin statuses during membership
1145 // status calculation. similarly we did fix for import in CRM-3570.
1146 if (empty($params['is_override'])) {
1147 $params['exclude_is_admin'] = TRUE;
1148 }
1149
1150 $joinDate = $formValues['join_date'];
1151 $startDate = $formValues['start_date'];
1152 $endDate = $formValues['end_date'];
1153
1154 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
1155
1156 $calcDates = [];
1157 foreach ($this->_memTypeSelected as $memType) {
1158 if (empty($memTypeNumTerms)) {
1159 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1160 }
1161 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1162 $joinDate, $startDate, $endDate, $memTypeNumTerms
1163 );
1164 }
1165
1166 foreach ($calcDates as $memType => $calcDate) {
1167 foreach (['join_date', 'start_date', 'end_date'] as $d) {
1168 //first give priority to form values then calDates.
1169 $date = $formValues[$d] ?? NULL;
1170 if (!$date) {
1171 $date = $calcDate[$d] ?? NULL;
1172 }
1173
1174 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
1175 }
1176 }
1177
1178 foreach ($this->_memTypeSelected as $memType) {
1179 if (array_key_exists('max_related', $formValues)) {
1180 // max related memberships - take from form or inherit from membership type
1181 $membershipTypeValues[$memType]['max_related'] = $formValues['max_related'] ?? NULL;
1182 }
1183 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
1184 $this->_id,
1185 'Membership'
1186 );
1187 $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1188 $memType
1189 );
1190 }
1191
1192 $membershipType = implode(', ', $membershipTypes);
1193
1194 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1195 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::getLoggedInContactID());
1196
1197 //CRM-13981, allow different person as a soft-contributor of chosen type
1198 if ($this->_contributorContactID != $this->_contactID) {
1199 $params['contribution_contact_id'] = $this->_contributorContactID;
1200 if (!empty($formValues['soft_credit_type_id'])) {
1201 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1202 $softParams['contact_id'] = $this->_contactID;
1203 }
1204 }
1205
1206 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1207
1208 if (!empty($formValues['record_contribution'])) {
1209 $recordContribution = [
1210 'total_amount',
1211 'financial_type_id',
1212 'payment_instrument_id',
1213 'trxn_id',
1214 'contribution_status_id',
1215 'check_number',
1216 'campaign_id',
1217 'receive_date',
1218 'card_type_id',
1219 'pan_truncation',
1220 ];
1221
1222 foreach ($recordContribution as $f) {
1223 $params[$f] = $formValues[$f] ?? NULL;
1224 }
1225
1226 if (empty($formValues['source'])) {
1227 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1228 1 => $membershipType,
1229 2 => $userName,
1230 ]);
1231 }
1232 else {
1233 $params['contribution_source'] = $formValues['source'];
1234 }
1235
1236 $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1237 if (empty($params['is_override']) &&
1238 CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
1239 ) {
1240 $params['status_id'] = $pendingMembershipStatusId;
1241 $params['skipStatusCal'] = TRUE;
1242 $params['is_pay_later'] = 1;
1243 $this->assign('is_pay_later', 1);
1244 }
1245
1246 if (!empty($formValues['send_receipt'])) {
1247 $params['receipt_date'] = $formValues['receive_date'] ?? NULL;
1248 }
1249
1250 //insert financial type name in receipt.
1251 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1252 $formValues['financial_type_id']
1253 );
1254 }
1255
1256 // process line items, until no previous line items.
1257 if (!empty($lineItem)) {
1258 $params['lineItems'] = $lineItem;
1259 $params['processPriceSet'] = TRUE;
1260 }
1261 $createdMemberships = [];
1262 if ($this->_mode) {
1263 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
1264
1265 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1266 $params['card_type_id'] = $this->_params['card_type_id'] ?? NULL;
1267 $params['pan_truncation'] = $this->_params['pan_truncation'] ?? NULL;
1268
1269 if (!$isQuickConfig) {
1270 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
1271 $this->_priceSetId,
1272 'financial_type_id'
1273 );
1274 }
1275 else {
1276 $params['financial_type_id'] = $formValues['financial_type_id'] ?? NULL;
1277 }
1278
1279 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1280 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1281 $params['register_date'] = date('YmdHis');
1282
1283 // add all the additional payment params we need
1284 $formValues['amount'] = $params['total_amount'];
1285 // @todo this is a candidate for beginPostProcessFunction.
1286 $formValues['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
1287 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1288 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1289 $formValues['financial_type_id'] = $params['financial_type_id'];
1290
1291 // at this point we've created a contact and stored its address etc
1292 // all the payment processors expect the name and address to be in the
1293 // so we copy stuff over to first_name etc.
1294 $paymentParams = $formValues;
1295 $paymentParams['contactID'] = $this->_contributorContactID;
1296 //CRM-10377 if payment is by an alternate contact then we need to set that person
1297 // as the contact in the payment params
1298 if ($this->_contributorContactID != $this->_contactID) {
1299 if (!empty($formValues['soft_credit_type_id'])) {
1300 $softParams['contact_id'] = $params['contact_id'];
1301 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1302 }
1303 }
1304 if (!empty($formValues['send_receipt'])) {
1305 $paymentParams['email'] = $this->_contributorEmail;
1306 }
1307
1308 // This is a candidate for shared beginPostProcess function.
1309 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1310 CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
1311 // CRM-7137 -for recurring membership,
1312 // we do need contribution and recurring records.
1313 $result = NULL;
1314 if (!empty($paymentParams['is_recur'])) {
1315 $financialType = new CRM_Financial_DAO_FinancialType();
1316 $financialType->id = $params['financial_type_id'];
1317 $financialType->find(TRUE);
1318 $this->_params = $formValues;
1319
1320 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1321 $paymentParams,
1322 NULL,
1323 [
1324 'contact_id' => $this->_contributorContactID,
1325 'line_item' => $lineItem,
1326 'is_test' => $isTest,
1327 'campaign_id' => $paymentParams['campaign_id'] ?? NULL,
1328 'contribution_page_id' => $formValues['contribution_page_id'] ?? NULL,
1329 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1330 'thankyou_date' => $paymentParams['thankyou_date'] ?? NULL,
1331 'payment_instrument_id' => $paymentInstrumentID,
1332 ],
1333 $financialType,
1334 FALSE,
1335 $this->_bltID,
1336 TRUE
1337 );
1338
1339 //create new soft-credit record, CRM-13981
1340 if ($softParams) {
1341 $softParams['contribution_id'] = $contribution->id;
1342 $softParams['currency'] = $contribution->currency;
1343 $softParams['amount'] = $contribution->total_amount;
1344 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1345 }
1346
1347 $paymentParams['contactID'] = $this->_contactID;
1348 $paymentParams['contributionID'] = $contribution->id;
1349 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1350 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1351 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1352 $params['contribution_id'] = $paymentParams['contributionID'];
1353 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1354 }
1355 $paymentStatus = NULL;
1356
1357 if ($params['total_amount'] > 0.0) {
1358 $payment = $this->_paymentProcessor['object'];
1359 try {
1360 $result = $payment->doPayment($paymentParams);
1361 $formValues = array_merge($formValues, $result);
1362 $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
1363 // Assign amount to template if payment was successful.
1364 $this->assign('amount', $params['total_amount']);
1365 }
1366 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
1367 if (!empty($paymentParams['contributionID'])) {
1368 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
1369 $e->getMessage());
1370 }
1371 if (!empty($paymentParams['contributionRecurID'])) {
1372 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1373 }
1374
1375 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1376 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
1377 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1378 ));
1379
1380 }
1381 }
1382
1383 if ($paymentStatus !== 'Completed') {
1384 $params['status_id'] = $pendingMembershipStatusId;
1385 $params['skipStatusCal'] = TRUE;
1386 // unset send-receipt option, since receipt will be sent when ipn is received.
1387 unset($formValues['send_receipt'], $formValues['send_receipt']);
1388 //as membership is pending set dates to null.
1389 $memberDates = [
1390 'join_date' => 'joinDate',
1391 'start_date' => 'startDate',
1392 'end_date' => 'endDate',
1393 ];
1394 foreach ($memberDates as $dv) {
1395 $$dv = NULL;
1396 foreach ($this->_memTypeSelected as $memType) {
1397 $membershipTypeValues[$memType][$dv] = NULL;
1398 }
1399 }
1400 }
1401 $now = date('YmdHis');
1402 $params['receive_date'] = date('Y-m-d H:i:s');
1403 $params['invoice_id'] = $formValues['invoiceID'];
1404 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1405 [1 => $membershipType, 2 => $userName]
1406 );
1407 $params['source'] = $formValues['source'] ?: $params['contribution_source'];
1408 $params['trxn_id'] = $result['trxn_id'] ?? NULL;
1409 $params['is_test'] = ($this->_mode === 'live') ? 0 : 1;
1410 if (!empty($formValues['send_receipt'])) {
1411 $params['receipt_date'] = $now;
1412 }
1413 else {
1414 $params['receipt_date'] = NULL;
1415 }
1416
1417 $this->set('params', $formValues);
1418 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
1419 $this->assign('receive_date',
1420 CRM_Utils_Date::mysqlToIso($params['receive_date'])
1421 );
1422
1423 // required for creating membership for related contacts
1424 $params['action'] = $this->_action;
1425
1426 //create membership record.
1427 $count = 0;
1428 foreach ($this->_memTypeSelected as $memType) {
1429 if ($count &&
1430 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1431 ) {
1432 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1433 }
1434
1435 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1436 //CRM-15366
1437 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1438 $membershipParams['soft_credit'] = $softParams;
1439 }
1440 if (isset($result['fee_amount'])) {
1441 $membershipParams['fee_amount'] = $result['fee_amount'];
1442 }
1443 // This is required to trigger the recording of the membership contribution in the
1444 // CRM_Member_BAO_Membership::Create function.
1445 // @todo stop setting this & 'teach' the create function to respond to something
1446 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1447 // process -
1448 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1449 $membershipParams['contribution_status_id'] = $result['payment_status_id'] ?? NULL;
1450 if (!empty($paymentParams['is_recur'])) {
1451 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1452 // of a single path!
1453 unset($membershipParams['lineItems']);
1454 }
1455 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
1456 // @todo stop passing $ids (membership and userId only are set above)
1457 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1458 $params['contribution'] = $membershipParams['contribution'] ?? NULL;
1459 unset($params['lineItems']);
1460 $this->_membershipIDs[] = $membership->id;
1461 $createdMemberships[$memType] = $membership;
1462 $count++;
1463 }
1464
1465 }
1466 else {
1467 $params['action'] = $this->_action;
1468 $count = 0;
1469 foreach ($this->_memTypeSelected as $memType) {
1470 if ($count && !empty($formValues['record_contribution']) &&
1471 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1472 ) {
1473 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1474 }
1475
1476 // @todo figure out why recieve_date isn't being set right here.
1477 if (empty($params['receive_date'])) {
1478 $params['receive_date'] = date('Y-m-d H:i:s');
1479 }
1480 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1481
1482 if (!empty($softParams)) {
1483 $membershipParams['soft_credit'] = $softParams;
1484 }
1485 // @todo stop passing $ids (membership and userId only are set above)
1486 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1487 $params['contribution'] = $membershipParams['contribution'] ?? NULL;
1488 unset($params['lineItems']);
1489 // skip line item creation for next interation since line item(s) are already created.
1490 $params['skipLineItem'] = TRUE;
1491
1492 $this->_membershipIDs[] = $membership->id;
1493 $createdMemberships[$memType] = $membership;
1494 $count++;
1495 }
1496 }
1497 $isRecur = $params['is_recur'] ?? NULL;
1498 if (($this->_action & CRM_Core_Action::UPDATE)) {
1499 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1500 }
1501 elseif (($this->_action & CRM_Core_Action::ADD)) {
1502 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $createdMemberships,
1503 $isRecur, $calcDates));
1504 }
1505
1506 if (!empty($lineItem[$this->_priceSetId])) {
1507 $invoicing = Civi::settings()->get('invoicing');
1508 $taxAmount = FALSE;
1509 $totalTaxAmount = 0;
1510 foreach ($lineItem[$this->_priceSetId] as & $priceFieldOp) {
1511 if (!empty($priceFieldOp['membership_type_id'])) {
1512 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date']) : '-';
1513 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date']) : '-';
1514 }
1515 else {
1516 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1517 }
1518 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1519 $taxAmount = TRUE;
1520 $totalTaxAmount += $priceFieldOp['tax_amount'];
1521 }
1522 }
1523 if ($invoicing) {
1524 $dataArray = [];
1525 foreach ($lineItem[$this->_priceSetId] as $key => $value) {
1526 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1527 if (isset($dataArray[$value['tax_rate']])) {
1528 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1529 }
1530 else {
1531 $dataArray[$value['tax_rate']] = $value['tax_amount'] ?? NULL;
1532 }
1533 }
1534 }
1535 if ($taxAmount) {
1536 $this->assign('totalTaxAmount', $totalTaxAmount);
1537 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1538 $this->assign('taxTerm', $this->getSalesTaxTerm());
1539 }
1540 $this->assign('dataArray', $dataArray);
1541 }
1542 }
1543 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1544
1545 $receiptSend = FALSE;
1546 $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
1547 $membershipIds = $this->_membershipIDs;
1548 if ($contributionId && !empty($membershipIds)) {
1549 $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(
1550 CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
1551 if ($contributionDetails[$membership->id]['contribution_status'] === 'Completed') {
1552 $receiptSend = TRUE;
1553 }
1554 }
1555
1556 $receiptSent = FALSE;
1557 if (!empty($formValues['send_receipt']) && $receiptSend) {
1558 $formValues['contact_id'] = $this->_contactID;
1559 $formValues['contribution_id'] = $contributionId;
1560 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1561 // handled in the receipt. But by setting one we avoid breaking templates for now
1562 // although at some point we should switch in the templates.
1563 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1564 // send email receipt
1565 $this->assignBillingName();
1566 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
1567 $receiptSent = TRUE;
1568 }
1569
1570 // finally set membership id if already not set
1571 if (!$this->_id) {
1572 $this->_id = $membership->id;
1573 }
1574
1575 $this->updateContributionOnMembershipTypeChange($params, $membership);
1576 if ($receiptSent && $mailSend) {
1577 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]));
1578 }
1579
1580 CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1581 $this->setStatusMessage($membership);
1582 }
1583
1584 /**
1585 * Update related contribution of a membership if update_contribution_on_membership_type_change
1586 * contribution setting is enabled and type is changed on edit
1587 *
1588 * @param array $inputParams
1589 * submitted form values
1590 * @param CRM_Member_DAO_Membership $membership
1591 * Updated membership object
1592 *
1593 * @throws \CRM_Core_Exception
1594 * @throws \CiviCRM_API3_Exception
1595 */
1596 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1597 if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
1598 // on update
1599 ($this->_action & CRM_Core_Action::UPDATE) &&
1600 // if ID is present
1601 $this->_id &&
1602 // if selected membership doesn't match with earlier membership
1603 !in_array($this->_memType, $this->_memTypeSelected)
1604 ) {
1605 if (!empty($inputParams['is_recur'])) {
1606 CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1607 return;
1608 }
1609
1610 // fetch lineitems by updated membership ID
1611 $lineItems = CRM_Price_BAO_LineItem::getLineItems($membership->id, 'membership');
1612 // retrieve the related contribution ID
1613 $contributionID = CRM_Core_DAO::getFieldValue(
1614 'CRM_Member_DAO_MembershipPayment',
1615 $membership->id,
1616 'contribution_id',
1617 'membership_id'
1618 );
1619 // get price fields of chosen price-set
1620 $priceSetDetails = CRM_Utils_Array::value(
1621 $this->_priceSetId,
1622 CRM_Price_BAO_PriceSet::getSetDetail(
1623 $this->_priceSetId,
1624 TRUE,
1625 TRUE
1626 )
1627 );
1628
1629 // add price field information in $inputParams
1630 self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
1631
1632 // update related contribution and financial records
1633 CRM_Price_BAO_LineItem::changeFeeSelections(
1634 $inputParams,
1635 $membership->id,
1636 'membership',
1637 $contributionID,
1638 $priceSetDetails['fields'],
1639 $lineItems
1640 );
1641 CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1642 }
1643 }
1644
1645 /**
1646 * Add selected price field information in $formValues
1647 *
1648 * @param array $formValues
1649 * submitted form values
1650 * @param array $priceFields
1651 * Price fields of selected Priceset ID
1652 * @param int $membershipTypeID
1653 * Selected membership type ID
1654 *
1655 */
1656 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1657 foreach ($priceFields as $priceFieldID => $priceField) {
1658 if (isset($priceField['options']) && count($priceField['options'])) {
1659 foreach ($priceField['options'] as $option) {
1660 if ($option['membership_type_id'] == $membershipTypeID) {
1661 $formValues["price_{$priceFieldID}"] = $option['id'];
1662 break;
1663 }
1664 }
1665 }
1666 }
1667 }
1668
1669 /**
1670 * Set context in session.
1671 */
1672 protected function setUserContext() {
1673 $buttonName = $this->controller->getButtonName();
1674 $session = CRM_Core_Session::singleton();
1675
1676 if ($buttonName == $this->getButtonName('upload', 'new')) {
1677 if ($this->_context === 'standalone') {
1678 $url = CRM_Utils_System::url('civicrm/member/add',
1679 'reset=1&action=add&context=standalone'
1680 );
1681 }
1682 else {
1683 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
1684 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1685 );
1686 }
1687 }
1688 else {
1689 $url = CRM_Utils_System::url('civicrm/contact/view',
1690 "reset=1&cid={$this->_contactID}&selectedChild=member"
1691 );
1692 }
1693 $session->replaceUserContext($url);
1694 }
1695
1696 /**
1697 * Get status message for updating membership.
1698 *
1699 * @param CRM_Member_BAO_Membership $membership
1700 * @param string $endDate
1701 *
1702 * @return string
1703 */
1704 protected function getStatusMessageForUpdate($membership, $endDate) {
1705 // End date can be modified by hooks, so if end date is set then use it.
1706 $endDate = ($membership->end_date) ? $membership->end_date : $endDate;
1707
1708 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName]);
1709 if ($endDate && $endDate !== 'null') {
1710 $endDate = CRM_Utils_Date::customFormat($endDate);
1711 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1712 }
1713 return $statusMsg;
1714 }
1715
1716 /**
1717 * Get status message for create action.
1718 *
1719 * @param string $endDate
1720 * @param array $createdMemberships
1721 * @param bool $isRecur
1722 * @param array $calcDates
1723 *
1724 * @return array|string
1725 */
1726 protected function getStatusMessageForCreate($endDate, $createdMemberships,
1727 $isRecur, $calcDates) {
1728 // FIX ME: fix status messages
1729
1730 $statusMsg = [];
1731 foreach ($this->_memTypeSelected as $membershipTypeID) {
1732 $statusMsg[$membershipTypeID] = ts('%1 membership for %2 has been added.', [
1733 1 => $this->allMembershipTypeDetails[$membershipTypeID]['name'],
1734 2 => $this->_memberDisplayName,
1735 ]);
1736
1737 $membership = $createdMemberships[$membershipTypeID];
1738 $memEndDate = $membership->end_date ?: $endDate;
1739
1740 //get the end date from calculated dates.
1741 if (!$memEndDate && !$isRecur) {
1742 $memEndDate = $calcDates[$membershipTypeID]['end_date'] ?? NULL;
1743 }
1744
1745 if ($memEndDate && $memEndDate !== 'null') {
1746 $memEndDate = CRM_Utils_Date::formatDateOnlyLong($memEndDate);
1747 $statusMsg[$membershipTypeID] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1748 }
1749 }
1750 $statusMsg = implode('<br/>', $statusMsg);
1751 return $statusMsg;
1752 }
1753
1754 /**
1755 * @param $membership
1756 */
1757 protected function setStatusMessage($membership) {
1758 //CRM-15187
1759 // display message when membership type is changed
1760 if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
1761 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'membership');
1762 $maxID = max(array_keys($lineItem));
1763 $lineItem = $lineItem[$maxID];
1764 $membershipTypeDetails = $this->allMembershipTypeDetails[$membership->membership_type_id];
1765 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1766 CRM_Core_Session::setStatus(
1767 ts('The financial types associated with the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its financial type.'),
1768 ts('Warning')
1769 );
1770 }
1771 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1772 CRM_Core_Session::setStatus(
1773 ts('The cost of the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its amount.'),
1774 ts('Warning')
1775 );
1776 }
1777 }
1778 }
1779
1780 /**
1781 * @return bool
1782 * @throws \CRM_Core_Exception
1783 */
1784 protected function isUpdateToExistingRecurringMembership() {
1785 $isRecur = FALSE;
1786 if ($this->_action & CRM_Core_Action::UPDATE
1787 && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1788 'contribution_recur_id')
1789 && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
1790
1791 $isRecur = TRUE;
1792 }
1793 return $isRecur;
1794 }
1795
1796 /**
1797 * Send a receipt for the membership.
1798 *
1799 * @param array $formValues
1800 * @param \CRM_Member_BAO_Membership $membership
1801 *
1802 * @return bool
1803 * @throws \CRM_Core_Exception
1804 */
1805 protected function emailMembershipReceipt($formValues, $membership) {
1806 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1807
1808 return self::emailReceipt($this, $formValues, $membership, $customValues);
1809 }
1810
1811 /**
1812 * Filter the custom values from the input parameters (for display in the email).
1813 *
1814 * @todo figure out why the scary code this calls does & document.
1815 *
1816 * @param array $formValues
1817 * @param \CRM_Member_BAO_Membership $membership
1818 * @return array
1819 */
1820 protected function getCustomValuesForReceipt($formValues, $membership) {
1821 $customFields = $customValues = [];
1822 if (property_exists($this, '_groupTree')
1823 && !empty($this->_groupTree)
1824 ) {
1825 foreach ($this->_groupTree as $groupID => $group) {
1826 if ($groupID === 'info') {
1827 continue;
1828 }
1829 foreach ($group['fields'] as $k => $field) {
1830 $field['title'] = $field['label'];
1831 $customFields["custom_{$k}"] = $field;
1832 }
1833 }
1834 }
1835
1836 $members = [['member_id', '=', $membership->id, 0, 0]];
1837 // check whether its a test drive
1838 if ($this->_mode === 'test') {
1839 $members[] = ['member_test', '=', 1, 0, 0];
1840 }
1841
1842 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1843 return $customValues;
1844 }
1845
1846 }