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