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