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