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