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