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