Merge pull request #6123 from eileenmcnaughton/CRM-16788
[civicrm-core.git] / CRM / Member / Form / MembershipRenewal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for Membership Renewal
38 *
39 */
40 class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
41
42 /**
43 * Display name of the member.
44 *
45 * @var string
46 */
47 protected $_memberDisplayName = NULL;
48
49 /**
50 * email of the person paying for the membership (used for receipts)
51 */
52 protected $_memberEmail = NULL;
53
54 /**
55 * Contact ID of the member.
56 *
57 *
58 * @var int
59 */
60 public $_contactID = NULL;
61
62 /**
63 * Display name of the person paying for the membership (used for receipts)
64 *
65 * @var string
66 */
67 protected $_contributorDisplayName = NULL;
68
69 /**
70 * email of the person paying for the membership (used for receipts)
71 */
72 protected $_contributorEmail = NULL;
73
74 /**
75 * email of the person paying for the membership (used for receipts)
76 *
77 * @var int
78 */
79 protected $_contributorContactID = NULL;
80
81 /**
82 * ID of the person the receipt is to go to
83 *
84 * @var int
85 */
86 protected $_receiptContactId = NULL;
87
88 /**
89 * context would be set to standalone if the contact is use is being selected from
90 * the form rather than in the URL
91 */
92 public $_context;
93
94 /**
95 * An array to hold a list of datefields on the form
96 * so that they can be converted to ISO in a consistent manner
97 *
98 * @var array
99 */
100 protected $_dateFields = array(
101 'receive_date' => array('default' => 'now'),
102 );
103
104 public function preProcess() {
105
106 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
107 $this->assign('formClass', 'membershiprenew');
108 parent::preProcess();
109 // check for edit permission
110 if (!CRM_Core_Permission::check('edit memberships')) {
111 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
112 }
113
114 $this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
115 $this->_id, 'end_date'
116 )
117 ));
118 $this->assign('membershipStatus',
119 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
120 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
121 $this->_id, 'status_id'
122 ),
123 'name'
124 )
125 );
126
127 if ($this->_mode) {
128 $membershipFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
129 if (!$membershipFee) {
130 $statusMsg = ts('Membership Renewal using a credit card requires a Membership fee. Since there is no fee associated with the selected membership type, you can use the normal renewal mode.');
131 CRM_Core_Session::setStatus($statusMsg, '', 'info');
132 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
133 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership"
134 ));
135 }
136 }
137
138 // when custom data is included in this page
139 if (!empty($_POST['hidden_custom'])) {
140 CRM_Custom_Form_CustomData::preProcess($this);
141 CRM_Custom_Form_CustomData::buildQuickForm($this);
142 CRM_Custom_Form_CustomData::setDefaultValues($this);
143 }
144
145 CRM_Utils_System::setTitle(ts('Renew Membership'));
146 }
147
148 /**
149 * Set default values for the form.
150 * the default values are retrieved from the database
151 *
152 * @return array
153 * Default values.
154 */
155 public function setDefaultValues() {
156
157 $defaults = parent::setDefaultValues();
158 $this->_memType = $defaults['membership_type_id'];
159
160 // set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
161 list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
162 $defaults['renewal_date'] = $now;
163 $defaults['receive_date'] = $now;
164 $defaults['receive_date_time'] = $currentTime;
165
166 if ($defaults['id']) {
167 $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
168 $defaults['id'],
169 'contribution_id',
170 'membership_id'
171 );
172 }
173
174 if (is_numeric($this->_memType)) {
175 $defaults['membership_type_id'] = array();
176 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
177 $this->_memType,
178 'member_of_contact_id',
179 'id'
180 );
181 $defaults['membership_type_id'][1] = $this->_memType;
182 }
183 else {
184 $defaults['membership_type_id'] = $this->_memType;
185 }
186
187 $defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
188
189 //CRM-13420
190 if (empty($defaults['payment_instrument_id'])) {
191 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
192 }
193
194 $defaults['total_amount'] = CRM_Utils_Money::format(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
195 $this->_memType,
196 'minimum_fee'
197 ), NULL, '%a');
198
199 $defaults['record_contribution'] = 0;
200 $defaults['num_terms'] = 1;
201 $defaults['send_receipt'] = 0;
202
203 //set Soft Credit Type to Gift by default
204 $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
205 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
206
207 $renewalDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('renewal_date', $defaults),
208 NULL, NULL, 'Y-m-d'
209 );
210 $this->assign('renewalDate', $renewalDate);
211 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
212
213 if ($this->_mode) {
214 // set default country from config if no country set
215 $config = CRM_Core_Config::singleton();
216 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
217 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
218 }
219
220 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
221 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
222 }
223
224 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
225 $defaults = array_merge($defaults, $billingDefaults);
226
227 }
228 return $defaults;
229 }
230
231 /**
232 * Build the form object.
233 */
234 public function buildQuickForm() {
235
236 parent::buildQuickForm();
237
238 $defaults = parent::setDefaultValues();
239 $this->_memType = $defaults['membership_type_id'];
240 $this->assign('customDataType', 'Membership');
241 $this->assign('customDataSubType', $this->_memType);
242 $this->assign('entityID', $this->_id);
243 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
244
245 $allMembershipInfo = array();
246
247 // auto renew options if enabled for the membership
248 $options = CRM_Core_SelectValues::memberAutoRenew();
249
250 foreach ($this->allMembershipTypeDetails as $key => $values) {
251 if (!empty($values['is_active'])) {
252 if ($this->_mode && empty($values['minimum_fee'])) {
253 continue;
254 }
255 else {
256 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
257 if (empty($selMemTypeOrg[$memberOfContactId])) {
258 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
259 $memberOfContactId,
260 'display_name',
261 'id'
262 );
263
264 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
265 }
266 if (empty($selOrgMemType[$memberOfContactId][$key])) {
267 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
268 }
269 }
270
271 // build membership info array, which is used to set the payment information block when
272 // membership type is selected.
273 $allMembershipInfo[$key] = array(
274 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
275 'total_amount' => CRM_Utils_Money::format($values['minimum_fee'], NULL, '%a'),
276 'total_amount_numeric' => CRM_Utils_Array::value('minimum_fee', $values),
277 );
278
279 if (!empty($values['auto_renew'])) {
280 $allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
281 }
282 }
283 }
284
285 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
286
287 if ($this->_memType) {
288 $this->assign('orgName', $selMemTypeOrg[$this->allMembershipTypeDetails[$this->_memType]['member_of_contact_id']]);
289 $this->assign('memType', $this->allMembershipTypeDetails[$this->_memType]['name']);
290 }
291
292 // force select of organization by default, if only one organization in
293 // the list
294 if (count($selMemTypeOrg) == 2) {
295 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
296 }
297 //sort membership organization and type, CRM-6099
298 natcasesort($selMemTypeOrg);
299 foreach ($selOrgMemType as $index => $orgMembershipType) {
300 natcasesort($orgMembershipType);
301 $selOrgMemType[$index] = $orgMembershipType;
302 }
303
304 $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);");
305 $sel = &$this->addElement('hierselect',
306 'membership_type_id',
307 ts('Renewal Membership Organization and Type'), $js
308 );
309
310 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
311 $elements = array();
312 if ($sel) {
313 $elements[] = $sel;
314 }
315
316 $this->applyFilter('__ALL__', 'trim');
317
318 $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
319
320 $this->add('select', 'financial_type_id', ts('Financial Type'),
321 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
322 );
323 if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
324 $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
325
326 $this->add('text', 'total_amount', ts('Amount'));
327 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
328
329 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
330
331 $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
332 $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
333
334 $this->add('select', 'payment_instrument_id', ts('Paid By'),
335 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
336 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
337 );
338
339 $this->add('text', 'trxn_id', ts('Transaction ID'));
340 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
341 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
342 );
343
344 $this->add('select', 'contribution_status_id', ts('Payment Status'),
345 CRM_Contribute_PseudoConstant::contributionStatus()
346 );
347
348 $this->add('text', 'check_number', ts('Check Number'),
349 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
350 );
351 }
352 else {
353 $this->add('text', 'total_amount', ts('Amount'));
354 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
355 }
356 $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
357 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);")
358 );
359
360 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
361
362 $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
363
364 // Retrieve the name and email of the contact - this will be the TO for receipt email
365 list($this->_contributorDisplayName,
366 $this->_contributorEmail
367 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
368 $this->assign('email', $this->_contributorEmail);
369 // The member form uses emailExists. Assigning both while we transition / synchronise.
370 $this->assign('emailExists', $this->_contributorEmail);
371
372 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
373 'mailing_backend'
374 );
375 $this->assign('outBound_option', $mailingInfo['outBound_option']);
376
377 if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
378 if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
379 $this->assign('cancelAutoRenew',
380 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
381 );
382 }
383 }
384 $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
385 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different
386 Contact?'));
387 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
388 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
389 }
390
391 /**
392 * Validation.
393 *
394 * @param array $params
395 * (ref.) an assoc array of name/value pairs.
396 *
397 * @return bool|array
398 * mixed true or array of errors
399 */
400 public static function formRule($params) {
401 $errors = array();
402 if ($params['membership_type_id'][0] == 0) {
403 $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.');
404 }
405 if ($params['membership_type_id'][1] == 0) {
406 $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.');
407 }
408
409 //total amount condition arise when membership type having no
410 //minimum fee
411 if (isset($params['record_contribution'])) {
412 if (!$params['financial_type_id']) {
413 $errors['financial_type_id'] = ts('Please select a Financial Type.');
414 }
415 if (!$params['total_amount']) {
416 $errors['total_amount'] = ts('Please enter a Contribution Amount.');
417 }
418 if (empty($params['payment_instrument_id'])) {
419 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
420 }
421 }
422 return empty($errors) ? TRUE : $errors;
423 }
424
425 /**
426 * Process the renewal form.
427 *
428 *
429 * @return void
430 */
431 public function postProcess() {
432
433 $config = CRM_Core_Config::singleton();
434
435 // get the submitted form values.
436 $this->_params = $formValues = $this->controller->exportValues($this->_name);
437
438 $this->storeContactFields($formValues);
439 // use values from screen
440
441 if ($formValues['membership_type_id'][1] <> 0) {
442 $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
443 $formValues['membership_type_id'][1],
444 'receipt_text_renewal'
445 );
446 }
447
448 $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
449 $this->convertDateFieldsToMySQL($formValues);
450 $this->assign('receive_date', $formValues['receive_date']);
451
452 if (!empty($this->_params['send_receipt'])) {
453 $formValues['receipt_date'] = $now;
454 $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
455 }
456 else {
457 $formValues['receipt_date'] = NULL;
458 }
459
460 if ($this->_mode) {
461 $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
462 $this->_memType, 'minimum_fee'
463 ));
464 if (empty($formValues['financial_type_id'])) {
465 $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
466 }
467
468 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'],
469 $this->_mode
470 );
471
472 $fields = array();
473
474 // set email for primary location.
475 $fields['email-Primary'] = 1;
476 $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
477 $formValues['register_date'] = $now;
478
479 // now set the values for the billing location.
480 foreach ($this->_fields as $name => $dontCare) {
481 $fields[$name] = 1;
482 }
483
484 // also add location name to the array
485 $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);
486
487 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
488
489 $fields["address_name-{$this->_bltID}"] = 1;
490
491 $fields["email-{$this->_bltID}"] = 1;
492
493 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
494
495 $nameFields = array('first_name', 'middle_name', 'last_name');
496
497 foreach ($nameFields as $name) {
498 $fields[$name] = 1;
499 if (array_key_exists("billing_$name", $formValues)) {
500 $formValues[$name] = $formValues["billing_{$name}"];
501 $formValues['preserveDBName'] = TRUE;
502 }
503 }
504
505 //here we are setting up the billing contact - if different from the member they are already created
506 // but they will get billing details assigned
507 CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields,
508 $this->_contributorContactID, NULL, NULL, $ctype
509 );
510
511 // add all the additional payment params we need
512 $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}"]);
513 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
514
515 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
516 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
517 $this->_params['description'] = ts('Office Credit Card Membership Renewal Contribution');
518 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
519 $this->_params['amount'] = $formValues['total_amount'];
520 $this->_params['currencyID'] = $config->defaultCurrency;
521 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
522
523 // at this point we've created a contact and stored its address etc
524 // all the payment processors expect the name and address to be in the passed params
525 // so we copy stuff over to first_name etc.
526 $paymentParams = $this->_params;
527 if (!empty($this->_params['send_receipt'])) {
528 $paymentParams['email'] = $this->_contributorEmail;
529 }
530
531 $paymentParams['contactID'] = $this->_contributorContactID;
532
533 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
534
535 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
536
537 $result = &$payment->doDirectPayment($paymentParams);
538
539 if (is_a($result, 'CRM_Core_Error')) {
540 CRM_Core_Error::displaySessionError($result);
541 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
542 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
543 ));
544 }
545
546 if ($result) {
547 $this->_params = array_merge($this->_params, $result);
548 }
549 $formValues['contribution_status_id'] = 1;
550 $formValues['invoice_id'] = $this->_params['invoiceID'];
551 $formValues['trxn_id'] = $result['trxn_id'];
552 $formValues['payment_instrument_id'] = 1;
553 $formValues['is_test'] = ($this->_mode == 'live') ? 0 : 1;
554 $this->set('params', $this->_params);
555 $this->assign('trxn_id', $result['trxn_id']);
556 }
557
558 $renewalDate = NULL;
559 if ($formValues['renewal_date']) {
560 $renewalDate = CRM_Utils_Date::processDate($formValues['renewal_date']);
561 }
562 // This set is probably obsolete.
563 $this->set('renewalDate', $renewalDate);
564
565 $this->_membershipId = $this->_id;
566
567 // membership type custom data
568 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE,
569 $formValues['membership_type_id'][1]
570 );
571
572 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
573 CRM_Core_BAO_CustomField::getFields('Membership',
574 FALSE, FALSE,
575 NULL, NULL, TRUE
576 )
577 );
578
579 $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues,
580 $this->_id,
581 'Membership'
582 );
583
584 // check for test membership.
585 $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
586
587 // chk for renewal for multiple terms CRM-8750
588 $numRenewTerms = 1;
589 if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
590 $numRenewTerms = $formValues['num_terms'];
591 }
592
593 //if contribution status is pending then set pay later
594 if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
595 $this->_params['is_pay_later'] = 1;
596 }
597
598 // These variable sets prior to renewMembership may not be required for this form. They were in
599 // a function this form shared with other forms.
600 $contributionRecurID = isset($this->_params['contributionRecurID']) ? $this->_params['contributionRecurID'] : NULL;
601 $membershipSource = NULL;
602 if (!empty($this->_params['membership_source'])) {
603 $membershipSource = $this->_params['membership_source'];
604 }
605 $isPayLater = NULL;
606 if (isset($this->_params)) {
607 $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_params);
608 }
609 $campaignId = NULL;
610 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
611 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
612 if (!array_key_exists('campaign_id', $this->_params)) {
613 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
614 }
615 }
616
617 $renewMembership = CRM_Member_BAO_Membership::renewMembership(
618 $this->_contactID, $formValues['membership_type_id'][1], $isTestMembership,
619 $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
620 self::extractPendingFormValue($this, $formValues['membership_type_id'][1]),
621 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
622 );
623
624 $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
625
626 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
627
628 $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
629
630 if (!empty($formValues['record_contribution']) || $this->_mode) {
631 // set the source
632 $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
633
634 //create line items
635 $lineItem = array();
636 $priceSetId = NULL;
637 CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
638 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
639 $this->_params, $lineItem[$priceSetId]
640 );
641 //CRM-11529 for quick config backoffice transactions
642 //when financial_type_id is passed in form, update the
643 //line items with the financial type selected in form
644 if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
645 foreach ($lineItem[$priceSetId] as &$li) {
646 $li['financial_type_id'] = $submittedFinancialType;
647 }
648 }
649 $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
650 if (!empty($lineItem)) {
651 $formValues['lineItems'] = $lineItem;
652 $formValues['processPriceSet'] = TRUE;
653 }
654
655 //assign contribution contact id to the field expected by recordMembershipContribution
656 if ($this->_contributorContactID != $this->_contactID) {
657 $formValues['contribution_contact_id'] = $this->_contributorContactID;
658 if (!empty($this->_params['soft_credit_type_id'])) {
659 $formValues['soft_credit'] = array(
660 'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
661 'contact_id' => $this->_contactID,
662 );
663 }
664 }
665 $formValues['contact_id'] = $this->_contactID;
666 //recordMembershipContribution receives params as a reference & adds one variable. This is
667 // not a great pattern & ideally it would not receive as a reference. We assign our params as a
668 // temporary variable to avoid e-notice & to make it clear to future refactorer that
669 // this function is NOT reliant on that var being set
670 $temporaryParams = array_merge($formValues, array('membership_id' => $renewMembership->id));
671 CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
672 }
673
674 $receiptSend = FALSE;
675 if (!empty($formValues['send_receipt'])) {
676 $receiptSend = TRUE;
677
678 $receiptFrom = $formValues['from_email_address'];
679
680 if (!empty($formValues['payment_instrument_id'])) {
681 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
682 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
683 }
684 //get the group Tree
685 $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
686
687 // retrieve custom data
688 $customFields = $customValues = $fo = array();
689 foreach ($this->_groupTree as $groupID => $group) {
690 if ($groupID == 'info') {
691 continue;
692 }
693 foreach ($group['fields'] as $k => $field) {
694 $field['title'] = $field['label'];
695 $customFields["custom_{$k}"] = $field;
696 }
697 }
698 $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
699 // check whether its a test drive
700 if ($this->_mode == 'test') {
701 $members[] = array('member_test', '=', 1, 0, 0);
702 }
703 CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
704
705 $this->assign_by_ref('formValues', $formValues);
706 if (!empty($formValues['contribution_id'])) {
707 $this->assign('contributionID', $formValues['contribution_id']);
708 }
709 $this->assign('membershipID', $this->_id);
710 $this->assign('contactID', $this->_contactID);
711 $this->assign('module', 'Membership');
712 $this->assign('receiptType', 'membership renewal');
713 $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
714 $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
715 $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
716 $renewMembership->membership_type_id
717 ));
718 $this->assign('customValues', $customValues);
719 if ($this->_mode) {
720 if (!empty($this->_params['billing_first_name'])) {
721 $name = $this->_params['billing_first_name'];
722 }
723
724 if (!empty($this->_params['billing_middle_name'])) {
725 $name .= " {$this->_params['billing_middle_name']}";
726 }
727
728 if (!empty($this->_params['billing_last_name'])) {
729 $name .= " {$this->_params['billing_last_name']}";
730 }
731 $this->assign('billingName', $name);
732
733 // assign the address formatted up for display
734 $addressParts = array(
735 "street_address-{$this->_bltID}",
736 "city-{$this->_bltID}",
737 "postal_code-{$this->_bltID}",
738 "state_province-{$this->_bltID}",
739 "country-{$this->_bltID}",
740 );
741 $addressFields = array();
742 foreach ($addressParts as $part) {
743 list($n, $id) = explode('-', $part);
744 if (isset($this->_params['billing_' . $part])) {
745 $addressFields[$n] = $this->_params['billing_' . $part];
746 }
747 }
748 $this->assign('address', CRM_Utils_Address::format($addressFields));
749 $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
750 $date = CRM_Utils_Date::mysqlToIso($date);
751 $this->assign('credit_card_exp_date', $date);
752 $this->assign('credit_card_number',
753 CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
754 );
755 $this->assign('credit_card_type', $this->_params['credit_card_type']);
756 $this->assign('contributeMode', 'direct');
757 $this->assign('isAmountzero', 0);
758 $this->assign('is_pay_later', 0);
759 $this->assign('isPrimary', 1);
760 $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
761 if ($this->_mode == 'test') {
762 $this->assign('action', '1024');
763 }
764 }
765
766 list($mailSend) = CRM_Core_BAO_MessageTemplate::sendTemplate(
767 array(
768 'groupName' => 'msg_tpl_workflow_membership',
769 'valueName' => 'membership_offline_receipt',
770 'contactId' => $this->_receiptContactId,
771 'from' => $receiptFrom,
772 'toName' => $this->_contributorDisplayName,
773 'toEmail' => $this->_contributorEmail,
774 'isTest' => $this->_mode == 'test',
775 )
776 );
777 }
778
779 $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
780
781 if ($endDate) {
782 $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate, 0, 8))));
783 }
784
785 if ($receiptSend && $mailSend) {
786 $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
787 }
788
789 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
790 }
791
792 /**
793 * Determine if the form has a pending status.
794 *
795 * @deprecated
796 *
797 * @param CRM_Core_Form $form
798 * @param int $membershipID
799 *
800 * @return bool
801 */
802 public static function extractPendingFormValue($form, $membershipID) {
803 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipID);
804 $pending = FALSE;
805 // @todo function was shared by 2 not-very-related forms & the below may include irrelevant stuff.
806 if (CRM_Utils_Array::value('minimum_fee', $membershipTypeDetails) > 0.0) {
807 if (((isset($form->_contributeMode) && $form->_contributeMode == 'notify') || !empty($form->_params['is_pay_later'])
808 ) &&
809 (($form->_values['is_monetary'] && $form->_amount > 0.0) ||
810 CRM_Utils_Array::value('record_contribution', $form->_params)
811 )
812 ) {
813 $pending = TRUE;
814 }
815 }
816 return $pending;
817 }
818
819 }