Merge pull request #2775 from ErichBSchulz/patch-3
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Core_Payment_BaseIPN {
36
37 static $_now = NULL;
8196c759 38
c8aa607b 39 /**
40 * Input parameters from payment processor. Store these so that
41 * the code does not need to keep retrieving from the http request
42 * @var array
43 */
44 protected $_inputParameters = array();
45
8196c759 46 /**
47 * Constructor
48 */
6a488035
TO
49 function __construct() {
50 self::$_now = date('YmdHis');
51 }
52
c8aa607b 53 /**
54 * Store input array on the class
55 * @param array $parameters
56 * @throws CRM_Core_Exceptions
57 */
58 function setInputParameters($parameters) {
59 if(!is_array($parameters)) {
cc0c30cc 60 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 61 }
62 $this->_inputParameters = $parameters;
63 }
8196c759 64 /**
65 * Validate incoming data. This function is intended to ensure that incoming data matches
66 * It provides a form of pseudo-authentication - by checking the calling fn already knows
67 * the correct contact id & contribution id (this can be problematic when that has changed in
68 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
69 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
70 * and didn't update your IPN URL.
71 *
72 * @param array $input interpreted values from the values returned through the IPN
73 * @param array $ids more interpreted values (ids) from the values returned through the IPN
74 * @param array $objects an empty array that will be populated with loaded object
75 * @param boolean $required boolean Return FALSE if the relevant objects don't exist
76 * @param integer $paymentProcessorID Id of the payment processor ID in use
77 * @return boolean
78 */
6a488035
TO
79 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
80
81 // make sure contact exists and is valid
5a9c68ac 82 $contact = new CRM_Contact_BAO_Contact();
6a488035
TO
83 $contact->id = $ids['contact'];
84 if (!$contact->find(TRUE)) {
85 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
86 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
87 return FALSE;
88 }
89
90 // make sure contribution exists and is valid
5a9c68ac 91 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
92 $contribution->id = $ids['contribution'];
93 if (!$contribution->find(TRUE)) {
94 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
95 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
96 return FALSE;
97 }
98 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
99
100 $objects['contact'] = &$contact;
101 $objects['contribution'] = &$contribution;
102 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
103 return FALSE;
104 }
105
106 return TRUE;
107 }
108
8196c759 109 /**
6a488035
TO
110 * Load objects related to contribution
111 *
112 * @input array information from Payment processor
8196c759 113 * @param array $ids
114 * @param array $objects
115 * @param boolean $required
116 * @param integer $paymentProcessorID
117 * @param array $error_handling
118 * @return multitype:number NULL |boolean
6a488035
TO
119 */
120 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
121 if (empty($error_handling)) {
122 // default options are that we log an error & echo it out
123 // note that we should refactor this error handling into error code @ some point
124 // but for now setting up enough separation so we can do unit tests
125 $error_handling = array(
126 'log_error' => 1,
127 'echo_error' => 1,
128 );
129 }
130 $ids['paymentProcessor'] = $paymentProcessorID;
131 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
132 $contribution = &$objects['contribution'];
133 }
134 else {
135 //legacy support - functions are 'used' to be able to pass in a DAO
136 $contribution = new CRM_Contribute_BAO_Contribution();
137 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
138 $contribution->find(TRUE);
139 $objects['contribution'] = &$contribution;
140 }
141 try {
142 $success = $contribution->loadRelatedObjects($input, $ids, $required);
143 }
c8aa607b 144 catch(Exception $e) {
cc0c30cc 145 $success = FALSE;
a7488080 146 if (!empty($error_handling['log_error'])) {
6a488035
TO
147 CRM_Core_Error::debug_log_message($e->getMessage());
148 }
a7488080 149 if (!empty($error_handling['echo_error'])) {
6a488035
TO
150 echo ($e->getMessage());
151 }
a7488080 152 if (!empty($error_handling['return_error'])) {
6a488035
TO
153 return array(
154 'is_error' => 1,
155 'error_message' => ($e->getMessage()),
156 );
157 }
158 }
159 $objects = array_merge($objects, $contribution->_relatedObjects);
160 return $success;
161 }
162
8196c759 163 /**
164 * Set contribution to failed
165 * @param array $objects
166 * @param object $transaction
167 * @param array $input
168 * @return boolean
169 */
6a488035
TO
170 function failed(&$objects, &$transaction, $input = array()) {
171 $contribution = &$objects['contribution'];
172 $memberships = array();
a7488080 173 if (!empty($objects['membership'])) {
6a488035
TO
174 $memberships = &$objects['membership'];
175 if (is_numeric($memberships)) {
176 $memberships = array($objects['membership']);
177 }
178 }
179
180 $addLineItems = FALSE;
181 if (empty($contribution->id)) {
182 $addLineItems = TRUE;
183 }
184 $participant = &$objects['participant'];
185
186 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
5a9c68ac
PJ
187 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
188 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
189 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
6a488035
TO
190 $contribution->contribution_status_id = array_search('Failed', $contributionStatus);
191 $contribution->save();
192
193 //add lineitems for recurring payments
a7488080 194 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
bf45dbe8 195 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, CRM_Core_DAO::$_nullArray);
6a488035
TO
196 }
197
8381af80 198 //add new soft credit against current contribution id and
6357981e 199 //copy initial contribution custom fields for recurring contributions
a7488080 200 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
8381af80 201 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
202 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
203 }
204
a7488080 205 if (empty($input['skipComponentSync'])) {
6a488035 206 if (!empty($memberships)) {
5968aa47
C
207 // if transaction is failed then set "Cancelled" as membership status
208 $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus());
6a488035
TO
209 foreach ($memberships as $membership) {
210 if ($membership) {
5968aa47 211 $membership->status_id = $cancelStatusId;
6a488035 212 $membership->save();
d63f4fc3 213
6a488035 214 //update related Memberships.
5968aa47 215 $params = array('status_id' => $cancelStatusId);
6a488035
TO
216 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
217 }
218 }
219 }
d63f4fc3 220
6a488035
TO
221 if ($participant) {
222 $participant->status_id = 4;
223 $participant->save();
224 }
225 }
226
227 $transaction->commit();
228 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
229 //echo "Success: Setting contribution status to failed<p>";
230 return TRUE;
231 }
232
8196c759 233 /**
234 * Handled pending contribution status
235 * @param array $objects
236 * @param object $transaction
237 * @return boolean
238 */
6a488035
TO
239 function pending(&$objects, &$transaction) {
240 $transaction->commit();
241 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
242 echo "Success: Returning since contribution status is pending<p>";
243 return TRUE;
244 }
245
246 function cancelled(&$objects, &$transaction, $input = array()) {
247 $contribution = &$objects['contribution'];
248 $memberships = &$objects['membership'];
249 if (is_numeric($memberships)) {
250 $memberships = array($objects['membership']);
251 }
252
253 $participant = &$objects['participant'];
254 $addLineItems = FALSE;
255 if (empty($contribution->id)) {
256 $addLineItems = TRUE;
257 }
258 $contribution->contribution_status_id = 3;
259 $contribution->cancel_date = self::$_now;
260 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
261 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
262 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
263 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
264 $contribution->save();
265
266 //add lineitems for recurring payments
a7488080 267 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
bf45dbe8 268 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, CRM_Core_DAO::$_nullArray);
6a488035
TO
269 }
270
8381af80 271 //add new soft credit against current $contribution and
6357981e 272 //copy initial contribution custom fields for recurring contributions
a7488080 273 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
8381af80 274 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
275 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
276 }
277
a7488080 278 if (empty($input['skipComponentSync'])) {
6a488035
TO
279 if (!empty($memberships)) {
280 foreach ($memberships as $membership) {
281 if ($membership) {
282 $membership->status_id = 6;
283 $membership->save();
d63f4fc3 284
6a488035
TO
285 //update related Memberships.
286 $params = array('status_id' => 6);
287 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
288 }
289 }
290 }
d63f4fc3 291
6a488035
TO
292 if ($participant) {
293 $participant->status_id = 4;
294 $participant->save();
295 }
296 }
297 $transaction->commit();
298 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
299 //echo "Success: Setting contribution status to cancelled<p>";
300 return TRUE;
301 }
302
303 function unhandled(&$objects, &$transaction) {
304 $transaction->rollback();
305 // we dont handle this as yet
306 CRM_Core_Error::debug_log_message("returning since contribution status: $status is not handled");
307 echo "Failure: contribution status $status is not handled<p>";
308 return FALSE;
309 }
310
311 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
312 $contribution = &$objects['contribution'];
313 $memberships = &$objects['membership'];
314 if (is_numeric($memberships)) {
315 $memberships = array($objects['membership']);
316 }
317 $participant = &$objects['participant'];
318 $event = &$objects['event'];
319 $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
320 $recurContrib = &$objects['contributionRecur'];
321
322 $values = array();
323 $source = NULL;
324 if ($input['component'] == 'contribute') {
325 if ($contribution->contribution_page_id) {
326 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
327 $source = ts('Online Contribution') . ': ' . $values['title'];
328 }
329 elseif ($recurContrib && $recurContrib->id) {
330 $contribution->contribution_page_id = NULL;
331 $values['amount'] = $recurContrib->amount;
332 $values['financial_type_id'] = $objects['contributionType']->id;
333 $values['title'] = $source = ts('Offline Recurring Contribution');
6a488035
TO
334 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
335 $values['receipt_from_name'] = $domainValues[0];
336 $values['receipt_from_email'] = $domainValues[1];
337 }
ef3a8cf0 338 if($recurContrib && $recurContrib->id){
2b5b0279 339 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
340 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
341 }
6a488035
TO
342
343 $contribution->source = $source;
a7488080 344 if (!empty($values['is_email_receipt'])) {
6a488035
TO
345 $contribution->receipt_date = self::$_now;
346 }
347
348 if (!empty($memberships)) {
349 $membershipsUpdate = array( );
350 foreach ($memberships as $membershipTypeIdKey => $membership) {
351 if ($membership) {
352 $format = '%Y%m%d';
353
354 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
355 $membership->membership_type_id,
356 $membership->is_test, $membership->id
357 );
358
359 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
360 // this picks up membership type changes during renewals
361 $sql = "
362SELECT membership_type_id
363FROM civicrm_membership_log
364WHERE membership_id=$membership->id
365ORDER BY id DESC
366LIMIT 1;";
367 $dao = new CRM_Core_DAO;
368 $dao->query($sql);
369 if ($dao->fetch()) {
370 if (!empty($dao->membership_type_id)) {
371 $membership->membership_type_id = $dao->membership_type_id;
372 $membership->save();
373 }
374 // else fall back to using current membership type
375 }
376 // else fall back to using current membership type
377 $dao->free();
378
379 if ($currentMembership) {
380 /*
381 * Fixed FOR CRM-4433
382 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
383 * when Contribution mode is notify and membership is for renewal )
384 */
385 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
386
387 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
388 $changeToday
389 );
390 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
391 }
392 else {
393 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
394 }
395
396 //get the status for membership.
397 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
398 $dates['end_date'],
399 $dates['join_date'],
400 'today',
401 TRUE
402 );
403
404 $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
405 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format),
406 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format),
407 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format),
408 );
409 //we might be renewing membership,
410 //so make status override false.
411 $formatedParams['is_override'] = FALSE;
412 $membership->copyValues($formatedParams);
413 $membership->save();
414
415 //updating the membership log
416 $membershipLog = array();
417 $membershipLog = $formatedParams;
418
419 $logStartDate = $formatedParams['start_date'];
a7488080 420 if (!empty($dates['log_start_date'])) {
6a488035
TO
421 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
422 $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
423 }
424
425 $membershipLog['start_date'] = $logStartDate;
426 $membershipLog['membership_id'] = $membership->id;
427 $membershipLog['modified_id'] = $membership->contact_id;
428 $membershipLog['modified_date'] = date('Ymd');
429 $membershipLog['membership_type_id'] = $membership->membership_type_id;
430
431 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
432
433 //update related Memberships.
434 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
d63f4fc3 435
6a488035
TO
436 //update the membership type key of membership relatedObjects array
437 //if it has changed after membership update
438 if ($membershipTypeIdKey != $membership->membership_type_id) {
439 $membershipsUpdate[$membership->membership_type_id] = $membership;
440 $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
441 unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
442 unset($memberships[$membershipTypeIdKey]);
443 }
444 }
445 }
446 //update the memberships object with updated membershipTypeId data
447 //if membershipTypeId has changed after membership update
448 if (!empty($membershipsUpdate)) {
449 $memberships = $memberships + $membershipsUpdate;
450 }
451 }
452 }
453 else {
454 // event
455 $eventParams = array('id' => $objects['event']->id);
456 $values['event'] = array();
457
458 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
459
460 //get location details
461 $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
462 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
463
464 $ufJoinParams = array(
465 'entity_table' => 'civicrm_event',
466 'entity_id' => $ids['event'],
467 'module' => 'CiviEvent',
468 );
d63f4fc3 469
6a488035
TO
470 list($custom_pre_id,
471 $custom_post_ids
472 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
d63f4fc3 473
6a488035
TO
474 $values['custom_pre_id'] = $custom_pre_id;
475 $values['custom_post_id'] = $custom_post_ids;
e1eb31b5
RN
476 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
477 //and cases involving status updation through ipn
478 $values['totalAmount'] = $input['amount'];
6a488035
TO
479
480 $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
481
482 if ($values['event']['is_email_confirm']) {
483 $contribution->receipt_date = self::$_now;
484 $values['is_email_receipt'] = 1;
485 }
a7488080 486 if (empty($input['skipComponentSync'])) {
6a488035
TO
487 $participant->status_id = 1;
488 }
489 $participant->save();
490 }
491
492 if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 &&
493 CRM_Utils_Array::value('fee_amount', $input, 0) != 0
494 ) {
495 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
496 }
497 $addLineItems = FALSE;
498 if (empty($contribution->id)) {
499 $addLineItems = TRUE;
500 }
d63f4fc3 501
6a488035
TO
502 $contribution->contribution_status_id = 1;
503 $contribution->is_test = $input['is_test'];
504 $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
505 $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
506 $contribution->trxn_id = $input['trxn_id'];
507 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
508 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
46fa5206 509 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
6a488035
TO
510 $contribution->cancel_date = 'null';
511
a7488080 512 if (!empty($input['check_number'])) {
6a488035
TO
513 $contribution->check_number = $input['check_number'];
514 }
515
a7488080 516 if (!empty($input['payment_instrument_id'])) {
6a488035
TO
517 $contribution->payment_instrument_id = $input['payment_instrument_id'];
518 }
d63f4fc3 519
6a488035
TO
520 if ($contribution->id) {
521 $contributionId['id'] = $contribution->id;
522 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
523 }
524 $contribution->save();
525
8381af80 526 //add new soft credit against current $contribution and
527 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
528 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
529 }
530
6a488035 531 //add lineitems for recurring payments
a7488080 532 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
bf45dbe8 533 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, $input);
6a488035
TO
534 }
535
6357981e
PJ
536 //copy initial contribution custom fields for recurring contributions
537 if ($recurContrib && $recurContrib->id) {
538 $this->copyCustomValues($recurContrib->id, $contribution->id);
539 }
540
6a488035
TO
541 // next create the transaction record
542 $paymentProcessor = $paymentProcessorId = '';
543 if (isset($objects['paymentProcessor'])) {
544 if (is_array($objects['paymentProcessor'])) {
545 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
546 $paymentProcessorId = $objects['paymentProcessor']['id'];
547 }
548 else {
549 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
550 $paymentProcessorId = $objects['paymentProcessor']->id;
551 }
552 }
4d34aefa 553 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
554 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
555 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
556 // it would be good if someone added some comments or refactored this
6a488035
TO
557 if ($contribution->id) {
558 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
cc757ab9 559 if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later &&
560- $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses))) {
561 $input['payment_processor'] = $paymentProcessorId;
6a488035 562 }
78b79549 563 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
6a488035
TO
564 $input['total_amount'] = $input['amount'];
565 $input['contribution'] = $contribution;
a1f5ffcc 566 $input['financial_type_id'] = $contribution->financial_type_id;
567
a7488080 568 if (!empty($contribution->_relatedObjects['participant'])) {
6a488035
TO
569 $input['contribution_mode'] = 'participant';
570 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
0ba0addf 571 $input['skipLineItem'] = 1;
f92fd420 572 }
4d34aefa 573 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
574 // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
575 // and since the contribution is saved prior to this line there is always a contribution-id,
576 // however there is never a prevContribution (which appears to mean original contribution not previous
577 // contribution - or preUpdateContributionObject most accurately)
578 // so, this is always called & only appears to succeed when prevContribution exists - which appears
579 // to mean "are we updating an exisitng pending contribution"
580 //I was able to make the unit test complete as fataling here doesn't prevent
581 // the contribution being created - but activities would not be created or emails sent
6a488035
TO
582 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
583 }
584
585 self::updateRecurLinkedPledge($contribution);
586
587 // create an activity record
588 if ($input['component'] == 'contribute') {
589 //CRM-4027
590 $targetContactID = NULL;
a7488080 591 if (!empty($ids['related_contact'])) {
6a488035
TO
592 $targetContactID = $contribution->contact_id;
593 $contribution->contact_id = $ids['related_contact'];
594 }
595 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
596 // event
597 }
598 else {
599 CRM_Activity_BAO_Activity::addActivity($participant);
600 }
601
602 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
603 $transaction->commit();
604
605 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
606 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
607 if (!array_key_exists('is_email_receipt', $values) ||
608 $values['is_email_receipt'] == 1
609 ) {
610 self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
bf014492 611 CRM_Core_Error::debug_log_message("Receipt sent");
6a488035
TO
612 }
613
bf014492 614 CRM_Core_Error::debug_log_message("Success: Database updated");
6a488035
TO
615 }
616
617 function getBillingID(&$ids) {
618 // get the billing location type
180409a4 619 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
620 // CRM-8108 remove the ts around the Billing locationtype
621 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
622 $ids['billing'] = array_search('Billing', $locationTypes);
623 if (!$ids['billing']) {
624 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
625 echo "Failure: Could not find billing location type<p>";
626 return FALSE;
627 }
628 return TRUE;
629 }
630
631 /*
632 * Send receipt from contribution. Note that the compose message part has been moved to contribution
633 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
634 *
635 * @params array $input Incoming data from Payment processor
636 * @params array $ids Related object IDs
637 * @params array $values values related to objects that have already been loaded
638 * @params bool $recur is it part of a recurring contribution
639 * @params bool $returnMessageText Should text be returned instead of sent. This
640 * is because the function is also used to generate pdfs
641 */
642 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
643 $contribution = &$objects['contribution'];
644 $input['is_recur'] = $recur;
645 // set receipt from e-mail and name in value
646 if (!$returnMessageText) {
647 $session = CRM_Core_Session::singleton();
648 $userID = $session->get('userID');
649 if (!empty($userID)) {
650 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
651 $values['receipt_from_email'] = $userEmail;
652 $values['receipt_from_name'] = $userName;
653 }
654 }
655 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
656 }
657
8196c759 658 /**
659 * Update contribution status - this is only called from one place in the code &
660 * it is unclear whether it is a function on the way in or on the way out
661 *
662 * @param unknown_type $params
663 * @return void|Ambigous <value, unknown, array>
664 */
6a488035
TO
665 function updateContributionStatus(&$params) {
666 // get minimum required values.
667 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
668 $componentId = CRM_Utils_Array::value('component_id', $params);
669 $componentName = CRM_Utils_Array::value('componentName', $params);
670 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
671
672 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
673 return;
674 }
675
676 $input = $ids = $objects = array();
677
678 //get the required ids.
679 $ids['contribution'] = $contributionId;
680
681 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
682 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
683 $contributionId,
684 'contact_id'
685 );
686 }
687
688 if ($componentName == 'Event') {
689 $name = 'event';
690 $ids['participant'] = $componentId;
691
692 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
693 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
694 $componentId,
695 'event_id'
696 );
697 }
698 }
699
700 if ($componentName == 'Membership') {
701 $name = 'contribute';
702 $ids['membership'] = $componentId;
703 }
704 $ids['contributionPage'] = NULL;
705 $ids['contributionRecur'] = NULL;
706 $input['component'] = $name;
707
708 $baseIPN = new CRM_Core_Payment_BaseIPN();
709 $transaction = new CRM_Core_Transaction();
710
711 // reset template values.
712 $template = CRM_Core_Smarty::singleton();
713 $template->clearTemplateVars();
714
715 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
716 CRM_Core_Error::fatal();
717 }
718
719 $contribution = &$objects['contribution'];
720
721 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
722 $input['skipComponentSync'] = CRM_Utils_Array::value('skipComponentSync', $params);
723 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
724 $baseIPN->cancelled($objects, $transaction, $input);
725 $transaction->commit();
726 return $statusId;
727 }
728 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
729 $baseIPN->failed($objects, $transaction, $input);
730 $transaction->commit();
731 return $statusId;
732 }
733
734 // status is not pending
735 if ($contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
736 $transaction->commit();
737 return;
738 }
739
740 //set values for ipn code.
741 foreach (array(
742 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
743 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
744 $input[$field] = $contribution->$field;
745 }
746 }
747 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
748 $input['trxn_id'] = $contribution->invoice_id;
749 }
750 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
751 $input['amount'] = $contribution->total_amount;
752 }
753 $input['is_test'] = $contribution->is_test;
754 $input['net_amount'] = $contribution->net_amount;
8cc574cf 755 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
6a488035
TO
756 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
757 }
758
759 //complete the contribution.
760 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
761
762 // reset template values before processing next transactions
763 $template->clearTemplateVars();
764
765 return $statusId;
766 }
767
768 /*
769 * Update pledge associated with a recurring contribution
770 *
771 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
772 *
773 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
774 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
775 * it should be assumed they
776 * do so with the intention that all payments will be linked
777 *
778 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
779 * If not the contribution will also need to be linked to the pledge
780 */
781 function updateRecurLinkedPledge(&$contribution) {
782 $returnProperties = array('id', 'pledge_id');
783 $paymentDetails = $paymentIDs = array();
784
785 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
786 $paymentDetails, $returnProperties
787 )) {
788 foreach ($paymentDetails as $key => $value) {
789 $paymentIDs[] = $value['id'];
790 $pledgeId = $value['pledge_id'];
791 }
792 }
793 else {
794 //payment is not already linked - if it is linked with a pledge we need to create a link.
795 // return if it is not recurring contribution
796 if (!$contribution->contribution_recur_id) {
797 return;
798 }
799
800 $relatedContributions = new CRM_Contribute_DAO_Contribution();
801 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
802 $relatedContributions->find();
803
804 while ($relatedContributions->fetch()) {
805 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
806 $paymentDetails, $returnProperties
807 );
808 }
809
810 if (empty($paymentDetails)) {
811 // payment is not linked with a pledge and neither are any other contributions on this
812 return;
813 }
814
815 foreach ($paymentDetails as $key => $value) {
816 $pledgeId = $value['pledge_id'];
817 }
818
819 // we have a pledge now we need to get the oldest unpaid payment
820 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
e3f3156b 821 if(empty($paymentDetails['id'])){
822 // we can assume this pledge is now completed
823 // return now so we don't create a core error & roll back
824 return;
825 }
6a488035
TO
826 $paymentDetails['contribution_id'] = $contribution->id;
827 $paymentDetails['status_id'] = $contribution->contribution_status_id;
828 $paymentDetails['actual_amount'] = $contribution->total_amount;
829
830 // put contribution against it
831 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
832 $paymentIDs[] = $payment->id;
833 }
834
835 // update pledge and corresponding payment statuses
836 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
837 NULL, $contribution->total_amount
838 );
839 }
840
bf45dbe8 841 function addrecurLineItems($recurId, $contributionId, &$input) {
6a488035
TO
842 $lineSets = $lineItems = array();
843
844 //Get the first contribution id with recur id
845 if ($recurId) {
846 $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
847 $lineItems = CRM_Price_BAO_LineItem::getLineItems($contriID, 'contribution');
848 if (!empty($lineItems)) {
849 foreach ($lineItems as $key => $value) {
9da8dc8c 850 $pricesetID = new CRM_Price_DAO_PriceField();
6a488035
TO
851 $pricesetID->id = $value['price_field_id'];
852 $pricesetID->find(TRUE);
853 $lineSets[$pricesetID->price_set_id][] = $value;
854 }
855 }
bf45dbe8
PN
856 if (!empty($input)) {
857 $input['line_item'] = $lineSets;
858 }
859 else {
860 CRM_Price_BAO_LineItem::processPriceSet($contributionId, $lineSets);
861 }
6a488035
TO
862 }
863 }
6a488035 864
6357981e
PJ
865 // function to copy custom data of the
866 // initial contribution into its recurring contributions
867 function copyCustomValues($recurId, $targetContributionId) {
868 if ($recurId && $targetContributionId) {
869 // get the initial contribution id of recur id
870 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
871
872 // if the same contribution is being proccessed then return
873 if ($sourceContributionId == $targetContributionId) {
874 return;
875 }
876 // check if proper recurring contribution record is being processed
877 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
878 if ($targetConRecurId != $recurId) {
879 return;
880 }
881
882 // copy custom data
883 $extends = array('Contribution');
884 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
885 if ($groupTree) {
886 foreach ($groupTree as $groupID => $group) {
887 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
888 foreach ($group['fields'] as $fieldID => $field) {
889 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
890 }
891 }
892
893 foreach ($table as $tableName => $tableColumns) {
894 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
895 $tableColumns[0] = $targetContributionId;
896 $select = 'SELECT ' . implode(', ', $tableColumns);
897 $from = ' FROM ' . $tableName;
898 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
899 $query = $insert . $select . $from . $where;
900 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
901 }
902 }
903 }
904 }
8381af80 905
906 // function to copy soft credit record of first recurring contribution
907 // and add new soft credit against $targetContributionId
908 function addrecurSoftCredit($recurId, $targetContributionId) {
909 $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
910
911 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
912 $soft_contribution->contribution_id = $contriID;
913
914 //check if first recurring contribution has any associated soft credit
915 if ($soft_contribution->find(TRUE)) {
916 $soft_contribution->contribution_id = $targetContributionId;
917 unset($soft_contribution->id);
918 $soft_contribution->save();
919 }
920 }
b2b0530a 921}