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