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