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