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