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