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