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