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