Merge pull request #911 from agh1/membership-dash-counts-new
[civicrm-core.git] / CRM / Member / Form / MembershipRenewal.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 Membership Renewal
38 *
39 */
40 class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
41 /*
42 * Display name of the member
43 */
44 protected $_memberDisplayName = null;
45 /*
46 * email of the person paying for the membership (used for receipts)
47 */
48 protected $_memberEmail = null;
49 /*
50 * Contact ID of the member
51 */
52 protected $_contactID = null;
53 /*
54 * Display name of the person paying for the membership (used for receipts)
55 */
56 protected $_contributorDisplayName = null;
57 /*
58 * email of the person paying for the membership (used for receipts)
59 */
60 protected $_contributorEmail = null;
61 /*
62 * email of the person paying for the membership (used for receipts)
63 */
64 protected $_contributorContactID = null;
65 /*
66 * ID of the person the receipt is to go to
67 */
68 protected $_receiptContactId = null;
69 /*
70 * context would be set to standalone if the contact is use is being selected from
71 * the form rather than in the URL
72 */
73 protected $_context;
74
75 public function preProcess() {
76 //custom data related code
77 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
78 $this->assign('cdType', FALSE);
79 if ($this->_cdType) {
80 $this->assign('cdType', TRUE);
81 return CRM_Custom_Form_CustomData::preProcess($this);
82 }
83
84 // check for edit permission
85 if (!CRM_Core_Permission::check('edit memberships')) {
86 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
87 }
88 // action
89 $this->_action = CRM_Utils_Request::retrieve('action', 'String',
90 $this, FALSE, 'add'
91 );
92 $this->_context = CRM_Utils_Request::retrieve('context', 'String',
93 $this, FALSE, 'membership'
94 );
95 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive',
96 $this
97 );
98 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive',
99 $this
100 );
101 if ($this->_id) {
102 $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
103 }
104
105 $this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
106 $this->_id, 'end_date'
107 )
108 ));
109 $this->assign('membershipStatus',
110 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
111 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
112 $this->_id, 'status_id'
113 ),
114 'name'
115 )
116 );
117
118 //using credit card :: CRM-2759
119 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
120 if ($this->_mode) {
121 $membershipFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
122 if (!$membershipFee) {
123 $statusMsg = ts('Membership Renewal using a credit card requires a Membership fee. Since there is no fee associated with the selected memebership type, you can use the normal renewal mode.');
124 CRM_Core_Session::setStatus($statusMsg, '', 'info');
125 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
126 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership"
127 ));
128 }
129 $this->assign('membershipMode', $this->_mode);
130
131 $this->_paymentProcessor = array('billing_mode' => 1);
132 $validProcessors = array();
133 $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'billing_mode IN ( 1, 3 )');
134
135 foreach ($processors as $ppID => $label) {
136 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
137 if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
138 continue;
139 }
140 elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
141 continue;
142 }
143 else {
144 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
145 $error = $paymentObject->checkConfig();
146 if (empty($error)) {
147 $validProcessors[$ppID] = $label;
148 }
149 $paymentObject = NULL;
150 }
151 }
152 if (empty($validProcessors)) {
153 CRM_Core_Error::fatal(ts('Could not find valid payment processor for this page'));
154 }
155 else {
156 $this->_processors = $validProcessors;
157 }
158 // also check for billing information
159 // get the billing location type
160 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
161 // CRM-8108 remove ts around Billing location type
162 //$this->_bltID = array_search( ts('Billing'), $locationTypes );
163 $this->_bltID = array_search('Billing', $locationTypes);
164 if (!$this->_bltID) {
165 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
166 }
167 $this->set('bltID', $this->_bltID);
168 $this->assign('bltID', $this->_bltID);
169
170 $this->_fields = array();
171
172 CRM_Core_Payment_Form::setCreditCardFields($this);
173
174 // this required to show billing block
175 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
176 $this->assign('hidePayPalExpress', TRUE);
177 }
178 else {
179 $this->assign('membershipMode', FALSE);
180 }
181
182 // when custom data is included in this page
183 if (CRM_Utils_Array::value('hidden_custom', $_POST)) {
184 CRM_Custom_Form_CustomData::preProcess($this);
185 CRM_Custom_Form_CustomData::buildQuickForm($this);
186 CRM_Custom_Form_CustomData::setDefaultValues($this);
187 }
188
189 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
190 parent::preProcess();
191 }
192
193 /**
194 * This function sets the default values for the form.
195 * the default values are retrieved from the database
196 *
197 * @access public
198 *
199 * @return None
200 */
201 public function setDefaultValues() {
202 if ($this->_cdType) {
203 return CRM_Custom_Form_CustomData::setDefaultValues($this);
204 }
205 $defaults = array();
206 $defaults = parent::setDefaultValues();
207 $this->_memType = $defaults['membership_type_id'];
208
209 // set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
210 list($now) = CRM_Utils_Date::setDateDefaults();
211 $defaults['renewal_date'] = $now;
212 $defaults['receive_date'] = $now;
213
214 if ($defaults['id']) {
215 $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
216 $defaults['id'],
217 'contribution_id',
218 'membership_id'
219 );
220 }
221
222 if (is_numeric($this->_memType)) {
223 $defaults['membership_type_id'] = array();
224 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
225 $this->_memType,
226 'member_of_contact_id',
227 'id'
228 );
229 $defaults['membership_type_id'][1] = $this->_memType;
230 }
231 else {
232 $defaults['membership_type_id'] = $this->_memType;
233 }
234
235 $defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
236
237 $defaults['total_amount'] = CRM_Utils_Money::format(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
238 $this->_memType,
239 'minimum_fee'
240 ), NULL, '%a');
241
242
243 $defaults['record_contribution'] = 0;
244 $defaults['num_terms'] = 1;
245 $defaults['send_receipt'] = 0;
246
247 $renewalDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('renewal_date', $defaults),
248 NULL, NULL, 'Y-m-d'
249 );
250 $this->assign('renewalDate', $renewalDate);
251 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
252
253 if ($this->_mode) {
254 $fields = array();
255
256 foreach ($this->_fields as $name => $dontCare) {
257 $fields[$name] = 1;
258 }
259
260 $names = array(
261 'first_name', 'middle_name', 'last_name', "street_address-{$this->_bltID}",
262 "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}",
263 "state_province_id-{$this->_bltID}",
264 );
265 foreach ($names as $name) {
266 $fields[$name] = 1;
267 }
268
269 $fields["state_province-{$this->_bltID}"] = 1;
270 $fields["country-{$this->_bltID}"] = 1;
271 $fields["email-{$this->_bltID}"] = 1;
272 $fields['email-Primary'] = 1;
273
274 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactID, $fields, $this->_defaults);
275
276 // use primary email address if billing email address is empty
277 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
278 !empty($this->_defaults['email-Primary'])
279 ) {
280 $defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
281 }
282
283 foreach ($names as $name) {
284 if (!empty($this->_defaults[$name])) {
285 $defaults['billing_' . $name] = $this->_defaults[$name];
286 }
287 }
288 }
289
290 return $defaults;
291 }
292
293 /**
294 * Function to build the form
295 *
296 * @return None
297 * @access public
298 */
299 public function buildQuickForm() {
300 if ($this->_cdType) {
301 return CRM_Custom_Form_CustomData::buildQuickForm($this);
302 }
303
304 parent::buildQuickForm();
305
306 $defaults = array();
307 $defaults = parent::setDefaultValues();
308 $this->_memType = $defaults['membership_type_id'];
309 $this->assign('customDataType', 'Membership');
310 $this->assign('customDataSubType', $this->_memType);
311 $this->assign('entityID', $this->_id);
312 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
313
314 $allMemberships = CRM_Member_BAO_Membership::buildMembershipTypeValues($this);
315
316 $allMembershipInfo = $membershipType = array();
317
318 // auto renew options if enabled for the membership
319 $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required '));
320
321 foreach( $allMemberships as $key => $values ) {
322 if (CRM_Utils_Array::value('is_active', $values) ) {
323 $membershipType[$key] = CRM_Utils_Array::value('name', $values);
324 if ($this->_mode && !CRM_Utils_Array::value('minimum_fee', $values)) {
325 continue;
326 }
327 else {
328 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
329 if (!CRM_Utils_Array::value($memberOfContactId, $selMemTypeOrg)) {
330 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
331 $memberOfContactId,
332 'display_name',
333 'id'
334 );
335
336 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
337 }
338 if (!CRM_Utils_Array::value($key, $selOrgMemType[$memberOfContactId])) {
339 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
340 }
341 }
342
343 // build membership info array, which is used to set the payment information block when
344 // membership type is selected.
345 $allMembershipInfo[$key] = array(
346 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
347 'total_amount' => CRM_Utils_Money::format($values['minimum_fee'], NULL, '%a'),
348 'total_amount_numeric' => CRM_Utils_Array::value('minimum_fee', $values)
349 );
350
351 if (CRM_Utils_Array::value('auto_renew', $values)) {
352 $allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
353 }
354 }
355 }
356
357 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
358
359 if ($this->_memType) {
360 $this->assign('orgName', $selMemTypeOrg[$allMemberships[$this->_memType]['member_of_contact_id']]);
361 $this->assign('memType', $allMemberships[$this->_memType]['name']);
362 }
363
364 // force select of organization by default, if only one organization in
365 // the list
366 if (count($selMemTypeOrg) == 2) {
367 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
368 }
369 //sort membership organization and type, CRM-6099
370 natcasesort($selMemTypeOrg);
371 foreach ($selOrgMemType as $index => $orgMembershipType) {
372 natcasesort($orgMembershipType);
373 $selOrgMemType[$index] = $orgMembershipType;
374 }
375
376 $js = array('onChange' => "setPaymentBlock( ); CRM.buildCustomData( 'Membership', this.value );");
377
378 //build the form for auto renew.
379 $recurProcessor = array();
380 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
381 //get the valid recurring processors.
382 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
383 $recurProcessor = array_intersect_assoc($this->_processors, $recurring);
384 if (!empty($recurProcessor)) {
385 $autoRenew = array();
386 if (!empty($membershipType)) {
387 $sql = '
388 SELECT id,
389 auto_renew,
390 duration_unit,
391 duration_interval
392 FROM civicrm_membership_type
393 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
394 $recurMembershipTypes = CRM_Core_DAO::executeQuery($sql);
395 while ($recurMembershipTypes->fetch()) {
396 $autoRenew[$recurMembershipTypes->id] = $recurMembershipTypes->auto_renew;
397 foreach (array(
398 'id', 'auto_renew', 'duration_unit', 'duration_interval') as $fld) {
399 $this->_recurMembershipTypes[$recurMembershipTypes->id][$fld] = $recurMembershipTypes->$fld;
400 }
401 }
402 }
403 $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData( 'Membership', this.value );");
404 $this->assign('autoRenew', json_encode($autoRenew));
405 }
406 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
407 NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
408 );
409 if ($this->_action & CRM_Core_Action::UPDATE) {
410 $autoRenewElement->freeze();
411 }
412 }
413 $this->assign('recurProcessor', json_encode($recurProcessor));
414
415 $sel = &$this->addElement('hierselect',
416 'membership_type_id',
417 ts('Renewal Membership Organization and Type'), $js
418 );
419
420 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
421 $elements = array();
422 if ($sel) {
423 $elements[] = $sel;
424 }
425
426 $this->applyFilter('__ALL__', 'trim');
427
428 $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
429
430 $this->add('select', 'financial_type_id', ts('Financial Type'),
431 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
432 );
433 if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
434 $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
435
436 $this->add('text', 'total_amount', ts('Amount'));
437 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
438
439 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDate'));
440
441 $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
442 $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
443
444 $this->add('select', 'payment_instrument_id', ts('Paid By'),
445 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
446 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
447 );
448
449 $this->add('text', 'trxn_id', ts('Transaction ID'));
450 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
451 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
452 );
453
454 $this->add('select', 'contribution_status_id', ts('Payment Status'),
455 CRM_Contribute_PseudoConstant::contributionStatus()
456 );
457
458 $this->add('text', 'check_number', ts('Check Number'),
459 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
460 );
461 }
462 else {
463 $this->add('text', 'total_amount', ts('Amount'));
464 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
465 }
466 $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
467 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);")
468 );
469
470 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
471
472 $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
473
474 if ($this->_mode) {
475 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
476 CRM_Core_Payment_Form::buildCreditCard($this, TRUE);
477 }
478
479 // Retrieve the name and email of the contact - this will be the TO for receipt email
480 list($this->_contributorDisplayName,
481 $this->_contributorEmail
482 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
483 $this->assign('email', $this->_contributorEmail);
484
485 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
486 'mailing_backend'
487 );
488 $this->assign('outBound_option', $mailingInfo['outBound_option']);
489
490 if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
491 if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
492 $this->assign('cancelAutoRenew',
493 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
494 );
495 }
496 }
497 $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
498 if ($this->_context != 'standalone') {
499 //CRM-10223 - allow contribution to be recorded against different contact
500 // causes a conflict in standalone mode so skip in standalone for now
501 $this->addElement('checkbox', 'contribution_contact', ts('Record Payment from a Different Contact?'));
502 $this->add( 'select', 'honor_type_id', ts('Membership payment is : '),
503 array( '' => ts( '-') ) + CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'honor_type_id') );
504 require_once 'CRM/Contact/Form/NewContact.php';
505 CRM_Contact_Form_NewContact::buildQuickForm($this,1, null, false,'contribution_');
506 }
507 }
508
509 /**
510 * Function for validation
511 *
512 * @param array $params (ref.) an assoc array of name/value pairs
513 *
514 * @return mixed true or array of errors
515 * @access public
516 * @static
517 */
518 static function formRule($params) {
519 $errors = array();
520 if ($params['membership_type_id'][0] == 0) {
521 $errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link, and select a Membership Organization.');
522 }
523 if ($params['membership_type_id'][1] == 0) {
524 $errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link and select a Membership Type from the list.');
525 }
526
527 //total amount condition arise when membership type having no
528 //minimum fee
529 if (isset($params['record_contribution'])) {
530 if (!$params['financial_type_id']) {
531 $errors['financial_type_id'] = ts('Please select a Financial Type.');
532 }
533 if (!$params['total_amount']) {
534 $errors['total_amount'] = ts('Please enter a Contribution Amount.');
535 }
536 }
537 return empty($errors) ? TRUE : $errors;
538 }
539
540 /**
541 * Function to process the renewal form
542 *
543 * @access public
544 *
545 * @return None
546 */
547 public function postProcess() {
548
549 $ids = array();
550 $config = CRM_Core_Config::singleton();
551
552 // get the submitted form values.
553 $this->_params = $formValues = $this->controller->exportValues($this->_name);
554
555 $this->storeContactFields($formValues);
556 // use values from screen
557
558 if ($formValues['membership_type_id'][1] <> 0) {
559 $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
560 $formValues['membership_type_id'][1],
561 'receipt_text_renewal'
562 );
563 }
564
565 $now = CRM_Utils_Date::getToday( null, 'YmdHis');
566 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
567 $formValues['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date']);
568 }
569 else {
570 $formValues['receive_date'] = $now;
571 }
572 $this->assign('receive_date', $formValues['receive_date']);
573
574 if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
575 $formValues['receipt_date'] = $now;
576 $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
577 }
578 else {
579 $formValues['receipt_date'] = NULL;
580 }
581
582 if ($this->_mode) {
583 $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
584 $this->_memType, 'minimum_fee'
585 ));
586 if (!CRM_Utils_Array::value('financial_type_id', $formValues)) {
587 $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType,'financial_type_id');
588 }
589
590 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'],
591 $this->_mode
592 );
593
594 $fields = array();
595
596 // set email for primary location.
597 $fields['email-Primary'] = 1;
598 $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
599 $formValues['register_date'] = $now;
600
601 // now set the values for the billing location.
602 foreach ($this->_fields as $name => $dontCare) {
603 $fields[$name] = 1;
604 }
605
606 // also add location name to the array
607 $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);
608
609 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
610
611 $fields["address_name-{$this->_bltID}"] = 1;
612
613 $fields["email-{$this->_bltID}"] = 1;
614
615 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
616
617 $nameFields = array('first_name', 'middle_name', 'last_name');
618
619 foreach ($nameFields as $name) {
620 $fields[$name] = 1;
621 if (array_key_exists("billing_$name", $formValues)) {
622 $formValues[$name] = $formValues["billing_{$name}"];
623 $formValues['preserveDBName'] = TRUE;
624 }
625 }
626
627 //here we are setting up the billing contact - if different from the member they are already created
628 // but they will get billing details assigned
629 CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields,
630 $this->_contributorContactID, NULL, NULL, $ctype
631 );
632
633 // add all the additional payment params we need
634 $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}"]);
635 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
636
637 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
638 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
639 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
640 $this->_params['amount'] = $formValues['total_amount'];
641 $this->_params['currencyID'] = $config->defaultCurrency;
642 $this->_params['payment_action'] = 'Sale';
643 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
644
645 // at this point we've created a contact and stored its address etc
646 // all the payment processors expect the name and address to be in the passed params
647 // so we copy stuff over to first_name etc.
648 $paymentParams = $this->_params;
649 if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
650 $paymentParams['email'] = $this->_contributorEmail;
651 }
652
653 $paymentParams['contactID'] = $this->_contributorContactID;
654 //CRM-10377 if payment is by an alternate contact then we need to set that person
655 // as the contact in the payment params
656 if ($this->_contributorContactID != $this->_contactID) {
657 if (CRM_Utils_Array::value('honor_type_id', $this->_params)) {
658 $paymentParams['honor_contact_id'] = $this->_contactID;
659 $paymentParams['honor_type_id'] = $this->_params['honor_type_id'];
660 }
661 }
662
663 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
664
665 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
666
667 $result = &$payment->doDirectPayment($paymentParams);
668
669 if (is_a($result, 'CRM_Core_Error')) {
670 CRM_Core_Error::displaySessionError($result);
671 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
672 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
673 ));
674 }
675
676 if ($result) {
677 $this->_params = array_merge($this->_params, $result);
678 }
679 $formValues['contribution_status_id'] = 1;
680 $formValues['invoice_id'] = $this->_params['invoiceID'];
681 $formValues['trxn_id'] = $result['trxn_id'];
682 $formValues['payment_instrument_id'] = 1;
683 $formValues['is_test'] = ($this->_mode == 'live') ? 0 : 1;
684 $this->set('params', $this->_params);
685 $this->assign('trxn_id', $result['trxn_id']);
686 }
687
688 $renewalDate = NULL;
689
690 if ($formValues['renewal_date']) {
691 $this->set('renewalDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
692 }
693 $this->_membershipId = $this->_id;
694
695 // membership type custom data
696 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE,
697 $formValues['membership_type_id'][1]
698 );
699
700 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
701 CRM_Core_BAO_CustomField::getFields('Membership',
702 FALSE, FALSE,
703 NULL, NULL, TRUE
704 )
705 );
706
707 $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues,
708 $customFields,
709 $this->_id,
710 'Membership'
711 );
712
713 // check for test membership.
714 $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
715
716 // chk for renewal for multiple terms CRM-8750
717 $numRenewTerms = 1;
718 if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
719 $numRenewTerms = $formValues['num_terms'];
720 }
721
722 //if contribution status is pending then set pay later
723 if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
724 $this->_params['is_pay_later'] = 1;
725 }
726 $renewMembership = CRM_Member_BAO_Membership::renewMembership($this->_contactID,
727 $formValues['membership_type_id'][1],
728 $isTestMembership, $this, NULL, NULL,
729 $customFieldsFormatted, $numRenewTerms
730 );
731
732 $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
733
734 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
735 $session = CRM_Core_Session::singleton();
736 $userID = $session->get('userID');
737
738 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
739
740 $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
741
742 if (CRM_Utils_Array::value('record_contribution', $formValues) || $this->_mode) {
743 // set the source
744 $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
745
746 //create line items
747 $lineItem = array();
748 $priceSetId = null;
749 CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
750 CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'],
751 $this->_params, $lineItem[$priceSetId]
752 );
753 //CRM-11529 for quick config backoffice transactions
754 //when financial_type_id is passed in form, update the
755 //lineitems with the financial type selected in form
756 if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
757 foreach ($lineItem[$priceSetId] as &$li) {
758 $li['financial_type_id'] = $submittedFinancialType;
759 }
760 }
761 $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
762 if (!empty($lineItem)) {
763 $formValues['lineItems'] = $lineItem;
764 $formValues['processPriceSet'] = TRUE;
765 }
766
767 //assign contribution contact id to the field expected by recordMembershipContribution
768 if($this->_contributorContactID != $this->_contactID){
769 $formValues['contribution_contact_id'] = $this->_contributorContactID;
770 if(CRM_Utils_Array::value('honor_type_id', $this->_params)){
771 $formValues['honor_contact_id'] = $this->_contactID;
772 }
773 }
774 $formValues['contact_id'] = $this->_contactID;
775
776 CRM_Member_BAO_Membership::recordMembershipContribution( $formValues,
777 CRM_Core_DAO::$_nullArray,
778 $renewMembership->id );
779 }
780
781 if (CRM_Utils_Array::value('send_receipt', $formValues)) {
782 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType',
783 $formValues['membership_type_id'][1],
784 'receipt_text_renewal',
785 $formValues['receipt_text_renewal']
786 );
787 }
788
789 $receiptSend = FALSE;
790 if (CRM_Utils_Array::value('send_receipt', $formValues)) {
791 $receiptSend = TRUE;
792
793 $receiptFrom = $formValues['from_email_address'];
794
795 if (CRM_Utils_Array::value('payment_instrument_id', $formValues)) {
796 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
797 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
798 }
799 //get the group Tree
800 $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
801
802 // retrieve custom data
803 $customFields = $customValues = $fo = array();
804 foreach ($this->_groupTree as $groupID => $group) {
805 if ($groupID == 'info') {
806 continue;
807 }
808 foreach ($group['fields'] as $k => $field) {
809 $field['title'] = $field['label'];
810 $customFields["custom_{$k}"] = $field;
811 }
812 }
813 $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
814 // check whether its a test drive
815 if ($this->_mode == 'test') {
816 $members[] = array('member_test', '=', 1, 0, 0);
817 }
818 CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
819
820 $this->assign_by_ref('formValues', $formValues);
821 if ( CRM_Utils_Array::value( 'contribution_id', $formValues ) ) {
822 $this->assign('contributionID', $formValues['contribution_id']);
823 }
824 $this->assign('membershipID', $this->_id);
825 $this->assign('contactID', $this->_contactID);
826 $this->assign('module', 'Membership');
827 $this->assign('receiptType', 'membership renewal');
828 $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
829 $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
830 $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
831 $renewMembership->membership_type_id
832 ));
833 $this->assign('customValues', $customValues);
834 if ($this->_mode) {
835 if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
836 $name = $this->_params['billing_first_name'];
837 }
838
839 if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
840 $name .= " {$this->_params['billing_middle_name']}";
841 }
842
843 if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
844 $name .= " {$this->_params['billing_last_name']}";
845 }
846 $this->assign('billingName', $name);
847
848 // assign the address formatted up for display
849 $addressParts = array(
850 "street_address-{$this->_bltID}",
851 "city-{$this->_bltID}",
852 "postal_code-{$this->_bltID}",
853 "state_province-{$this->_bltID}",
854 "country-{$this->_bltID}",
855 );
856 $addressFields = array();
857 foreach ($addressParts as $part) {
858 list($n, $id) = explode('-', $part);
859 if (isset($this->_params['billing_' . $part])) {
860 $addressFields[$n] = $this->_params['billing_' . $part];
861 }
862 }
863 $this->assign('address', CRM_Utils_Address::format($addressFields));
864 $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
865 $date = CRM_Utils_Date::mysqlToIso($date);
866 $this->assign('credit_card_exp_date', $date);
867 $this->assign('credit_card_number',
868 CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
869 );
870 $this->assign('credit_card_type', $this->_params['credit_card_type']);
871 $this->assign('contributeMode', 'direct');
872 $this->assign('isAmountzero', 0);
873 $this->assign('is_pay_later', 0);
874 $this->assign('isPrimary', 1);
875 if ($this->_mode == 'test') {
876 $this->assign('action', '1024');
877 }
878 }
879
880 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(
881 array(
882 'groupName' => 'msg_tpl_workflow_membership',
883 'valueName' => 'membership_offline_receipt',
884 'contactId' => $this->_receiptContactId,
885 'from' => $receiptFrom,
886 'toName' => $this->_contributorDisplayName,
887 'toEmail' => $this->_contributorEmail,
888 'isTest' => $this->_mode == 'test',
889 )
890 );
891 }
892
893 $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
894
895 if ($endDate) {
896 $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate,0,8))));
897 }
898
899 if ($receiptSend && $mailSend) {
900 $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
901 }
902
903 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
904 }
905 }
906