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