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