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