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