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