Merge pull request #5209 from davecivicrm/CRM-15958
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
1d86918a 29 * Class CRM_Core_Payment_BaseIPN.
6a488035
TO
30 */
31class CRM_Core_Payment_BaseIPN {
32
33 static $_now = NULL;
8196c759 34
c8aa607b 35 /**
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
38 * @var array
39 */
40 protected $_inputParameters = array();
41
937cf542
EM
42 protected $_isRecurring = FALSE;
43
44 protected $_isFirstOrLastRecurringPayment = FALSE;
353ffa53 45
8196c759 46 /**
fe482240 47 * Constructor.
8196c759 48 */
00be9182 49 public function __construct() {
6a488035
TO
50 self::$_now = date('YmdHis');
51 }
52
c8aa607b 53 /**
fe482240 54 * Store input array on the class.
77b97be7 55 *
c8aa607b 56 * @param array $parameters
77b97be7
EM
57 *
58 * @throws CRM_Core_Exception
c8aa607b 59 */
00be9182 60 public function setInputParameters($parameters) {
22e263ad 61 if (!is_array($parameters)) {
cc0c30cc 62 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 63 }
64 $this->_inputParameters = $parameters;
65 }
353ffa53 66
8196c759 67 /**
1d86918a
EM
68 * Validate incoming data.
69 *
70 * This function is intended to ensure that incoming data matches
8196c759 71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
76 *
6a0b768e
TO
77 * @param array $input
78 * Interpreted values from the values returned through the IPN.
79 * @param array $ids
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
1d86918a 87 *
5c766a0b 88 * @return bool
8196c759 89 */
00be9182 90 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
6a488035
TO
91
92 // make sure contact exists and is valid
5a9c68ac 93 $contact = new CRM_Contact_BAO_Contact();
6a488035
TO
94 $contact->id = $ids['contact'];
95 if (!$contact->find(TRUE)) {
92fcb95f 96 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
6a488035
TO
97 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
98 return FALSE;
99 }
100
101 // make sure contribution exists and is valid
5a9c68ac 102 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
103 $contribution->id = $ids['contribution'];
104 if (!$contribution->find(TRUE)) {
92fcb95f 105 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
6a488035
TO
106 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
107 return FALSE;
108 }
109 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
110
111 $objects['contact'] = &$contact;
112 $objects['contribution'] = &$contribution;
113 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
114 return FALSE;
115 }
a284891b
EM
116 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
117 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
118 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
119 if (isset($objects['contributionRecur'])) {
120 $objects['first_contribution'] = $objects['contribution'];
121 }
6a488035
TO
122 return TRUE;
123 }
124
8196c759 125 /**
fe482240 126 * Load objects related to contribution.
6a488035
TO
127 *
128 * @input array information from Payment processor
dd244018
EM
129 *
130 * @param $input
8196c759 131 * @param array $ids
132 * @param array $objects
6a0b768e
TO
133 * @param bool $required
134 * @param int $paymentProcessorID
8196c759 135 * @param array $error_handling
dd244018 136 *
5c766a0b 137 * @return bool
6a488035 138 */
00be9182 139 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
6a488035
TO
140 if (empty($error_handling)) {
141 // default options are that we log an error & echo it out
142 // note that we should refactor this error handling into error code @ some point
143 // but for now setting up enough separation so we can do unit tests
144 $error_handling = array(
145 'log_error' => 1,
146 'echo_error' => 1,
147 );
148 }
149 $ids['paymentProcessor'] = $paymentProcessorID;
150 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
151 $contribution = &$objects['contribution'];
152 }
153 else {
154 //legacy support - functions are 'used' to be able to pass in a DAO
155 $contribution = new CRM_Contribute_BAO_Contribution();
156 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
157 $contribution->find(TRUE);
158 $objects['contribution'] = &$contribution;
159 }
160 try {
161 $success = $contribution->loadRelatedObjects($input, $ids, $required);
162 }
353ffa53 163 catch (Exception $e) {
cc0c30cc 164 $success = FALSE;
a7488080 165 if (!empty($error_handling['log_error'])) {
6a488035
TO
166 CRM_Core_Error::debug_log_message($e->getMessage());
167 }
a7488080 168 if (!empty($error_handling['echo_error'])) {
6c552737 169 echo $e->getMessage();
6a488035 170 }
a7488080 171 if (!empty($error_handling['return_error'])) {
6a488035
TO
172 return array(
173 'is_error' => 1,
174 'error_message' => ($e->getMessage()),
175 );
176 }
177 }
178 $objects = array_merge($objects, $contribution->_relatedObjects);
179 return $success;
180 }
181
8196c759 182 /**
fe482240 183 * Set contribution to failed.
28de42d1 184 *
8196c759 185 * @param array $objects
186 * @param object $transaction
187 * @param array $input
28de42d1 188 *
5c766a0b 189 * @return bool
8196c759 190 */
00be9182 191 public function failed(&$objects, &$transaction, $input = array()) {
6a488035
TO
192 $contribution = &$objects['contribution'];
193 $memberships = array();
a7488080 194 if (!empty($objects['membership'])) {
6a488035
TO
195 $memberships = &$objects['membership'];
196 if (is_numeric($memberships)) {
197 $memberships = array($objects['membership']);
198 }
199 }
200
201 $addLineItems = FALSE;
202 if (empty($contribution->id)) {
203 $addLineItems = TRUE;
204 }
205 $participant = &$objects['participant'];
206
71d085fe 207 //CRM-15546
353ffa53
TO
208 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
209 'labelColumn' => 'name',
af9b09df 210 'flip' => 1,
353ffa53 211 ));
5a9c68ac
PJ
212 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
213 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
214 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
71d085fe 215 $contribution->contribution_status_id = $contributionStatuses['Failed'];
6a488035
TO
216 $contribution->save();
217
28de42d1 218 // Add line items for recurring payments.
a7488080 219 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
34a100a7 220 $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
221 }
222
8381af80 223 //add new soft credit against current contribution id and
6357981e 224 //copy initial contribution custom fields for recurring contributions
a7488080 225 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
8381af80 226 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
227 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
228 }
229
a7488080 230 if (empty($input['skipComponentSync'])) {
6a488035 231 if (!empty($memberships)) {
5968aa47 232 // if transaction is failed then set "Cancelled" as membership status
353ffa53
TO
233 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
234 'labelColumn' => 'name',
af9b09df 235 'flip' => 1,
353ffa53 236 ));
6a488035
TO
237 foreach ($memberships as $membership) {
238 if ($membership) {
71d085fe 239 $membership->status_id = $membershipStatuses['Cancelled'];
6a488035 240 $membership->save();
d63f4fc3 241
6a488035 242 //update related Memberships.
71d085fe 243 $params = array('status_id' => $membershipStatuses['Cancelled']);
6a488035
TO
244 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
245 }
246 }
247 }
d63f4fc3 248
6a488035 249 if ($participant) {
353ffa53
TO
250 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
251 'labelColumn' => 'name',
af9b09df 252 'flip' => 1,
353ffa53 253 ));
71d085fe 254 $participant->status_id = $participantStatuses['Cancelled'];
6a488035
TO
255 $participant->save();
256 }
257 }
258
259 $transaction->commit();
260 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
261 //echo "Success: Setting contribution status to failed<p>";
262 return TRUE;
263 }
264
8196c759 265 /**
fe482240 266 * Handled pending contribution status.
1d86918a 267 *
8196c759 268 * @param array $objects
269 * @param object $transaction
1d86918a 270 *
5c766a0b 271 * @return bool
8196c759 272 */
00be9182 273 public function pending(&$objects, &$transaction) {
6a488035
TO
274 $transaction->commit();
275 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
276 echo "Success: Returning since contribution status is pending<p>";
277 return TRUE;
278 }
279
6c786a9b 280 /**
1d86918a
EM
281 * Process cancelled payment outcome.
282 *
6c786a9b
EM
283 * @param $objects
284 * @param $transaction
285 * @param array $input
286 *
287 * @return bool
288 */
00be9182 289 public function cancelled(&$objects, &$transaction, $input = array()) {
6a488035
TO
290 $contribution = &$objects['contribution'];
291 $memberships = &$objects['membership'];
292 if (is_numeric($memberships)) {
293 $memberships = array($objects['membership']);
294 }
295
296 $participant = &$objects['participant'];
297 $addLineItems = FALSE;
298 if (empty($contribution->id)) {
299 $addLineItems = TRUE;
300 }
353ffa53
TO
301 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
302 'labelColumn' => 'name',
af9b09df 303 'flip' => 1,
353ffa53 304 ));
71d085fe 305 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
306 $contribution->cancel_date = self::$_now;
307 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
308 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
309 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
310 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
311 $contribution->save();
312
313 //add lineitems for recurring payments
a7488080 314 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
34a100a7 315 $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
316 }
317
8381af80 318 //add new soft credit against current $contribution and
6357981e 319 //copy initial contribution custom fields for recurring contributions
a7488080 320 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
8381af80 321 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
322 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
323 }
324
a7488080 325 if (empty($input['skipComponentSync'])) {
6a488035 326 if (!empty($memberships)) {
353ffa53
TO
327 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
328 'labelColumn' => 'name',
af9b09df 329 'flip' => 1,
353ffa53 330 ));
6a488035
TO
331 foreach ($memberships as $membership) {
332 if ($membership) {
71d085fe 333 $membership->status_id = $membershipStatuses['Cancelled'];
6a488035 334 $membership->save();
d63f4fc3 335
6a488035 336 //update related Memberships.
71d085fe 337 $params = array('status_id' => $membershipStatuses['Cancelled']);
6a488035
TO
338 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
339 }
340 }
341 }
d63f4fc3 342
6a488035 343 if ($participant) {
353ffa53
TO
344 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
345 'labelColumn' => 'name',
af9b09df 346 'flip' => 1,
353ffa53 347 ));
71d085fe 348 $participant->status_id = $participantStatuses['Cancelled'];
6a488035
TO
349 $participant->save();
350 }
351 }
352 $transaction->commit();
353 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
354 //echo "Success: Setting contribution status to cancelled<p>";
355 return TRUE;
356 }
357
6c786a9b 358 /**
1d86918a
EM
359 * Rollback unhandled outcomes.
360 *
6c786a9b
EM
361 * @param $objects
362 * @param $transaction
363 *
364 * @return bool
365 */
00be9182 366 public function unhandled(&$objects, &$transaction) {
6a488035 367 $transaction->rollback();
2d8851f6
EM
368 CRM_Core_Error::debug_log_message("returning since contribution status: is not handled");
369 echo "Failure: contribution status is not handled<p>";
6a488035
TO
370 return FALSE;
371 }
372
6c786a9b 373 /**
3ccde016 374 * Jumbled up function.
1d86918a 375 *
3ccde016
EM
376 * The purpose of this function is to transition a pending transaction to Completed including updating any
377 * related entities.
378 *
379 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
380 * updating related entities.
381 *
382 * It is recommended to avoid calling this function directly and call the api functions:
383 * - contribution.completetransaction
384 * - contribution.repeattransaction
385 *
386 * These functions are the focus of testing efforts and more accurately reflect the division of roles
387 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
388 * and from there it should be possible to pass off transaction management.)
389 *
390 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
391 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
392 *
393 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
394 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
395 * a shared function that updates related components.
396 *
397 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
398 * IPN class is better accessed through the api which de-jumbles it a bit.
399 *
400 * e.g the payment class can have a function like (based on Omnipay extension):
401 *
402 * public function handlePaymentNotification() {
403 * $response = $this->getValidatedOutcome();
404 * if ($response->isSuccessful()) {
405 * try {
406 * // @todo check if it is a repeat transaction & call repeattransaction instead.
407 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
408 * }
409 * catch (CiviCRM_API3_Exception $e) {
410 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
411 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
412 * have occurred. Please check your receipt is correct');
413 * $this->redirectOrExit('success');
414 * }
415 * elseif ($this->transaction_id) {
416 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
417 * 'Failed'));
418 * }
419 *
420 * @param array $input
421 * @param array $ids
422 * @param array $objects
6c786a9b
EM
423 * @param $transaction
424 * @param bool $recur
425 */
00be9182 426 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
6a488035 427 $contribution = &$objects['contribution'];
a284891b
EM
428
429 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
430
6a488035
TO
431 $memberships = &$objects['membership'];
432 if (is_numeric($memberships)) {
433 $memberships = array($objects['membership']);
434 }
353ffa53 435 $participant = &$objects['participant'];
1d86918a 436
353ffa53 437 $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
6a488035
TO
438 $recurContrib = &$objects['contributionRecur'];
439
440 $values = array();
441 $source = NULL;
442 if ($input['component'] == 'contribute') {
443 if ($contribution->contribution_page_id) {
444 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
445 $source = ts('Online Contribution') . ': ' . $values['title'];
446 }
447 elseif ($recurContrib && $recurContrib->id) {
448 $contribution->contribution_page_id = NULL;
449 $values['amount'] = $recurContrib->amount;
450 $values['financial_type_id'] = $objects['contributionType']->id;
451 $values['title'] = $source = ts('Offline Recurring Contribution');
6a488035
TO
452 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
453 $values['receipt_from_name'] = $domainValues[0];
454 $values['receipt_from_email'] = $domainValues[1];
455 }
9b873358 456 if ($recurContrib && $recurContrib->id) {
2b5b0279 457 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
458 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
459 }
6a488035
TO
460
461 $contribution->source = $source;
a7488080 462 if (!empty($values['is_email_receipt'])) {
6a488035
TO
463 $contribution->receipt_date = self::$_now;
464 }
465
466 if (!empty($memberships)) {
2aa397bc 467 $membershipsUpdate = array();
6a488035
TO
468 foreach ($memberships as $membershipTypeIdKey => $membership) {
469 if ($membership) {
470 $format = '%Y%m%d';
471
472 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
473 $membership->membership_type_id,
474 $membership->is_test, $membership->id
475 );
476
477 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
478 // this picks up membership type changes during renewals
479 $sql = "
480SELECT membership_type_id
481FROM civicrm_membership_log
482WHERE membership_id=$membership->id
483ORDER BY id DESC
484LIMIT 1;";
2177d15c 485 $dao = new CRM_Core_DAO();
6a488035
TO
486 $dao->query($sql);
487 if ($dao->fetch()) {
488 if (!empty($dao->membership_type_id)) {
489 $membership->membership_type_id = $dao->membership_type_id;
490 $membership->save();
491 }
492 // else fall back to using current membership type
493 }
494 // else fall back to using current membership type
495 $dao->free();
496
a284891b 497 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
6a488035
TO
498 if ($currentMembership) {
499 /*
500 * Fixed FOR CRM-4433
501 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
502 * when Contribution mode is notify and membership is for renewal )
503 */
504 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
505
2243fe93
EM
506 // @todo - we should pass membership_type_id instead of null here but not
507 // adding as not sure of testing
6a488035 508 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
2243fe93 509 $changeToday, NULL, $num_terms
6a488035 510 );
2243fe93 511
6a488035
TO
512 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
513 }
514 else {
29347f3d 515 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
6a488035
TO
516 }
517
518 //get the status for membership.
519 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
520 $dates['end_date'],
521 $dates['join_date'],
522 'today',
5f11bbcc
EM
523 TRUE,
524 $membership->membership_type_id,
525 (array) $membership
6a488035
TO
526 );
527
2aa397bc 528 $formatedParams = array(
353ffa53 529 'status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
6a488035
TO
530 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format),
531 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format),
532 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format),
533 );
534 //we might be renewing membership,
535 //so make status override false.
536 $formatedParams['is_override'] = FALSE;
537 $membership->copyValues($formatedParams);
538 $membership->save();
539
540 //updating the membership log
541 $membershipLog = array();
542 $membershipLog = $formatedParams;
543
544 $logStartDate = $formatedParams['start_date'];
a7488080 545 if (!empty($dates['log_start_date'])) {
6a488035
TO
546 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
547 $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
548 }
549
550 $membershipLog['start_date'] = $logStartDate;
551 $membershipLog['membership_id'] = $membership->id;
552 $membershipLog['modified_id'] = $membership->contact_id;
553 $membershipLog['modified_date'] = date('Ymd');
554 $membershipLog['membership_type_id'] = $membership->membership_type_id;
555
556 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
557
558 //update related Memberships.
559 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
d63f4fc3 560
6a488035
TO
561 //update the membership type key of membership relatedObjects array
562 //if it has changed after membership update
563 if ($membershipTypeIdKey != $membership->membership_type_id) {
564 $membershipsUpdate[$membership->membership_type_id] = $membership;
565 $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
566 unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
567 unset($memberships[$membershipTypeIdKey]);
568 }
569 }
570 }
571 //update the memberships object with updated membershipTypeId data
572 //if membershipTypeId has changed after membership update
573 if (!empty($membershipsUpdate)) {
574 $memberships = $memberships + $membershipsUpdate;
575 }
576 }
577 }
578 else {
579 // event
580 $eventParams = array('id' => $objects['event']->id);
581 $values['event'] = array();
582
583 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
584
585 //get location details
586 $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
587 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
588
589 $ufJoinParams = array(
590 'entity_table' => 'civicrm_event',
353ffa53
TO
591 'entity_id' => $ids['event'],
592 'module' => 'CiviEvent',
6a488035 593 );
d63f4fc3 594
6a488035 595 list($custom_pre_id,
353ffa53
TO
596 $custom_post_ids
597 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
d63f4fc3 598
6a488035
TO
599 $values['custom_pre_id'] = $custom_pre_id;
600 $values['custom_post_id'] = $custom_post_ids;
e1eb31b5
RN
601 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
602 //and cases involving status updation through ipn
603 $values['totalAmount'] = $input['amount'];
6a488035
TO
604
605 $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
606
607 if ($values['event']['is_email_confirm']) {
608 $contribution->receipt_date = self::$_now;
609 $values['is_email_receipt'] = 1;
610 }
a7488080 611 if (empty($input['skipComponentSync'])) {
353ffa53
TO
612 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
613 'labelColumn' => 'name',
af9b09df 614 'flip' => 1,
353ffa53 615 ));
71d085fe 616 $participant->status_id = $participantStatuses['Registered'];
6a488035
TO
617 }
618 $participant->save();
619 }
620
621 if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 &&
622 CRM_Utils_Array::value('fee_amount', $input, 0) != 0
623 ) {
624 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
625 }
5fa7c328
EM
626 // This complete transaction function is being overloaded to create new contributions too.
627 // here we record if it is a new contribution.
628 // @todo separate the 2 more appropriately.
629 $isNewContribution = FALSE;
6a488035 630 if (empty($contribution->id)) {
5fa7c328 631 $isNewContribution = TRUE;
6a488035 632 }
353ffa53
TO
633 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
634 'labelColumn' => 'name',
af9b09df 635 'flip' => 1,
353ffa53 636 ));
500d35ec
EM
637
638 // @todo this section should call the api in order to have hooks called &
639 // because all this 'messiness' setting variables could be avoided
640 // by letting the api resolve pseudoconstants & copy set values and format dates.
71d085fe 641 $contribution->contribution_status_id = $contributionStatuses['Completed'];
6a488035 642 $contribution->is_test = $input['is_test'];
500d35ec
EM
643
644 // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
645 if (isset($input['net_amount'])) {
646 $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
647 }
648 if (isset($input['net_amount'])) {
649 $contribution->net_amount = $input['net_amount'];
650 }
651
6a488035
TO
652 $contribution->trxn_id = $input['trxn_id'];
653 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
654 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
46fa5206 655 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
6a488035
TO
656 $contribution->cancel_date = 'null';
657
a7488080 658 if (!empty($input['check_number'])) {
6a488035
TO
659 $contribution->check_number = $input['check_number'];
660 }
661
a7488080 662 if (!empty($input['payment_instrument_id'])) {
6a488035
TO
663 $contribution->payment_instrument_id = $input['payment_instrument_id'];
664 }
d63f4fc3 665
d97c96dc 666 if (!empty($contribution->id)) {
6a488035
TO
667 $contributionId['id'] = $contribution->id;
668 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
669 }
670 $contribution->save();
671
28de42d1 672 // Add new soft credit against current $contribution.
8381af80 673 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
674 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
675 }
676
5fa7c328
EM
677 //add line items for recurring payments
678 if (!empty($contribution->contribution_recur_id)) {
679 if ($isNewContribution) {
680 $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
34a100a7
EM
681 }
682 else {
683 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
684 $input['line_item'] = array();
685 }
6a488035
TO
686 }
687
6357981e
PJ
688 //copy initial contribution custom fields for recurring contributions
689 if ($recurContrib && $recurContrib->id) {
690 $this->copyCustomValues($recurContrib->id, $contribution->id);
691 }
692
6a488035
TO
693 // next create the transaction record
694 $paymentProcessor = $paymentProcessorId = '';
695 if (isset($objects['paymentProcessor'])) {
696 if (is_array($objects['paymentProcessor'])) {
697 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
698 $paymentProcessorId = $objects['paymentProcessor']['id'];
699 }
700 else {
701 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
702 $paymentProcessorId = $objects['paymentProcessor']->id;
703 }
704 }
4d34aefa 705 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
706 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
707 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
708 // it would be good if someone added some comments or refactored this
6a488035 709 if ($contribution->id) {
353ffa53
TO
710 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
711 'labelColumn' => 'name',
af9b09df 712 'flip' => 1,
353ffa53 713 ));
29d98e13 714 if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
2aa397bc 715 $input['payment_processor'] = $paymentProcessorId;
6a488035 716 }
71d085fe 717 $input['contribution_status_id'] = $contributionStatuses['Completed'];
6a488035
TO
718 $input['total_amount'] = $input['amount'];
719 $input['contribution'] = $contribution;
a1f5ffcc 720 $input['financial_type_id'] = $contribution->financial_type_id;
721
a7488080 722 if (!empty($contribution->_relatedObjects['participant'])) {
6a488035
TO
723 $input['contribution_mode'] = 'participant';
724 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
0ba0addf 725 $input['skipLineItem'] = 1;
f92fd420 726 }
d2035566
PN
727 elseif (!empty($contribution->_relatedObjects['membership'])) {
728 $input['skipLineItem'] = TRUE;
729 $input['contribution_mode'] = 'membership';
730 }
4d34aefa 731 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
34a100a7 732 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
4d34aefa 733 // and since the contribution is saved prior to this line there is always a contribution-id,
734 // however there is never a prevContribution (which appears to mean original contribution not previous
735 // contribution - or preUpdateContributionObject most accurately)
736 // so, this is always called & only appears to succeed when prevContribution exists - which appears
737 // to mean "are we updating an exisitng pending contribution"
738 //I was able to make the unit test complete as fataling here doesn't prevent
739 // the contribution being created - but activities would not be created or emails sent
34a100a7 740
6a488035
TO
741 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
742 }
743
744 self::updateRecurLinkedPledge($contribution);
745
746 // create an activity record
747 if ($input['component'] == 'contribute') {
748 //CRM-4027
749 $targetContactID = NULL;
a7488080 750 if (!empty($ids['related_contact'])) {
6a488035
TO
751 $targetContactID = $contribution->contact_id;
752 $contribution->contact_id = $ids['related_contact'];
753 }
754 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
755 // event
756 }
757 else {
758 CRM_Activity_BAO_Activity::addActivity($participant);
759 }
760
761 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
762 $transaction->commit();
763
764 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
765 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
766 if (!array_key_exists('is_email_receipt', $values) ||
767 $values['is_email_receipt'] == 1
768 ) {
769 self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
bf014492 770 CRM_Core_Error::debug_log_message("Receipt sent");
6a488035
TO
771 }
772
bf014492 773 CRM_Core_Error::debug_log_message("Success: Database updated");
937cf542
EM
774 if ($this->_isRecurring) {
775 $this->sendRecurringStartOrEndNotification($ids, $recur);
776 }
6a488035
TO
777 }
778
6c786a9b 779 /**
1d86918a
EM
780 * Get site billing ID.
781 *
782 * @param array $ids
6c786a9b
EM
783 *
784 * @return bool
785 */
00be9182 786 public function getBillingID(&$ids) {
6a488035 787 // get the billing location type
180409a4 788 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1d86918a 789 // CRM-8108 remove the ts around the Billing location type
6a488035
TO
790 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
791 $ids['billing'] = array_search('Billing', $locationTypes);
792 if (!$ids['billing']) {
793 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
794 echo "Failure: Could not find billing location type<p>";
795 return FALSE;
796 }
797 return TRUE;
798 }
799
c490a46a 800 /**
1d86918a
EM
801 * Send receipt from contribution.
802 *
803 * Note that the compose message part has been moved to contribution
6a488035
TO
804 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
805 *
6a0b768e
TO
806 * @param array $input
807 * Incoming data from Payment processor.
808 * @param array $ids
809 * Related object IDs.
6c786a9b 810 * @param $objects
6a0b768e
TO
811 * @param array $values
812 * Values related to objects that have already been loaded.
813 * @param bool $recur
814 * Is it part of a recurring contribution.
815 * @param bool $returnMessageText
816 * Should text be returned instead of sent. This.
16b10e64 817 * is because the function is also used to generate pdfs
6c786a9b 818 *
c490a46a 819 * @return array
6c786a9b 820 */
00be9182 821 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
6a488035
TO
822 $contribution = &$objects['contribution'];
823 $input['is_recur'] = $recur;
824 // set receipt from e-mail and name in value
825 if (!$returnMessageText) {
826 $session = CRM_Core_Session::singleton();
827 $userID = $session->get('userID');
828 if (!empty($userID)) {
829 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
830 $values['receipt_from_email'] = $userEmail;
831 $values['receipt_from_name'] = $userName;
832 }
833 }
834 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
835 }
836
937cf542 837 /**
fe482240 838 * Send start or end notification for recurring payments.
1d86918a
EM
839 *
840 * @param array $ids
937cf542
EM
841 * @param $recur
842 */
00be9182 843 public function sendRecurringStartOrEndNotification($ids, $recur) {
937cf542
EM
844 if ($this->_isFirstOrLastRecurringPayment) {
845 $autoRenewMembership = FALSE;
846 if ($recur->id &&
847 isset($ids['membership']) && $ids['membership']
848 ) {
849 $autoRenewMembership = TRUE;
850 }
851
852 //send recurring Notification email for user
853 CRM_Contribute_BAO_ContributionPage::recurringNotify($this->_isFirstOrLastRecurringPayment,
854 $ids['contact'],
855 $ids['contributionPage'],
856 $recur,
857 $autoRenewMembership
858 );
859 }
860 }
861
8196c759 862 /**
1d86918a
EM
863 * Update contribution status.
864 *
865 * @deprecated
866 * This is only called from one place in the code &
8196c759 867 * it is unclear whether it is a function on the way in or on the way out
868 *
72b3a70c 869 * @param array $params
1d86918a 870 *
a1a2a83d 871 * @return void|NULL|int
8196c759 872 */
00be9182 873 public function updateContributionStatus(&$params) {
6a488035 874 // get minimum required values.
353ffa53
TO
875 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
876 $componentId = CRM_Utils_Array::value('component_id', $params);
877 $componentName = CRM_Utils_Array::value('componentName', $params);
6a488035
TO
878 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
879
880 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
a1a2a83d 881 return NULL;
6a488035
TO
882 }
883
884 $input = $ids = $objects = array();
885
886 //get the required ids.
887 $ids['contribution'] = $contributionId;
888
889 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
890 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
891 $contributionId,
892 'contact_id'
893 );
894 }
895
896 if ($componentName == 'Event') {
897 $name = 'event';
898 $ids['participant'] = $componentId;
899
900 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
901 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
902 $componentId,
903 'event_id'
904 );
905 }
906 }
907
908 if ($componentName == 'Membership') {
909 $name = 'contribute';
910 $ids['membership'] = $componentId;
911 }
912 $ids['contributionPage'] = NULL;
913 $ids['contributionRecur'] = NULL;
914 $input['component'] = $name;
915
916 $baseIPN = new CRM_Core_Payment_BaseIPN();
917 $transaction = new CRM_Core_Transaction();
918
919 // reset template values.
920 $template = CRM_Core_Smarty::singleton();
921 $template->clearTemplateVars();
922
923 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
924 CRM_Core_Error::fatal();
925 }
926
927 $contribution = &$objects['contribution'];
928
353ffa53
TO
929 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
930 'labelColumn' => 'name',
af9b09df 931 'flip' => 1,
353ffa53 932 ));
6a488035 933 $input['skipComponentSync'] = CRM_Utils_Array::value('skipComponentSync', $params);
71d085fe 934 if ($statusId == $contributionStatuses['Cancelled']) {
6a488035
TO
935 $baseIPN->cancelled($objects, $transaction, $input);
936 $transaction->commit();
937 return $statusId;
938 }
71d085fe 939 elseif ($statusId == $contributionStatuses['Failed']) {
6a488035
TO
940 $baseIPN->failed($objects, $transaction, $input);
941 $transaction->commit();
942 return $statusId;
943 }
944
945 // status is not pending
71d085fe 946 if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
6a488035
TO
947 $transaction->commit();
948 return;
949 }
950
951 //set values for ipn code.
952 foreach (array(
353ffa53
TO
953 'fee_amount',
954 'check_number',
af9b09df 955 'payment_instrument_id',
353ffa53 956 ) as $field) {
6a488035
TO
957 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
958 $input[$field] = $contribution->$field;
959 }
960 }
961 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
962 $input['trxn_id'] = $contribution->invoice_id;
963 }
964 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
965 $input['amount'] = $contribution->total_amount;
966 }
967 $input['is_test'] = $contribution->is_test;
968 $input['net_amount'] = $contribution->net_amount;
8cc574cf 969 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
6a488035
TO
970 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
971 }
972
973 //complete the contribution.
974 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
975
976 // reset template values before processing next transactions
977 $template->clearTemplateVars();
978
979 return $statusId;
980 }
981
d424ffde 982 /**
fe482240 983 * Update pledge associated with a recurring contribution.
6a488035
TO
984 *
985 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
986 *
987 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
988 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
989 * it should be assumed they
990 * do so with the intention that all payments will be linked
991 *
992 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
993 * If not the contribution will also need to be linked to the pledge
d424ffde
CW
994 *
995 * @param CRM_Contribute_BAO_Contribution $contribution
6c786a9b 996 */
00be9182 997 public function updateRecurLinkedPledge(&$contribution) {
6a488035 998 $returnProperties = array('id', 'pledge_id');
353ffa53 999 $paymentDetails = $paymentIDs = array();
6a488035
TO
1000
1001 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
353ffa53
TO
1002 $paymentDetails, $returnProperties
1003 )
1004 ) {
6a488035
TO
1005 foreach ($paymentDetails as $key => $value) {
1006 $paymentIDs[] = $value['id'];
1007 $pledgeId = $value['pledge_id'];
1008 }
1009 }
1010 else {
1011 //payment is not already linked - if it is linked with a pledge we need to create a link.
1012 // return if it is not recurring contribution
1013 if (!$contribution->contribution_recur_id) {
1014 return;
1015 }
1016
1017 $relatedContributions = new CRM_Contribute_DAO_Contribution();
1018 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
1019 $relatedContributions->find();
1020
1021 while ($relatedContributions->fetch()) {
1022 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
1023 $paymentDetails, $returnProperties
1024 );
1025 }
1026
1027 if (empty($paymentDetails)) {
1028 // payment is not linked with a pledge and neither are any other contributions on this
1029 return;
1030 }
1031
1032 foreach ($paymentDetails as $key => $value) {
1033 $pledgeId = $value['pledge_id'];
1034 }
1035
1036 // we have a pledge now we need to get the oldest unpaid payment
1037 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
9b873358 1038 if (empty($paymentDetails['id'])) {
e3f3156b 1039 // we can assume this pledge is now completed
1040 // return now so we don't create a core error & roll back
1041 return;
1042 }
6a488035
TO
1043 $paymentDetails['contribution_id'] = $contribution->id;
1044 $paymentDetails['status_id'] = $contribution->contribution_status_id;
1045 $paymentDetails['actual_amount'] = $contribution->total_amount;
1046
1047 // put contribution against it
1048 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
1049 $paymentIDs[] = $payment->id;
1050 }
1051
1052 // update pledge and corresponding payment statuses
1053 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
1054 NULL, $contribution->total_amount
1055 );
1056 }
1057
6c786a9b 1058 /**
1d86918a
EM
1059 * Add line items for recurring contribution.
1060 *
c490a46a 1061 * @param int $recurId
34a100a7
EM
1062 * @param $contribution
1063 *
34a100a7 1064 * @return array
6c786a9b 1065 */
00be9182 1066 public function addRecurLineItems($recurId, $contribution) {
34a100a7
EM
1067 $lineSets = array();
1068
1069 $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1070 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
1071 if (!empty($lineItems)) {
1072 foreach ($lineItems as $key => $value) {
1073 $priceField = new CRM_Price_DAO_PriceField();
1074 $priceField->id = $value['price_field_id'];
1075 $priceField->find(TRUE);
1076 $lineSets[$priceField->price_set_id][] = $value;
1077 if ($value['entity_table'] == 'civicrm_membership') {
1078 try {
353ffa53
TO
1079 civicrm_api3('membership_payment', 'create', array(
1080 'membership_id' => $value['entity_id'],
af9b09df 1081 'contribution_id' => $contribution->id,
353ffa53 1082 ));
34a100a7
EM
1083 }
1084 catch (CiviCRM_API3_Exception $e) {
1085 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
1086 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
1087 }
6a488035
TO
1088 }
1089 }
6a488035 1090 }
34a100a7
EM
1091 else {
1092 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
1093 }
1094 return $lineSets;
6a488035 1095 }
6a488035 1096
6c786a9b 1097 /**
1d86918a
EM
1098 * Copy custom data of the initial contribution into its recurring contributions.
1099 *
100fef9d
CW
1100 * @param int $recurId
1101 * @param int $targetContributionId
6c786a9b 1102 */
00be9182 1103 public function copyCustomValues($recurId, $targetContributionId) {
6357981e
PJ
1104 if ($recurId && $targetContributionId) {
1105 // get the initial contribution id of recur id
1106 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1107
1108 // if the same contribution is being proccessed then return
1109 if ($sourceContributionId == $targetContributionId) {
1110 return;
1111 }
1112 // check if proper recurring contribution record is being processed
1113 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
1114 if ($targetConRecurId != $recurId) {
1115 return;
1116 }
1117
1118 // copy custom data
1119 $extends = array('Contribution');
1120 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
1121 if ($groupTree) {
1122 foreach ($groupTree as $groupID => $group) {
1123 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1124 foreach ($group['fields'] as $fieldID => $field) {
1125 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1126 }
1127 }
1128
1129 foreach ($table as $tableName => $tableColumns) {
353ffa53 1130 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
6357981e 1131 $tableColumns[0] = $targetContributionId;
353ffa53
TO
1132 $select = 'SELECT ' . implode(', ', $tableColumns);
1133 $from = ' FROM ' . $tableName;
1134 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1135 $query = $insert . $select . $from . $where;
1136 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
6357981e
PJ
1137 }
1138 }
1139 }
1140 }
8381af80 1141
6c786a9b 1142 /**
1d86918a
EM
1143 * Add soft credit to for recurring payment.
1144 *
fe482240 1145 * copy soft credit record of first recurring contribution.
4f1f1f2a
CW
1146 * and add new soft credit against $targetContributionId
1147 *
100fef9d
CW
1148 * @param int $recurId
1149 * @param int $targetContributionId
6c786a9b 1150 */
00be9182 1151 public function addrecurSoftCredit($recurId, $targetContributionId) {
8381af80 1152 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1d86918a 1153 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
8381af80 1154
1d86918a 1155 // Check if first recurring contribution has any associated soft credit.
8381af80 1156 if ($soft_contribution->find(TRUE)) {
1157 $soft_contribution->contribution_id = $targetContributionId;
1158 unset($soft_contribution->id);
1159 $soft_contribution->save();
1160 }
1161 }
96025800 1162
b2b0530a 1163}