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