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