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