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