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