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