Merge pull request #19281 from eileenmcnaughton/bool
[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 [$this->_memberDisplayName, $this->_memberEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
614
615 $this->assign('emailExists', $this->_memberEmail);
616 $this->assign('displayName', $this->_memberDisplayName);
617 }
618
619 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
620 $this->assign('cancelAutoRenew',
621 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
622 );
623 }
624
625 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
626
627 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
628 $mailingInfo = Civi::settings()->get('mailing_backend');
629 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
630
631 parent::buildQuickForm();
632 }
633
634 /**
635 * Validation.
636 *
637 * @param array $params
638 * (ref.) an assoc array of name/value pairs.
639 *
640 * @param array $files
641 * @param CRM_Member_Form_Membership $self
642 *
643 * @return bool|array
644 * mixed true or array of errors
645 *
646 * @throws \CRM_Core_Exception
647 * @throws CiviCRM_API3_Exception
648 */
649 public static function formRule($params, $files, $self) {
650 $errors = [];
651
652 $priceSetId = $self->getPriceSetID($params);
653 $priceSetDetails = $self->getPriceSetDetails($params);
654
655 $selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
656
657 if (!empty($params['price_set_id'])) {
658 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
659
660 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
661
662 if (!empty($priceFieldIDS)) {
663 $ids = implode(',', $priceFieldIDS);
664
665 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
666 foreach ($count as $occurrence) {
667 if ($occurrence > 1) {
668 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
669 }
670 }
671 }
672 // Return error if empty $self->_memTypeSelected
673 if (empty($errors) && empty($selectedMemberships)) {
674 $errors['_qf_default'] = ts('Select at least one membership option.');
675 }
676 if (!$self->_mode && empty($params['record_contribution'])) {
677 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
678 }
679 }
680 else {
681 if (empty($params['membership_type_id'][1])) {
682 $errors['membership_type_id'] = ts('Please select a membership type.');
683 }
684 $numterms = $params['num_terms'] ?? NULL;
685 if ($numterms && intval($numterms) != $numterms) {
686 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
687 }
688
689 if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
690 $errors['financial_type_id'] = ts('Please enter the financial Type.');
691 }
692 }
693
694 if (!empty($errors) && (count($selectedMemberships) > 1)) {
695 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
696 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
697 foreach ($duplicateMemberOfContacts as $countDuplicate) {
698 if ($countDuplicate > 1) {
699 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
700 }
701 }
702 }
703
704 if (!empty($errors)) {
705 return $errors;
706 }
707
708 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
709 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
710 }
711
712 if (!empty($params['is_different_contribution_contact'])) {
713 if (empty($params['soft_credit_type_id'])) {
714 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
715 }
716 if (empty($params['soft_credit_contact_id'])) {
717 $errors['soft_credit_contact_id'] = ts('Please select a contact');
718 }
719 }
720
721 if (!empty($params['payment_processor_id'])) {
722 // validate payment instrument (e.g. credit card number)
723 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
724 }
725
726 $joinDate = NULL;
727 if (!empty($params['join_date'])) {
728
729 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
730
731 foreach ($selectedMemberships as $memType) {
732 $startDate = NULL;
733 if (!empty($params['start_date'])) {
734 $startDate = CRM_Utils_Date::processDate($params['start_date']);
735 }
736
737 // if end date is set, ensure that start date is also set
738 // and that end date is later than start date
739 $endDate = NULL;
740 if (!empty($params['end_date'])) {
741 $endDate = CRM_Utils_Date::processDate($params['end_date']);
742 }
743
744 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipType($memType);
745 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) === 'rolling') {
746 if ($startDate < $joinDate) {
747 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
748 }
749 }
750
751 if ($endDate) {
752 if ($membershipDetails['duration_unit'] === 'lifetime') {
753 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
754 // process to update status based on end-date. The user must change the status now.
755 $result = civicrm_api3('MembershipStatus', 'get', [
756 'sequential' => 1,
757 'is_current_member' => 0,
758 ]);
759 $tmp_statuses = $result['values'];
760 $status_ids = [];
761 foreach ($tmp_statuses as $cur_stat) {
762 $status_ids[] = $cur_stat['id'];
763 }
764
765 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
766 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
767 }
768
769 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
770 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
771 }
772 }
773 else {
774 if (!$startDate) {
775 $errors['start_date'] = ts('Start date must be set if end date is set.');
776 }
777 if ($endDate < $startDate) {
778 $errors['end_date'] = ts('End date must be the same or later than start date.');
779 }
780 }
781 }
782
783 // Default values for start and end dates if not supplied on the form.
784 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
785 $joinDate,
786 $startDate,
787 $endDate
788 );
789
790 if (!$startDate) {
791 $startDate = CRM_Utils_Array::value('start_date',
792 $defaultDates
793 );
794 }
795 if (!$endDate) {
796 $endDate = CRM_Utils_Array::value('end_date',
797 $defaultDates
798 );
799 }
800
801 //CRM-3724, check for availability of valid membership status.
802 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
803 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
804 $endDate,
805 $joinDate,
806 'now',
807 TRUE,
808 $memType,
809 $params
810 );
811 if (empty($calcStatus)) {
812 $url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
813 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
814 $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]);
815 if (!$self->_mode) {
816 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
817 }
818 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
819 }
820 }
821 }
822 }
823 else {
824 $errors['join_date'] = ts('Please enter the Member Since.');
825 }
826
827 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
828 $errors['status_id'] = ts('Please enter the Membership status.');
829 }
830
831 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
832 if (empty($params['status_override_end_date'])) {
833 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
834 }
835 }
836
837 //total amount condition arise when membership type having no
838 //minimum fee
839 if (isset($params['record_contribution'])) {
840 if (CRM_Utils_System::isNull($params['total_amount'])) {
841 $errors['total_amount'] = ts('Please enter the contribution.');
842 }
843 }
844
845 return empty($errors) ? TRUE : $errors;
846 }
847
848 /**
849 * Process the form submission.
850 *
851 * @throws \CRM_Core_Exception
852 * @throws \CiviCRM_API3_Exception
853 */
854 public function postProcess() {
855 if ($this->_action & CRM_Core_Action::DELETE) {
856 CRM_Member_BAO_Membership::del($this->_id);
857 return;
858 }
859 // get the submitted form values.
860 $this->_params = $this->controller->exportValues($this->_name);
861 $this->prepareStatusOverrideValues();
862
863 $this->submit();
864
865 $this->setUserContext();
866 }
867
868 /**
869 * Prepares the values related to status override.
870 */
871 private function prepareStatusOverrideValues() {
872 $this->setOverrideDateValue();
873 $this->convertIsOverrideValue();
874 }
875
876 /**
877 * Sets status override end date to empty value if
878 * the selected override option is not 'until date'.
879 */
880 private function setOverrideDateValue() {
881 if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
882 $this->_params['status_override_end_date'] = '';
883 }
884 }
885
886 /**
887 * Convert the value of selected (status override?)
888 * option to TRUE if it indicate an overridden status
889 * or FALSE otherwise.
890 */
891 private function convertIsOverrideValue() {
892 $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override'] ?? CRM_Member_StatusOverrideTypes::NO);
893 }
894
895 /**
896 * Send email receipt.
897 *
898 * @param CRM_Core_Form $form
899 * Form object.
900 * @param array $formValues
901 * @param object $membership
902 * Object.
903 * @param array $customValues
904 *
905 * @return bool
906 * true if mail was sent successfully
907 * @throws \CRM_Core_Exception
908 *
909 * @deprecated
910 * This function is shared with Batch_Entry which has limited overlap
911 * & needs rationalising.
912 *
913 */
914 public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
915 // retrieve 'from email id' for acknowledgement
916 $receiptFrom = $formValues['from_email_address'] ?? NULL;
917
918 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
919 if (!empty($formValues['payment_instrument_id'])) {
920 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
921 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
922 }
923
924 $form->assign('customValues', $customValues);
925
926 if ($form->_mode) {
927 // @todo move this outside shared code as Batch entry just doesn't
928 $form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
929 $form->_params,
930 $form->_bltID
931 ));
932
933 $valuesForForm = CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($form->_params);
934 $form->assignVariables($valuesForForm, ['credit_card_exp_date', 'credit_card_type', 'credit_card_number']);
935 $form->assign('is_pay_later', 0);
936 $form->assign('isPrimary', 1);
937 }
938
939 $form->assign('module', 'Membership');
940 $form->assign('contactID', $formValues['contact_id']);
941
942 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
943
944 if (!empty($formValues['contribution_id'])) {
945 $form->assign('contributionID', $formValues['contribution_id']);
946 }
947
948 if (!empty($formValues['contribution_status_id'])) {
949 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
950 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
951 }
952
953 if (!empty($formValues['is_renew'])) {
954 $form->assign('receiptType', 'membership renewal');
955 }
956 else {
957 $form->assign('receiptType', 'membership signup');
958 }
959 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
960 $form->assign('formValues', $formValues);
961
962 if (empty($lineItem)) {
963 $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date));
964 if (!CRM_Utils_System::isNull($membership->end_date)) {
965 $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date));
966 }
967 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
968 }
969
970 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
971 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
972 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
973 // in this case the form is being called statically from the batch editing screen
974 // having one class in the form layer call another statically is not greate
975 // & we should aim to move this function to the BAO layer in future.
976 // however, we can assume that the contact_id passed in by the batch
977 // function will be the recipient
978 [$form->_contributorDisplayName, $form->_contributorEmail]
979 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
980 if (empty($form->_receiptContactId) || $isBatchProcess) {
981 $form->_receiptContactId = $formValues['contact_id'];
982 }
983 }
984
985 CRM_Core_BAO_MessageTemplate::sendTemplate(
986 [
987 'groupName' => 'msg_tpl_workflow_membership',
988 'valueName' => 'membership_offline_receipt',
989 'contactId' => $form->_receiptContactId,
990 'from' => $receiptFrom,
991 'toName' => $form->_contributorDisplayName,
992 'toEmail' => $form->_contributorEmail,
993 'PDFFilename' => ts('receipt') . '.pdf',
994 'isEmailPdf' => Civi::settings()->get('invoicing') && Civi::settings()->get('is_email_pdf'),
995 'contributionId' => $formValues['contribution_id'],
996 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
997 ]
998 );
999
1000 return TRUE;
1001 }
1002
1003 /**
1004 * Submit function.
1005 *
1006 * This is also accessed by unit tests.
1007 *
1008 * @throws \CRM_Core_Exception
1009 * @throws \CiviCRM_API3_Exception
1010 */
1011 public function submit() {
1012 $isTest = ($this->_mode === 'test') ? 1 : 0;
1013 $this->storeContactFields($this->_params);
1014 $this->beginPostProcess();
1015 $endDate = NULL;
1016 $membership = $calcDate = [];
1017
1018 $paymentInstrumentID = $this->_paymentProcessor['object']->getPaymentInstrumentID();
1019 $params = $softParams = $ids = [];
1020
1021 $mailSend = FALSE;
1022 $this->processBillingAddress();
1023 $formValues = $this->_params;
1024 $formValues = $this->setPriceSetParameters($formValues);
1025
1026 if ($this->_id) {
1027 $ids['membership'] = $params['id'] = $this->_id;
1028 }
1029
1030 // Set variables that we normally get from context.
1031 // In form mode these are set in preProcess.
1032 //TODO: set memberships, fixme
1033 $this->setContextVariables($formValues);
1034
1035 $this->_memTypeSelected = self::getSelectedMemberships(
1036 $this->_priceSet,
1037 $formValues
1038 );
1039 if (empty($formValues['financial_type_id'])) {
1040 $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
1041 }
1042
1043 $membershipTypeValues = [];
1044 foreach ($this->_memTypeSelected as $memType) {
1045 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1046 }
1047
1048 //take the required membership recur values.
1049 if ($this->_mode && !empty($formValues['auto_renew'])) {
1050 $params['is_recur'] = $formValues['is_recur'] = TRUE;
1051
1052 $count = 0;
1053 foreach ($this->_memTypeSelected as $memType) {
1054 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
1055 $this->allMembershipTypeDetails, []
1056 );
1057 if (!$recurMembershipTypeValues['auto_renew']) {
1058 continue;
1059 }
1060 foreach ([
1061 'frequency_interval' => 'duration_interval',
1062 'frequency_unit' => 'duration_unit',
1063 ] as $mapVal => $mapParam) {
1064 $membershipTypeValues[$memType][$mapVal] = $recurMembershipTypeValues[$mapParam];
1065
1066 if (!$count) {
1067 $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
1068 $recurMembershipTypeValues
1069 );
1070 }
1071 }
1072 $count++;
1073 }
1074 }
1075
1076 $isQuickConfig = $this->_priceSet['is_quick_config'];
1077
1078 $termsByType = [];
1079
1080 $lineItem = [$this->_priceSetId => []];
1081
1082 // BEGIN Fix for dev/core/issues/860
1083 // Prepare fee block and call buildAmount hook - based on CRM_Price_BAO_PriceSet::buildPriceSet().
1084 CRM_Utils_Hook::buildAmount('membership', $this, $this->_priceSet['fields']);
1085 // END Fix for dev/core/issues/860
1086
1087 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1088 $formValues, $lineItem[$this->_priceSetId], $this->_priceSetId);
1089
1090 if (!empty($formValues['tax_amount'])) {
1091 $params['tax_amount'] = $formValues['tax_amount'];
1092 }
1093 $params['total_amount'] = $formValues['amount'] ?? NULL;
1094 if (!empty($lineItem[$this->_priceSetId])) {
1095 foreach ($lineItem[$this->_priceSetId] as &$li) {
1096 if (!empty($li['membership_type_id'])) {
1097 if (!empty($li['membership_num_terms'])) {
1098 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1099 }
1100 }
1101
1102 ///CRM-11529 for quick config backoffice transactions
1103 //when financial_type_id is passed in form, update the
1104 //lineitems with the financial type selected in form
1105 $submittedFinancialType = $formValues['financial_type_id'] ?? NULL;
1106 if ($isQuickConfig && $submittedFinancialType) {
1107 $li['financial_type_id'] = $submittedFinancialType;
1108 }
1109 }
1110 }
1111
1112 $params['contact_id'] = $this->_contactID;
1113
1114 $fields = [
1115 'status_id',
1116 'source',
1117 'is_override',
1118 'status_override_end_date',
1119 'campaign_id',
1120 ];
1121
1122 foreach ($fields as $f) {
1123 $params[$f] = $formValues[$f] ?? NULL;
1124 }
1125
1126 // fix for CRM-3724
1127 // when is_override false ignore is_admin statuses during membership
1128 // status calculation. similarly we did fix for import in CRM-3570.
1129 if (empty($params['is_override'])) {
1130 $params['exclude_is_admin'] = TRUE;
1131 }
1132
1133 $joinDate = $formValues['join_date'];
1134 $startDate = $formValues['start_date'];
1135 $endDate = $formValues['end_date'];
1136
1137 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
1138
1139 $calcDates = [];
1140 foreach ($this->_memTypeSelected as $memType) {
1141 if (empty($memTypeNumTerms)) {
1142 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1143 }
1144 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1145 $joinDate, $startDate, $endDate, $memTypeNumTerms
1146 );
1147 }
1148
1149 foreach ($calcDates as $memType => $calcDate) {
1150 foreach (['join_date', 'start_date', 'end_date'] as $d) {
1151 //first give priority to form values then calDates.
1152 $date = $formValues[$d] ?? NULL;
1153 if (!$date) {
1154 $date = $calcDate[$d] ?? NULL;
1155 }
1156
1157 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
1158 }
1159 }
1160
1161 foreach ($this->_memTypeSelected as $memType) {
1162 if (array_key_exists('max_related', $formValues)) {
1163 // max related memberships - take from form or inherit from membership type
1164 $membershipTypeValues[$memType]['max_related'] = $formValues['max_related'] ?? NULL;
1165 }
1166 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
1167 $this->_id,
1168 'Membership'
1169 );
1170 }
1171
1172 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1173 [$userName] = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::getLoggedInContactID());
1174
1175 //CRM-13981, allow different person as a soft-contributor of chosen type
1176 if ($this->_contributorContactID != $this->_contactID) {
1177 $params['contribution_contact_id'] = $this->_contributorContactID;
1178 if (!empty($formValues['soft_credit_type_id'])) {
1179 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1180 $softParams['contact_id'] = $this->_contactID;
1181 }
1182 }
1183
1184 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1185
1186 if (!empty($formValues['record_contribution'])) {
1187 $recordContribution = [
1188 'total_amount',
1189 'financial_type_id',
1190 'payment_instrument_id',
1191 'trxn_id',
1192 'contribution_status_id',
1193 'check_number',
1194 'campaign_id',
1195 'receive_date',
1196 'card_type_id',
1197 'pan_truncation',
1198 ];
1199
1200 foreach ($recordContribution as $f) {
1201 $params[$f] = $formValues[$f] ?? NULL;
1202 }
1203
1204 if (empty($formValues['source'])) {
1205 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1206 1 => $this->getSelectedMembershipLabels(),
1207 2 => $userName,
1208 ]);
1209 }
1210 else {
1211 $params['contribution_source'] = $formValues['source'];
1212 }
1213
1214 $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1215 if (empty($params['is_override']) &&
1216 CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
1217 ) {
1218 $params['status_id'] = $pendingMembershipStatusId;
1219 $params['skipStatusCal'] = TRUE;
1220 $params['is_pay_later'] = 1;
1221 $this->assign('is_pay_later', 1);
1222 }
1223
1224 if (!empty($formValues['send_receipt'])) {
1225 $params['receipt_date'] = $formValues['receive_date'] ?? NULL;
1226 }
1227
1228 //insert financial type name in receipt.
1229 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1230 $formValues['financial_type_id']
1231 );
1232 }
1233
1234 // process line items, until no previous line items.
1235 if (!empty($lineItem)) {
1236 $params['lineItems'] = $lineItem;
1237 $params['processPriceSet'] = TRUE;
1238 }
1239 $createdMemberships = [];
1240 if ($this->_mode) {
1241 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
1242
1243 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1244 $params['card_type_id'] = $this->_params['card_type_id'] ?? NULL;
1245 $params['pan_truncation'] = $this->_params['pan_truncation'] ?? NULL;
1246
1247 if (!$isQuickConfig) {
1248 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
1249 $this->_priceSetId,
1250 'financial_type_id'
1251 );
1252 }
1253 else {
1254 $params['financial_type_id'] = $formValues['financial_type_id'] ?? NULL;
1255 }
1256
1257 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1258 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1259 $params['register_date'] = date('YmdHis');
1260
1261 // add all the additional payment params we need
1262 $formValues['amount'] = $params['total_amount'];
1263 // @todo this is a candidate for beginPostProcessFunction.
1264 $formValues['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
1265 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1266 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1267 $formValues['financial_type_id'] = $params['financial_type_id'];
1268
1269 // at this point we've created a contact and stored its address etc
1270 // all the payment processors expect the name and address to be in the
1271 // so we copy stuff over to first_name etc.
1272 $paymentParams = $formValues;
1273 $paymentParams['contactID'] = $this->_contributorContactID;
1274 //CRM-10377 if payment is by an alternate contact then we need to set that person
1275 // as the contact in the payment params
1276 if ($this->_contributorContactID != $this->_contactID) {
1277 if (!empty($formValues['soft_credit_type_id'])) {
1278 $softParams['contact_id'] = $params['contact_id'];
1279 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1280 }
1281 }
1282 if (!empty($formValues['send_receipt'])) {
1283 $paymentParams['email'] = $this->_contributorEmail;
1284 }
1285
1286 // This is a candidate for shared beginPostProcess function.
1287 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1288 CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
1289 // CRM-7137 -for recurring membership,
1290 // we do need contribution and recurring records.
1291 $result = NULL;
1292 if (!empty($paymentParams['is_recur'])) {
1293 $financialType = new CRM_Financial_DAO_FinancialType();
1294 $financialType->id = $params['financial_type_id'];
1295 $financialType->find(TRUE);
1296 $this->_params = $formValues;
1297
1298 $contribution = $this->processContribution(
1299 $paymentParams,
1300 NULL,
1301 [
1302 'contact_id' => $this->_contributorContactID,
1303 'line_item' => $lineItem,
1304 'is_test' => $isTest,
1305 'campaign_id' => $paymentParams['campaign_id'] ?? NULL,
1306 'contribution_page_id' => $formValues['contribution_page_id'] ?? NULL,
1307 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1308 'thankyou_date' => $paymentParams['thankyou_date'] ?? NULL,
1309 'payment_instrument_id' => $paymentInstrumentID,
1310 ],
1311 $financialType
1312 );
1313
1314 //create new soft-credit record, CRM-13981
1315 if ($softParams) {
1316 $softParams['contribution_id'] = $contribution->id;
1317 $softParams['currency'] = $contribution->currency;
1318 $softParams['amount'] = $contribution->total_amount;
1319 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1320 }
1321
1322 $paymentParams['contactID'] = $this->_contactID;
1323 $paymentParams['contributionID'] = $contribution->id;
1324 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1325 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1326 $params['contribution_id'] = $paymentParams['contributionID'];
1327 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1328 }
1329 $paymentStatus = NULL;
1330
1331 if ($params['total_amount'] > 0.0) {
1332 $payment = $this->_paymentProcessor['object'];
1333 try {
1334 $result = $payment->doPayment($paymentParams);
1335 $formValues = array_merge($formValues, $result);
1336 $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
1337 // Assign amount to template if payment was successful.
1338 $this->assign('amount', $params['total_amount']);
1339 }
1340 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
1341 if (!empty($paymentParams['contributionID'])) {
1342 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
1343 $e->getMessage());
1344 }
1345 if (!empty($paymentParams['contributionRecurID'])) {
1346 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1347 }
1348
1349 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1350 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
1351 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1352 ));
1353
1354 }
1355 }
1356
1357 if ($paymentStatus !== 'Completed') {
1358 $params['status_id'] = $pendingMembershipStatusId;
1359 $params['skipStatusCal'] = TRUE;
1360 // unset send-receipt option, since receipt will be sent when ipn is received.
1361 unset($formValues['send_receipt'], $formValues['send_receipt']);
1362 //as membership is pending set dates to null.
1363 foreach ($this->_memTypeSelected as $memType) {
1364 $membershipTypeValues[$memType]['joinDate'] = NULL;
1365 $membershipTypeValues[$memType]['startDate'] = NULL;
1366 $membershipTypeValues[$memType]['endDate'] = NULL;
1367 }
1368 $endDate = $startDate = NULL;
1369 }
1370 $now = date('YmdHis');
1371 $params['receive_date'] = date('Y-m-d H:i:s');
1372 $params['invoice_id'] = $formValues['invoiceID'];
1373 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1374 [1 => $this->getSelectedMembershipLabels(), 2 => $userName]
1375 );
1376 $params['source'] = $formValues['source'] ?: $params['contribution_source'];
1377 $params['trxn_id'] = $result['trxn_id'] ?? NULL;
1378 $params['is_test'] = ($this->_mode === 'live') ? 0 : 1;
1379 if (!empty($formValues['send_receipt'])) {
1380 $params['receipt_date'] = $now;
1381 }
1382 else {
1383 $params['receipt_date'] = NULL;
1384 }
1385
1386 $this->set('params', $formValues);
1387 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
1388 $this->assign('receive_date',
1389 CRM_Utils_Date::mysqlToIso($params['receive_date'])
1390 );
1391
1392 // required for creating membership for related contacts
1393 $params['action'] = $this->_action;
1394
1395 //create membership record.
1396 $count = 0;
1397 foreach ($this->_memTypeSelected as $memType) {
1398 if ($count &&
1399 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1400 ) {
1401 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1402 }
1403
1404 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1405 //CRM-15366
1406 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1407 $membershipParams['soft_credit'] = $softParams;
1408 }
1409 if (isset($result['fee_amount'])) {
1410 $membershipParams['fee_amount'] = $result['fee_amount'];
1411 }
1412 // This is required to trigger the recording of the membership contribution in the
1413 // CRM_Member_BAO_Membership::Create function.
1414 // @todo stop setting this & 'teach' the create function to respond to something
1415 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1416 // process -
1417 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1418 $membershipParams['contribution_status_id'] = $result['payment_status_id'] ?? NULL;
1419 if (!empty($paymentParams['is_recur'])) {
1420 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1421 // of a single path!
1422 unset($membershipParams['lineItems']);
1423 }
1424 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
1425 // @todo stop passing $ids (membership and userId only are set above)
1426 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1427 $params['contribution'] = $membershipParams['contribution'] ?? NULL;
1428 unset($params['lineItems']);
1429 $this->_membershipIDs[] = $membership->id;
1430 $createdMemberships[$memType] = $membership;
1431 $count++;
1432 }
1433
1434 }
1435 else {
1436 $params['action'] = $this->_action;
1437 foreach ($lineItem[$this->_priceSetId] as $id => $lineItemValues) {
1438 if (empty($lineItemValues['membership_type_id'])) {
1439 continue;
1440 }
1441
1442 // @todo figure out why recieve_date isn't being set right here.
1443 if (empty($params['receive_date'])) {
1444 $params['receive_date'] = date('Y-m-d H:i:s');
1445 }
1446 $membershipParams = array_merge($params, $membershipTypeValues[$lineItemValues['membership_type_id']]);
1447
1448 if (!empty($softParams)) {
1449 $membershipParams['soft_credit'] = $softParams;
1450 }
1451 unset($membershipParams['contribution_status_id']);
1452 $membershipParams['skipLineItem'] = TRUE;
1453 unset($membershipParams['lineItems']);
1454 // @todo stop passing $ids (membership and userId only are set above)
1455 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1456 $lineItem[$this->_priceSetId][$id]['entity_id'] = $membership->id;
1457 $lineItem[$this->_priceSetId][$id]['entity_table'] = 'civicrm_membership';
1458
1459 $this->_membershipIDs[] = $membership->id;
1460 $createdMemberships[$membership->membership_type_id] = $membership;
1461 }
1462 $params['lineItems'] = $lineItem;
1463 if (!empty($formValues['record_contribution'])) {
1464 CRM_Member_BAO_Membership::recordMembershipContribution($params);
1465 }
1466 }
1467 $isRecur = $params['is_recur'] ?? NULL;
1468 if (($this->_action & CRM_Core_Action::UPDATE)) {
1469 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1470 }
1471 elseif (($this->_action & CRM_Core_Action::ADD)) {
1472 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $createdMemberships,
1473 $isRecur, $calcDates));
1474 }
1475
1476 // This would always be true as we always add price set id into both
1477 // quick config & non quick config price sets.
1478 if (!empty($lineItem[$this->_priceSetId])) {
1479 $invoicing = Civi::settings()->get('invoicing');
1480 $taxAmount = FALSE;
1481 $totalTaxAmount = 0;
1482 foreach ($lineItem[$this->_priceSetId] as & $priceFieldOp) {
1483 if (!empty($priceFieldOp['membership_type_id'])) {
1484 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date']) : '-';
1485 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date']) : '-';
1486 }
1487 else {
1488 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1489 }
1490 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1491 $taxAmount = TRUE;
1492 $totalTaxAmount += $priceFieldOp['tax_amount'];
1493 }
1494 }
1495 if ($invoicing) {
1496 $dataArray = [];
1497 foreach ($lineItem[$this->_priceSetId] as $key => $value) {
1498 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1499 if (isset($dataArray[$value['tax_rate']])) {
1500 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1501 }
1502 else {
1503 $dataArray[$value['tax_rate']] = $value['tax_amount'] ?? NULL;
1504 }
1505 }
1506 }
1507 if ($taxAmount) {
1508 $this->assign('totalTaxAmount', $totalTaxAmount);
1509 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1510 $this->assign('taxTerm', $this->getSalesTaxTerm());
1511 }
1512 $this->assign('dataArray', $dataArray);
1513 }
1514 }
1515 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1516
1517 $receiptSend = FALSE;
1518 $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
1519 $membershipIds = $this->_membershipIDs;
1520 if ($contributionId && !empty($membershipIds)) {
1521 $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(
1522 CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
1523 if ($contributionDetails[$membership->id]['contribution_status'] === 'Completed') {
1524 $receiptSend = TRUE;
1525 }
1526 }
1527
1528 $receiptSent = FALSE;
1529 if (!empty($formValues['send_receipt']) && $receiptSend) {
1530 $formValues['contact_id'] = $this->_contactID;
1531 $formValues['contribution_id'] = $contributionId;
1532 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1533 // handled in the receipt. But by setting one we avoid breaking templates for now
1534 // although at some point we should switch in the templates.
1535 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1536 // send email receipt
1537 $this->assignBillingName();
1538 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
1539 $receiptSent = TRUE;
1540 }
1541
1542 // finally set membership id if already not set
1543 if (!$this->_id) {
1544 $this->_id = $membership->id;
1545 }
1546
1547 $this->updateContributionOnMembershipTypeChange($params, $membership);
1548 if ($receiptSent && $mailSend) {
1549 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]));
1550 }
1551
1552 CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1553 $this->setStatusMessage($membership);
1554 }
1555
1556 /**
1557 * Update related contribution of a membership if update_contribution_on_membership_type_change
1558 * contribution setting is enabled and type is changed on edit
1559 *
1560 * @param array $inputParams
1561 * submitted form values
1562 * @param CRM_Member_DAO_Membership $membership
1563 * Updated membership object
1564 *
1565 * @throws \CRM_Core_Exception
1566 * @throws \CiviCRM_API3_Exception
1567 */
1568 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1569 if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
1570 // on update
1571 ($this->_action & CRM_Core_Action::UPDATE) &&
1572 // if ID is present
1573 $this->_id &&
1574 // if selected membership doesn't match with earlier membership
1575 !in_array($this->_memType, $this->_memTypeSelected)
1576 ) {
1577 if (!empty($inputParams['is_recur'])) {
1578 CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1579 return;
1580 }
1581
1582 // fetch lineitems by updated membership ID
1583 $lineItems = CRM_Price_BAO_LineItem::getLineItems($membership->id, 'membership');
1584 // retrieve the related contribution ID
1585 $contributionID = CRM_Core_DAO::getFieldValue(
1586 'CRM_Member_DAO_MembershipPayment',
1587 $membership->id,
1588 'contribution_id',
1589 'membership_id'
1590 );
1591 // get price fields of chosen price-set
1592 $priceSetDetails = CRM_Utils_Array::value(
1593 $this->_priceSetId,
1594 CRM_Price_BAO_PriceSet::getSetDetail(
1595 $this->_priceSetId,
1596 TRUE,
1597 TRUE
1598 )
1599 );
1600
1601 // add price field information in $inputParams
1602 self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
1603
1604 // update related contribution and financial records
1605 CRM_Price_BAO_LineItem::changeFeeSelections(
1606 $inputParams,
1607 $membership->id,
1608 'membership',
1609 $contributionID,
1610 $priceSetDetails['fields'],
1611 $lineItems
1612 );
1613 CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1614 }
1615 }
1616
1617 /**
1618 * Add selected price field information in $formValues
1619 *
1620 * @param array $formValues
1621 * submitted form values
1622 * @param array $priceFields
1623 * Price fields of selected Priceset ID
1624 * @param int $membershipTypeID
1625 * Selected membership type ID
1626 *
1627 */
1628 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1629 foreach ($priceFields as $priceFieldID => $priceField) {
1630 if (isset($priceField['options']) && count($priceField['options'])) {
1631 foreach ($priceField['options'] as $option) {
1632 if ($option['membership_type_id'] == $membershipTypeID) {
1633 $formValues["price_{$priceFieldID}"] = $option['id'];
1634 break;
1635 }
1636 }
1637 }
1638 }
1639 }
1640
1641 /**
1642 * Set context in session.
1643 */
1644 protected function setUserContext() {
1645 $buttonName = $this->controller->getButtonName();
1646 $session = CRM_Core_Session::singleton();
1647
1648 if ($buttonName == $this->getButtonName('upload', 'new')) {
1649 if ($this->_context === 'standalone') {
1650 $url = CRM_Utils_System::url('civicrm/member/add',
1651 'reset=1&action=add&context=standalone'
1652 );
1653 }
1654 else {
1655 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
1656 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1657 );
1658 }
1659 }
1660 else {
1661 $url = CRM_Utils_System::url('civicrm/contact/view',
1662 "reset=1&cid={$this->_contactID}&selectedChild=member"
1663 );
1664 }
1665 $session->replaceUserContext($url);
1666 }
1667
1668 /**
1669 * Get status message for updating membership.
1670 *
1671 * @param CRM_Member_BAO_Membership $membership
1672 * @param string $endDate
1673 *
1674 * @return string
1675 */
1676 protected function getStatusMessageForUpdate($membership, $endDate) {
1677 // End date can be modified by hooks, so if end date is set then use it.
1678 $endDate = ($membership->end_date) ? $membership->end_date : $endDate;
1679
1680 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName]);
1681 if ($endDate && $endDate !== 'null') {
1682 $endDate = CRM_Utils_Date::customFormat($endDate);
1683 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1684 }
1685 return $statusMsg;
1686 }
1687
1688 /**
1689 * Get status message for create action.
1690 *
1691 * @param string $endDate
1692 * @param array $createdMemberships
1693 * @param bool $isRecur
1694 * @param array $calcDates
1695 *
1696 * @return array|string
1697 */
1698 protected function getStatusMessageForCreate($endDate, $createdMemberships,
1699 $isRecur, $calcDates) {
1700 // FIX ME: fix status messages
1701
1702 $statusMsg = [];
1703 foreach ($this->_memTypeSelected as $membershipTypeID) {
1704 $statusMsg[$membershipTypeID] = ts('%1 membership for %2 has been added.', [
1705 1 => $this->allMembershipTypeDetails[$membershipTypeID]['name'],
1706 2 => $this->_memberDisplayName,
1707 ]);
1708
1709 $membership = $createdMemberships[$membershipTypeID];
1710 $memEndDate = $membership->end_date ?: $endDate;
1711
1712 //get the end date from calculated dates.
1713 if (!$memEndDate && !$isRecur) {
1714 $memEndDate = $calcDates[$membershipTypeID]['end_date'] ?? NULL;
1715 }
1716
1717 if ($memEndDate && $memEndDate !== 'null') {
1718 $memEndDate = CRM_Utils_Date::formatDateOnlyLong($memEndDate);
1719 $statusMsg[$membershipTypeID] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1720 }
1721 }
1722 $statusMsg = implode('<br/>', $statusMsg);
1723 return $statusMsg;
1724 }
1725
1726 /**
1727 * @param $membership
1728 */
1729 protected function setStatusMessage($membership) {
1730 //CRM-15187
1731 // display message when membership type is changed
1732 if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
1733 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'membership');
1734 $maxID = max(array_keys($lineItem));
1735 $lineItem = $lineItem[$maxID];
1736 $membershipTypeDetails = $this->allMembershipTypeDetails[$membership->membership_type_id];
1737 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1738 CRM_Core_Session::setStatus(
1739 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.'),
1740 ts('Warning')
1741 );
1742 }
1743 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1744 CRM_Core_Session::setStatus(
1745 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.'),
1746 ts('Warning')
1747 );
1748 }
1749 }
1750 }
1751
1752 /**
1753 * @return bool
1754 * @throws \CRM_Core_Exception
1755 */
1756 protected function isUpdateToExistingRecurringMembership() {
1757 $isRecur = FALSE;
1758 if ($this->_action & CRM_Core_Action::UPDATE
1759 && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1760 'contribution_recur_id')
1761 && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
1762
1763 $isRecur = TRUE;
1764 }
1765 return $isRecur;
1766 }
1767
1768 /**
1769 * Send a receipt for the membership.
1770 *
1771 * @param array $formValues
1772 * @param \CRM_Member_BAO_Membership $membership
1773 *
1774 * @return bool
1775 * @throws \CRM_Core_Exception
1776 */
1777 protected function emailMembershipReceipt($formValues, $membership) {
1778 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1779
1780 return self::emailReceipt($this, $formValues, $membership, $customValues);
1781 }
1782
1783 /**
1784 * Filter the custom values from the input parameters (for display in the email).
1785 *
1786 * @todo figure out why the scary code this calls does & document.
1787 *
1788 * @param array $formValues
1789 * @param \CRM_Member_BAO_Membership $membership
1790 * @return array
1791 */
1792 protected function getCustomValuesForReceipt($formValues, $membership) {
1793 $customFields = $customValues = [];
1794 if (property_exists($this, '_groupTree')
1795 && !empty($this->_groupTree)
1796 ) {
1797 foreach ($this->_groupTree as $groupID => $group) {
1798 if ($groupID === 'info') {
1799 continue;
1800 }
1801 foreach ($group['fields'] as $k => $field) {
1802 $field['title'] = $field['label'];
1803 $customFields["custom_{$k}"] = $field;
1804 }
1805 }
1806 }
1807
1808 $members = [['member_id', '=', $membership->id, 0, 0]];
1809 // check whether its a test drive
1810 if ($this->_mode === 'test') {
1811 $members[] = ['member_test', '=', 1, 0, 0];
1812 }
1813
1814 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1815 return $customValues;
1816 }
1817
1818 /**
1819 * Get the selected memberships as a string of labels.
1820 *
1821 * @return string
1822 */
1823 protected function getSelectedMembershipLabels(): string {
1824 $return = [];
1825 foreach ($this->_memTypeSelected as $membershipTypeID) {
1826 $return[] = $this->allMembershipTypeDetails[$membershipTypeID]['name'];
1827 }
1828 return implode(', ', $return);
1829 }
1830
1831 /**
1832 * Legacy contribution processing function.
1833 *
1834 * This is copied from a shared function in order to clean it up. Most of the
1835 * stuff in it, maybe all except the ContributionRecur create is
1836 * not applicable to this form & can be removed in follow up cleanup.
1837 *
1838 * It's like the contribution create being done here is actively bad and
1839 * being fixed later.
1840 *
1841 * @param array $params
1842 * @param array $result
1843 * @param array $contributionParams
1844 * Parameters to be passed to contribution create action.
1845 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1846 * passed consistently & 2) documenting them here.
1847 * - contact_id
1848 * - line_item
1849 * - is_test
1850 * - campaign_id
1851 * - contribution_page_id
1852 * - source
1853 * - payment_type_id
1854 * - thankyou_date (not all forms will set this)
1855 *
1856 * @param CRM_Financial_DAO_FinancialType $financialType
1857 *
1858 * @return \CRM_Contribute_DAO_Contribution
1859 *
1860 * @throws \CRM_Core_Exception
1861 * @throws \CiviCRM_API3_Exception
1862 */
1863 protected function processContribution(
1864 $params,
1865 $result,
1866 $contributionParams,
1867 $financialType
1868 ) {
1869 $form = $this;
1870 $transaction = new CRM_Core_Transaction();
1871 $contactID = $contributionParams['contact_id'];
1872
1873 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
1874
1875 // add these values for the recurringContrib function ,CRM-10188
1876 $params['financial_type_id'] = $financialType->id;
1877
1878 //@todo - this is being set from the form to resolve CRM-10188 - an
1879 // eNotice caused by it not being set @ the front end
1880 // however, we then get it being over-written with null for backend contributions
1881 // a better fix would be to set the values in the respective forms rather than require
1882 // a function being shared by two forms to deal with their respective values
1883 // moving it to the BAO & not taking the $form as a param would make sense here.
1884 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1885 $params['is_email_receipt'] = $isEmailReceipt;
1886 }
1887 $params['is_recur'] = TRUE;
1888 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ?? NULL;
1889 $recurringContributionID = $this->legacyProcessRecurringContribution($params, $contactID, $financialType);
1890
1891 $now = date('YmdHis');
1892 $receiptDate = $params['receipt_date'] ?? NULL;
1893 if ($isEmailReceipt) {
1894 $receiptDate = $now;
1895 }
1896
1897 if (isset($params['amount'])) {
1898 $contributionParams = array_merge([
1899 'financial_type_id' => $financialType->id,
1900 'receive_date' => !empty($params['receive_date']) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
1901 'tax_amount' => $params['tax_amount'] ?? NULL,
1902 'amount_level' => $params['amount_level'] ?? NULL,
1903 'invoice_id' => $params['invoiceID'],
1904 'currency' => $params['currencyID'],
1905 'is_pay_later' => $params['is_pay_later'] ?? 0,
1906 //configure cancel reason, cancel date and thankyou date
1907 //from 'contribution' type profile if included
1908 'cancel_reason' => $params['cancel_reason'] ?? 0,
1909 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL,
1910 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL,
1911 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
1912 'skipLineItem' => $params['skipLineItem'] ?? 0,
1913 ], $contributionParams);
1914
1915 if (!empty($params["is_email_receipt"])) {
1916 $contributionParams += [
1917 'receipt_date' => $receiptDate,
1918 ];
1919 }
1920
1921 if ($recurringContributionID) {
1922 $contributionParams['contribution_recur_id'] = $recurringContributionID;
1923 }
1924
1925 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1926 if (isset($contributionParams['invoice_id'])) {
1927 $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
1928 'CRM_Contribute_DAO_Contribution',
1929 $contributionParams['invoice_id'],
1930 'id',
1931 'invoice_id'
1932 );
1933 }
1934
1935 $contributionParams['skipCleanMoney'] = TRUE;
1936 // @todo this is the wrong place for this - it should be done as close to form submission
1937 // as possible
1938 $contributionParams['total_amount'] = $params['amount'];
1939 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
1940
1941 // lets store it in the form variable so postProcess hook can get to this and use it
1942 $form->_contributionID = $contribution->id;
1943 }
1944
1945 // process soft credit / pcp params first
1946 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
1947
1948 //CRM-13981, processing honor contact into soft-credit contribution
1949 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
1950
1951 $transaction->commit();
1952 return $contribution;
1953 }
1954
1955 /**
1956 * Create the recurring contribution record.
1957 *
1958 * This function was copied from another form & needs cleanup.
1959 *
1960 * @param array $params
1961 * @param int $contactID
1962 * @param string $contributionType
1963 *
1964 * @return int|null
1965 */
1966 protected function legacyProcessRecurringContribution(&$params, $contactID, $contributionType) {
1967 $form = $this;
1968 if (empty($params['is_recur'])) {
1969 return NULL;
1970 }
1971
1972 $recurParams = ['contact_id' => $contactID];
1973 $recurParams['amount'] = $params['amount'] ?? NULL;
1974 $recurParams['auto_renew'] = $params['auto_renew'] ?? NULL;
1975 $recurParams['frequency_unit'] = $params['frequency_unit'] ?? NULL;
1976 $recurParams['frequency_interval'] = $params['frequency_interval'] ?? NULL;
1977 $recurParams['installments'] = $params['installments'] ?? NULL;
1978 $recurParams['financial_type_id'] = $params['financial_type_id'] ?? NULL;
1979 $recurParams['currency'] = $params['currency'] ?? NULL;
1980 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1981
1982 $recurParams['is_test'] = 0;
1983 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1984 (isset($form->_mode) && ($form->_mode == 'test'))
1985 ) {
1986 $recurParams['is_test'] = 1;
1987 }
1988
1989 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1990 if (!empty($params['receive_date'])) {
1991 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1992 }
1993 $recurParams['invoice_id'] = $params['invoiceID'] ?? NULL;
1994 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1995 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ?? NULL;
1996 $recurParams['is_email_receipt'] = $params['is_email_receipt'] ?? NULL;
1997 // we need to add a unique trxn_id to avoid a unique key error
1998 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1999 $recurParams['trxn_id'] = $params['trxn_id'] ?? $params['invoiceID'];
2000 $recurParams['financial_type_id'] = $contributionType->id;
2001
2002 $campaignId = $params['campaign_id'] ?? $form->_values['campaign_id'] ?? NULL;
2003 $recurParams['campaign_id'] = $campaignId;
2004 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
2005 if (is_a($recurring, 'CRM_Core_Error')) {
2006 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($recurring));
2007 }
2008
2009 return $recurring->id;
2010 }
2011
2012 }