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