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