Merge pull request #12070 from eileenmcnaughton/loggin_fix
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
34
35 static $_paymentProcessor = NULL;
c8aa607b 36
37 /**
38 * Input parameters from payment processor. Store these so that
39 * the code does not need to keep retrieving from the http request
40 * @var array
41 */
42 protected $_inputParameters = array();
43
44 /**
fe482240 45 * Store for the variables from the invoice string.
c8aa607b 46 * @var array
47 */
48 protected $_invoiceData = array();
49
50 /**
fe482240 51 * Is this a payment express transaction.
c8aa607b 52 */
53 protected $_isPaymentExpress = FALSE;
54
55 /**
56 * Are we dealing with an event an 'anything else' (contribute)
57 * @var string component
58 */
59 protected $_component = 'contribute';
0dbefed3 60
c8aa607b 61 /**
fe482240 62 * Constructor function.
0dbefed3 63 *
6a0b768e
TO
64 * @param array $inputData
65 * Contents of HTTP REQUEST.
0dbefed3
EM
66 *
67 * @throws CRM_Core_Exception
c8aa607b 68 */
00be9182 69 public function __construct($inputData) {
c8aa607b 70 $this->setInputParameters($inputData);
71 $this->setInvoiceData();
6a488035
TO
72 parent::__construct();
73 }
74
c8aa607b 75 /**
fe482240 76 * get the values from the rp_invoice_id string.
77b97be7 77 *
6a0b768e
TO
78 * @param string $name
79 * E.g. i, values are stored in the string with letter codes.
80 * @param bool $abort
16b10e64 81 * Throw exception if not found
77b97be7
EM
82 *
83 * @throws CRM_Core_Exception
16b10e64 84 * @return mixed
c8aa607b 85 */
00be9182 86 public function getValue($name, $abort = TRUE) {
c8aa607b 87 if ($abort && empty($this->_invoiceData[$name])) {
88 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
6a488035
TO
89 }
90 else {
c8aa607b 91 return CRM_Utils_Array::value($name, $this->_invoiceData);
92 }
93 }
94
95 /**
96 * Set $this->_invoiceData from the input array
97 */
00be9182 98 public function setInvoiceData() {
22e263ad 99 if (empty($this->_inputParameters['rp_invoice_id'])) {
c8aa607b 100 $this->_isPaymentExpress = TRUE;
101 return;
102 }
103 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
104 // for clarify let's also store without the single letter unreadable
105 //@todo after more refactoring we might ditch storing the one letter stuff
106 $mapping = array(
107 'i' => 'invoice_id',
108 'm' => 'component',
109 'c' => 'contact_id',
110 'b' => 'contribution_id',
111 'r' => 'contribution_recur_id',
112 'p' => 'participant_id',
113 'e' => 'event_id',
114 );
115 foreach ($rpInvoiceArray as $rpInvoiceValue) {
116 $rpValueArray = explode('=', $rpInvoiceValue);
117 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
118 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
119 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
120 // alphabet with more letters.
121 // the mode will always be resolved before the mystery p is reached
22e263ad 122 if ($rpValueArray[1] == 'contribute') {
c8aa607b 123 $mapping['p'] = 'contribution_page_id';
124 }
6a488035 125 }
22e263ad 126 if (empty($this->_inputParameters['component'])) {
949babe8
JM
127 $this->_isPaymentExpress = TRUE;
128 }
6a488035
TO
129 }
130
c8aa607b 131 /**
6a0b768e
TO
132 * @param string $name
133 * Of variable to return.
134 * @param string $type
135 * Data type.
c8aa607b 136 * - String
137 * - Integer
6a0b768e
TO
138 * @param string $location
139 * Deprecated.
140 * @param bool $abort
141 * Abort if empty.
77b97be7
EM
142 *
143 * @throws CRM_Core_Exception
72b3a70c 144 * @return mixed
c8aa607b 145 */
00be9182 146 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
c8aa607b 147 $value = CRM_Utils_Type::validate(
148 CRM_Utils_Array::value($name, $this->_inputParameters),
149 $type,
150 FALSE
6a488035
TO
151 );
152 if ($abort && $value === NULL) {
c8aa607b 153 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
6a488035
TO
154 }
155 return $value;
156 }
157
c8aa607b 158 /**
fe482240 159 * Process recurring contributions.
c8aa607b 160 * @param array $input
161 * @param array $ids
162 * @param array $objects
6a0b768e 163 * @param bool $first
0b014509 164 * @return bool
c8aa607b 165 */
00be9182 166 public function recur(&$input, &$ids, &$objects, $first) {
6a488035
TO
167 if (!isset($input['txnType'])) {
168 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
169 echo "Failure: Invalid parameters<p>";
170 return FALSE;
171 }
172
6a488035
TO
173 $recur = &$objects['contributionRecur'];
174
175 // make sure the invoice ids match
176 // make sure the invoice is valid and matches what we have in
177 // the contribution record
178 if ($recur->invoice_id != $input['invoice']) {
179 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
180 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
181 return FALSE;
182 }
183
184 $now = date('YmdHis');
185
186 // fix dates that already exist
187 $dates = array('create', 'start', 'end', 'cancel', 'modified');
188 foreach ($dates as $date) {
189 $name = "{$date}_date";
190 if ($recur->$name) {
191 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
192 }
193 }
194
195 $sendNotification = FALSE;
196 $subscriptionPaymentStatus = NULL;
197 //List of Transaction Type
198 /*
e70a7fc0 199 recurring_payment_profile_created RP Profile Created
b44e3f84 200 recurring_payment RP Successful Payment
e70a7fc0
TO
201 recurring_payment_failed RP Failed Payment
202 recurring_payment_profile_cancel RP Profile Cancelled
203 recurring_payment_expired RP Profile Expired
204 recurring_payment_skipped RP Profile Skipped
b44e3f84 205 recurring_payment_outstanding_payment RP Successful Outstanding Payment
e70a7fc0
TO
206 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
207 recurring_payment_suspended RP Profile Suspended
208 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
209 */
6a488035 210
6a488035 211 //set transaction type
c8aa607b 212 $txnType = $this->retrieve('txn_type', 'String');
6a488035 213 //Changes for paypal pro recurring payment
e25b58d1
E
214 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
215 $contributionStatuses = $contributionStatuses['values'];
6a488035
TO
216 switch ($txnType) {
217 case 'recurring_payment_profile_created':
353ffa53
TO
218 if (in_array($recur->contribution_status_id, array(
219 array_search('Pending', $contributionStatuses),
d5cc0fc2 220 array_search('In Progress', $contributionStatuses),
353ffa53
TO
221 ))
222 && !empty($recur->processor_id)
223 ) {
e25b58d1 224 echo "already handled";
0b014509 225 return FALSE;
e25b58d1 226 }
6a488035
TO
227 $recur->create_date = $now;
228 $recur->contribution_status_id = 2;
d57577d4 229 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
6a488035
TO
230 $recur->trxn_id = $recur->processor_id;
231 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
232 $sendNotification = TRUE;
233 break;
234
235 case 'recurring_payment':
236 if ($first) {
237 $recur->start_date = $now;
238 }
239 else {
5b51381e 240 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
241 $input['original_contribution_id'] = $ids['contribution'];
242 $input['contribution_recur_id'] = $ids['contributionRecur'];
243
244 if ($input['paymentStatus'] != 'Completed') {
245 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
246 }
247 // In future moving to create pending & then complete, but this OK for now.
248 // Also consider accepting 'Failed' like other processors.
249 $input['contribution_status_id'] = 1;
250
251 civicrm_api3('Contribution', 'repeattransaction', $input);
252 return;
6a488035
TO
253 }
254
255 //contribution installment is completed
c8aa607b 256 if ($this->retrieve('profile_status', 'String') == 'Expired') {
22e263ad 257 if (!empty($recur->end_date)) {
e25b58d1 258 echo "already handled";
0b014509 259 return FALSE;
e25b58d1 260 }
6a488035
TO
261 $recur->contribution_status_id = 1;
262 $recur->end_date = $now;
263 $sendNotification = TRUE;
264 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
265 }
266
267 // make sure the contribution status is not done
268 // since order of ipn's is unknown
269 if ($recur->contribution_status_id != 1) {
270 $recur->contribution_status_id = 5;
271 }
272 break;
273 }
274
275 $recur->save();
276
277 if ($sendNotification) {
278 $autoRenewMembership = FALSE;
279 if ($recur->id &&
280 isset($ids['membership']) && $ids['membership']
281 ) {
282 $autoRenewMembership = TRUE;
283 }
284 //send recurring Notification email for user
285 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
286 $ids['contact'],
287 $ids['contributionPage'],
288 $recur,
289 $autoRenewMembership
290 );
291 }
292
293 if ($txnType != 'recurring_payment') {
0b014509 294 return TRUE;
6a488035
TO
295 }
296
297 if (!$first) {
bc66bc9e
PJ
298 //check if this contribution transaction is already processed
299 //if not create a contribution and then get it processed
6a488035 300 $contribution = new CRM_Contribute_BAO_Contribution();
bc66bc9e
PJ
301 $contribution->trxn_id = $input['trxn_id'];
302 if ($contribution->trxn_id && $contribution->find()) {
303 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
304 echo "Success: Contribution has already been handled<p>";
305 return TRUE;
306 }
307
73004adf 308 $contribution->contact_id = $recur->contact_id;
353ffa53 309 $contribution->financial_type_id = $objects['contributionType']->id;
6a488035
TO
310 $contribution->contribution_page_id = $ids['contributionPage'];
311 $contribution->contribution_recur_id = $ids['contributionRecur'];
6a488035
TO
312 $contribution->currency = $objects['contribution']->currency;
313 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
314 $contribution->amount_level = $objects['contribution']->amount_level;
94d1bc8d 315 $contribution->campaign_id = $objects['contribution']->campaign_id;
6a488035 316 $objects['contribution'] = &$contribution;
5b51381e 317 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
6a488035 318 }
da88a16b 319 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
2aa397bc 320 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
6a488035
TO
321
322 $this->single($input, $ids, $objects,
323 TRUE, $first
324 );
325 }
326
6c786a9b
EM
327 /**
328 * @param $input
329 * @param $ids
330 * @param $objects
331 * @param bool $recur
332 * @param bool $first
7a9ab499
EM
333 *
334 * @return bool
6c786a9b 335 */
00be9182 336 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
6a488035
TO
337 $contribution = &$objects['contribution'];
338
339 // make sure the invoice is valid and matches what we have in the contribution record
340 if ((!$recur) || ($recur && $first)) {
341 if ($contribution->invoice_id != $input['invoice']) {
342 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
343 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
344 return FALSE;
345 }
346 }
347 else {
348 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
349 }
350
351 if (!$recur) {
352 if ($contribution->total_amount != $input['amount']) {
353 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
354 echo "Failure: Amount values dont match between database and IPN request<p>";
355 return FALSE;
356 }
357 }
358 else {
359 $contribution->total_amount = $input['amount'];
360 }
361
362 $transaction = new CRM_Core_Transaction();
363
6a488035
TO
364 $status = $input['paymentStatus'];
365 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
366 return $this->failed($objects, $transaction);
367 }
368 elseif ($status == 'Pending') {
369 return $this->pending($objects, $transaction);
370 }
371 elseif ($status == 'Refunded' || $status == 'Reversed') {
372 return $this->cancelled($objects, $transaction);
373 }
374 elseif ($status != 'Completed') {
375 return $this->unhandled($objects, $transaction);
376 }
377
378 // check if contribution is already completed, if so we ignore this ipn
379 if ($contribution->contribution_status_id == 1) {
380 $transaction->commit();
381 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
382 echo "Success: Contribution has already been handled<p>";
383 return TRUE;
384 }
385
386 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
387 }
388
eaf9432c
LB
389 /**
390 * Gets PaymentProcessorID for PayPal
391 *
392 * @return int
393 */
394 public function getPayPalPaymentProcessorID() {
395 // This is an unreliable method as there could be more than one instance.
396 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
397 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
398 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
399 // & call completetransaction or call fail? (which may not exist yet).
400 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
401 'PayPal', 'id', 'name'
402 );
403 return (int) civicrm_api3('PaymentProcessor', 'getvalue', array(
404 'is_test' => 0,
405 'options' => array('limit' => 1),
406 'payment_processor_type_id' => $paymentProcessorTypeID,
407 'return' => 'id',
408 ));
409
410 }
411
c8aa607b 412 /**
413 * This is the main function to call. It should be sufficient to instantiate the class
414 * (with the input parameters) & call this & all will be done
415 *
416 * @todo the references to POST throughout this class need to be removed
0b014509 417 * @return bool
c8aa607b 418 */
00be9182 419 public function main() {
6a488035
TO
420 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
421 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
22e263ad 422 if ($this->_isPaymentExpress) {
c8aa607b 423 $this->handlePaymentExpress();
0b014509 424 return FALSE;
c8aa607b 425 }
6a488035 426 $objects = $ids = $input = array();
353ffa53 427 $this->_component = $input['component'] = self::getValue('m');
949babe8 428 $input['invoice'] = self::getValue('i', TRUE);
6a488035
TO
429 // get the contribution and contact ids from the GET params
430 $ids['contact'] = self::getValue('c', TRUE);
431 $ids['contribution'] = self::getValue('b', TRUE);
432
433 $this->getInput($input, $ids);
434
c8aa607b 435 if ($this->_component == 'event') {
6a488035
TO
436 $ids['event'] = self::getValue('e', TRUE);
437 $ids['participant'] = self::getValue('p', TRUE);
438 $ids['contributionRecur'] = self::getValue('r', FALSE);
439 }
440 else {
441 // get the optional ids
c8aa607b 442 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
443 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
6a488035
TO
444 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
445 $ids['contributionRecur'] = self::getValue('r', FALSE);
446 $ids['contributionPage'] = self::getValue('p', FALSE);
447 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
448 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
449 }
450
451 if (!$ids['membership'] && $ids['contributionRecur']) {
452 $sql = "
453 SELECT m.id
454 FROM civicrm_membership m
455INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
456 WHERE m.contribution_recur_id = %2
457 LIMIT 1";
2aa397bc 458 $sqlParams = array(
353ffa53 459 1 => array($ids['contribution'], 'Integer'),
6a488035
TO
460 2 => array($ids['contributionRecur'], 'Integer'),
461 );
462 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
463 $ids['membership'] = $membershipId;
464 }
465 }
466
8b8e1e57 467 // This is an unreliable method as there could be more than one instance.
468 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
469 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
470 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
471 // & call completetransaction or call fail? (which may not exist yet).
eaf9432c
LB
472
473 $paymentProcessorID = self::getPayPalPaymentProcessorID();
6a488035
TO
474
475 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
476 return FALSE;
477 }
478
479 self::$_paymentProcessor = &$objects['paymentProcessor'];
c8aa607b 480 //?? how on earth would we not have component be one of these?
481 // they are the only valid settings & this IPN file can't even be called without one of them
482 // grepping for this class doesn't find other paths to call this class
483 if ($this->_component == 'contribute' || $this->_component == 'event') {
6a488035
TO
484 if ($ids['contributionRecur']) {
485 // check if first contribution is completed, else complete first contribution
486 $first = TRUE;
487 if ($objects['contribution']->contribution_status_id == 1) {
488 $first = FALSE;
489 }
490 return $this->recur($input, $ids, $objects, $first);
491 }
492 else {
493 return $this->single($input, $ids, $objects, FALSE, FALSE);
494 }
495 }
496 else {
497 return $this->single($input, $ids, $objects, FALSE, FALSE);
498 }
499 }
500
6c786a9b
EM
501 /**
502 * @param $input
503 * @param $ids
504 *
72b3a70c 505 * @return bool
6c786a9b
EM
506 * @throws CRM_Core_Exception
507 */
00be9182 508 public function getInput(&$input, &$ids) {
6a488035
TO
509
510 if (!$this->getBillingID($ids)) {
511 return FALSE;
512 }
513
514 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
515 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
6a488035
TO
516
517 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
518 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
519
520 $billingID = $ids['billing'];
521 $lookup = array(
522 "first_name" => 'first_name',
523 "last_name" => 'last_name',
524 "street_address-{$billingID}" => 'address_street',
525 "city-{$billingID}" => 'address_city',
526 "state-{$billingID}" => 'address_state',
527 "postal_code-{$billingID}" => 'address_zip',
528 "country-{$billingID}" => 'address_country_code',
529 );
530 foreach ($lookup as $name => $paypalName) {
531 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
532 $input[$name] = $value ? $value : NULL;
533 }
534
353ffa53 535 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
6a488035
TO
536 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
537 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
353ffa53 538 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
12829b5d 539 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
94155403 540 $input['total_amount'] = $input['amount'];
6a488035 541 }
c8aa607b 542
543 /**
fe482240 544 * Handle payment express IPNs.
c8aa607b 545 * For one off IPNS no actual response is required
546 * Recurring is more difficult as we have limited confirmation material
949babe8
JM
547 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
548 * duplicated
549 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
550 * then the quasi security of the ids array might be required - although better to
551 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
552 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
553 * only contribute is handled
c8aa607b 554 */
00be9182 555 public function handlePaymentExpress() {
2aa397bc
TO
556 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
557 // keep discreet
558 // also note that a lot of the complexity above could be removed if we used
559 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
560 // as membership id etc can be derived by the load objects fn
949babe8
JM
561 $objects = $ids = $input = array();
562 $isFirst = FALSE;
353ffa53 563 $input['txnType'] = $this->retrieve('txn_type', 'String');
22e263ad 564 if ($input['txnType'] != 'recurring_payment') {
949babe8
JM
565 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
566 }
567 $input['invoice'] = self::getValue('i', FALSE);
568 $this->getInput($input, $ids);
d3e86119 569 if ($this->transactionExists($input['trxn_id'])) {
949babe8
JM
570 throw new CRM_Core_Exception('This transaction has already been processed');
571 }
572
353ffa53
TO
573 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array(
574 'return' => 'contact_id, id',
d5cc0fc2 575 'invoice_id' => $input['invoice'],
353ffa53 576 ));
949babe8
JM
577 $ids['contact'] = $contributionRecur['contact_id'];
578 $ids['contributionRecur'] = $contributionRecur['id'];
481a74f4 579 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice']));
949babe8
JM
580
581 $ids['contribution'] = $result['id'];
582 //@todo hard - coding 'pending' for now
22e263ad 583 if ($result['contribution_status_id'] == 2) {
2aa397bc 584 $isFirst = TRUE;
949babe8
JM
585 }
586 // arg api won't get this - fix it
353ffa53
TO
587 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(
588 1 => array(
589 $ids['contribution'],
d5cc0fc2 590 'Integer',
591 ),
353ffa53 592 ));
949babe8
JM
593 // only handle component at this stage - not terribly sure how a recurring event payment would arise
594 // & suspec main function may be a victom of copy & paste
595 // membership would be an easy add - but not relevant to my customer...
353ffa53 596 $this->_component = $input['component'] = 'contribute';
949babe8 597 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String')));
eaf9432c 598 $paymentProcessorID = self::getPayPalPaymentProcessorID();
949babe8
JM
599
600 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
601 throw new CRM_Core_Exception('Data did not validate');
602 }
603 return $this->recur($input, $ids, $objects, $isFirst);
604 }
605
606 /**
fe482240 607 * Function check if transaction already exists.
949babe8 608 * @param string $trxn_id
72b3a70c 609 * @return bool|void
949babe8 610 */
00be9182 611 public function transactionExists($trxn_id) {
22e263ad 612 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
949babe8 613 array(
21dfd5f5 614 1 => array($trxn_id, 'String'),
353ffa53
TO
615 ))
616 ) {
949babe8
JM
617 return TRUE;
618 }
c8aa607b 619 }
96025800 620
6a488035 621}