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