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