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