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