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