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