CRM/Core/Payment add missing code blocks (autogenerated)
[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 * constructor function
64 */
65 function __construct($inputData) {
66 $this->setInputParameters($inputData);
67 $this->setInvoiceData();
68 parent::__construct();
69 }
70
71 /**
72 * function exists to get the values from the rp_invoice_id string
73 *
74 * @param string $name e.g. i, values are stored in the string with letter codes
75 * @param boolean $abort fatal if not found?
76 *
77 * @throws CRM_Core_Exception
78 * @return unknown
79 */
80 function getValue($name, $abort = TRUE) {
81 if ($abort && empty($this->_invoiceData[$name])) {
82 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
83 }
84 else {
85 return CRM_Utils_Array::value($name, $this->_invoiceData);
86 }
87 }
88
89 /**
90 * Set $this->_invoiceData from the input array
91 */
92 function setInvoiceData() {
93 if(empty($this->_inputParameters['rp_invoice_id'])) {
94 $this->_isPaymentExpress = TRUE;
95 return;
96 }
97 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
98 // for clarify let's also store without the single letter unreadable
99 //@todo after more refactoring we might ditch storing the one letter stuff
100 $mapping = array(
101 'i' => 'invoice_id',
102 'm' => 'component',
103 'c' => 'contact_id',
104 'b' => 'contribution_id',
105 'r' => 'contribution_recur_id',
106 'p' => 'participant_id',
107 'e' => 'event_id',
108 );
109 foreach ($rpInvoiceArray as $rpInvoiceValue) {
110 $rpValueArray = explode('=', $rpInvoiceValue);
111 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
112 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
113 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
114 // alphabet with more letters.
115 // the mode will always be resolved before the mystery p is reached
116 if($rpValueArray[1] == 'contribute') {
117 $mapping['p'] = 'contribution_page_id';
118 }
119 }
120 }
121
122 /**
123 * @param string $name of variable to return
124 * @param string $type data type
125 * - String
126 * - Integer
127 * @param string $location - deprecated
128 * @param boolean $abort abort if empty
129 *
130 * @throws CRM_Core_Exception
131 * @return Ambigous <mixed, NULL, value, unknown, array, number>
132 */
133 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
134 $value = CRM_Utils_Type::validate(
135 CRM_Utils_Array::value($name, $this->_inputParameters),
136 $type,
137 FALSE
138 );
139 if ($abort && $value === NULL) {
140 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
141 }
142 return $value;
143 }
144
145 /**
146 * Process recurring contributions
147 * @param array $input
148 * @param array $ids
149 * @param array $objects
150 * @param boolean $first
151 * @return void|boolean
152 */
153 function recur(&$input, &$ids, &$objects, $first) {
154 if (!isset($input['txnType'])) {
155 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
156 echo "Failure: Invalid parameters<p>";
157 return FALSE;
158 }
159
160 if ($input['txnType'] == 'recurring_payment' &&
161 $input['paymentStatus'] != 'Completed'
162 ) {
163 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
164 echo "Failure: Invalid parameters<p>";
165 return FALSE;
166 }
167
168 $recur = &$objects['contributionRecur'];
169
170 // make sure the invoice ids match
171 // make sure the invoice is valid and matches what we have in
172 // the contribution record
173 if ($recur->invoice_id != $input['invoice']) {
174 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
175 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
176 return FALSE;
177 }
178
179 $now = date('YmdHis');
180
181 // fix dates that already exist
182 $dates = array('create', 'start', 'end', 'cancel', 'modified');
183 foreach ($dates as $date) {
184 $name = "{$date}_date";
185 if ($recur->$name) {
186 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
187 }
188 }
189
190 $sendNotification = FALSE;
191 $subscriptionPaymentStatus = NULL;
192 //List of Transaction Type
193 /*
194 recurring_payment_profile_created RP Profile Created
195 recurring_payment RP Sucessful Payment
196 recurring_payment_failed RP Failed Payment
197 recurring_payment_profile_cancel RP Profile Cancelled
198 recurring_payment_expired RP Profile Expired
199 recurring_payment_skipped RP Profile Skipped
200 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
201 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
202 recurring_payment_suspended RP Profile Suspended
203 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
204 */
205
206
207 //set transaction type
208 $txnType = $this->retrieve('txn_type', 'String');
209 //Changes for paypal pro recurring payment
210
211 switch ($txnType) {
212 case 'recurring_payment_profile_created':
213 $recur->create_date = $now;
214 $recur->contribution_status_id = 2;
215 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
216 $recur->trxn_id = $recur->processor_id;
217 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
218 $sendNotification = TRUE;
219 break;
220
221 case 'recurring_payment':
222 if ($first) {
223 $recur->start_date = $now;
224 }
225 else {
226 $recur->modified_date = $now;
227 }
228
229 //contribution installment is completed
230 if ($this->retrieve('profile_status', 'String') == 'Expired') {
231 $recur->contribution_status_id = 1;
232 $recur->end_date = $now;
233 $sendNotification = TRUE;
234 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
235 }
236
237 // make sure the contribution status is not done
238 // since order of ipn's is unknown
239 if ($recur->contribution_status_id != 1) {
240 $recur->contribution_status_id = 5;
241 }
242 break;
243 }
244
245 $recur->save();
246
247 if ($sendNotification) {
248 $autoRenewMembership = FALSE;
249 if ($recur->id &&
250 isset($ids['membership']) && $ids['membership']
251 ) {
252 $autoRenewMembership = TRUE;
253 }
254 //send recurring Notification email for user
255 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
256 $ids['contact'],
257 $ids['contributionPage'],
258 $recur,
259 $autoRenewMembership
260 );
261 }
262
263 if ($txnType != 'recurring_payment') {
264 return;
265 }
266
267 if (!$first) {
268 //check if this contribution transaction is already processed
269 //if not create a contribution and then get it processed
270 $contribution = new CRM_Contribute_BAO_Contribution();
271 $contribution->trxn_id = $input['trxn_id'];
272 if ($contribution->trxn_id && $contribution->find()) {
273 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
274 echo "Success: Contribution has already been handled<p>";
275 return TRUE;
276 }
277
278 $contribution->contact_id = $recur->contact_id;
279 $contribution->financial_type_id = $objects['contributionType']->id;
280 $contribution->contribution_page_id = $ids['contributionPage'];
281 $contribution->contribution_recur_id = $ids['contributionRecur'];
282 $contribution->currency = $objects['contribution']->currency;
283 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
284 $contribution->amount_level = $objects['contribution']->amount_level;
285 $contribution->campaign_id = $objects['contribution']->campaign_id;
286 $objects['contribution'] = &$contribution;
287 }
288 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
289 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])): $now;
290
291 $this->single($input, $ids, $objects,
292 TRUE, $first
293 );
294 }
295
296 /**
297 * @param $input
298 * @param $ids
299 * @param $objects
300 * @param bool $recur
301 * @param bool $first
302 */
303 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
304 $contribution = &$objects['contribution'];
305
306 // make sure the invoice is valid and matches what we have in the contribution record
307 if ((!$recur) || ($recur && $first)) {
308 if ($contribution->invoice_id != $input['invoice']) {
309 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
310 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
311 return FALSE;
312 }
313 }
314 else {
315 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
316 }
317
318 if (!$recur) {
319 if ($contribution->total_amount != $input['amount']) {
320 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
321 echo "Failure: Amount values dont match between database and IPN request<p>";
322 return FALSE;
323 }
324 }
325 else {
326 $contribution->total_amount = $input['amount'];
327 }
328
329 $transaction = new CRM_Core_Transaction();
330
331 $participant = &$objects['participant'];
332 $membership = &$objects['membership'];
333
334 $status = $input['paymentStatus'];
335 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
336 return $this->failed($objects, $transaction);
337 }
338 elseif ($status == 'Pending') {
339 return $this->pending($objects, $transaction);
340 }
341 elseif ($status == 'Refunded' || $status == 'Reversed') {
342 return $this->cancelled($objects, $transaction);
343 }
344 elseif ($status != 'Completed') {
345 return $this->unhandled($objects, $transaction);
346 }
347
348 // check if contribution is already completed, if so we ignore this ipn
349 if ($contribution->contribution_status_id == 1) {
350 $transaction->commit();
351 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
352 echo "Success: Contribution has already been handled<p>";
353 return TRUE;
354 }
355
356 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
357 }
358
359 /**
360 * This is the main function to call. It should be sufficient to instantiate the class
361 * (with the input parameters) & call this & all will be done
362 *
363 * @todo the references to POST throughout this class need to be removed
364 * @return void|boolean|Ambigous <void, boolean>
365 */
366 function main() {
367 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
368 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
369 if($this->_isPaymentExpress) {
370 $this->handlePaymentExpress();
371 return;
372 }
373 $objects = $ids = $input = array();
374 $this->_component = $input['component'] = self::getValue('m');
375
376 // get the contribution and contact ids from the GET params
377 $ids['contact'] = self::getValue('c', TRUE);
378 $ids['contribution'] = self::getValue('b', TRUE);
379
380 $this->getInput($input, $ids);
381
382 if ($this->_component == 'event') {
383 $ids['event'] = self::getValue('e', TRUE);
384 $ids['participant'] = self::getValue('p', TRUE);
385 $ids['contributionRecur'] = self::getValue('r', FALSE);
386 }
387 else {
388 // get the optional ids
389 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
390 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
391 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
392 $ids['contributionRecur'] = self::getValue('r', FALSE);
393 $ids['contributionPage'] = self::getValue('p', FALSE);
394 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
395 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
396 }
397
398 if (!$ids['membership'] && $ids['contributionRecur']) {
399 $sql = "
400 SELECT m.id
401 FROM civicrm_membership m
402 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
403 WHERE m.contribution_recur_id = %2
404 LIMIT 1";
405 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
406 2 => array($ids['contributionRecur'], 'Integer'),
407 );
408 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
409 $ids['membership'] = $membershipId;
410 }
411 }
412
413 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
414 'PayPal', 'id', 'name'
415 );
416
417 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
418 return FALSE;
419 }
420
421 self::$_paymentProcessor = &$objects['paymentProcessor'];
422 //?? how on earth would we not have component be one of these?
423 // they are the only valid settings & this IPN file can't even be called without one of them
424 // grepping for this class doesn't find other paths to call this class
425 if ($this->_component == 'contribute' || $this->_component == 'event') {
426 if ($ids['contributionRecur']) {
427 // check if first contribution is completed, else complete first contribution
428 $first = TRUE;
429 if ($objects['contribution']->contribution_status_id == 1) {
430 $first = FALSE;
431 }
432 return $this->recur($input, $ids, $objects, $first);
433 }
434 else {
435 return $this->single($input, $ids, $objects, FALSE, FALSE);
436 }
437 }
438 else {
439 return $this->single($input, $ids, $objects, FALSE, FALSE);
440 }
441 }
442
443 /**
444 * @param $input
445 * @param $ids
446 *
447 * @throws CRM_Core_Exception
448 */
449 function getInput(&$input, &$ids) {
450
451 if (!$this->getBillingID($ids)) {
452 return FALSE;
453 }
454
455 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
456 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
457 $input['invoice'] = self::getValue('i', TRUE);
458
459 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
460 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
461
462 $billingID = $ids['billing'];
463 $lookup = array(
464 "first_name" => 'first_name',
465 "last_name" => 'last_name',
466 "street_address-{$billingID}" => 'address_street',
467 "city-{$billingID}" => 'address_city',
468 "state-{$billingID}" => 'address_state',
469 "postal_code-{$billingID}" => 'address_zip',
470 "country-{$billingID}" => 'address_country_code',
471 );
472 foreach ($lookup as $name => $paypalName) {
473 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
474 $input[$name] = $value ? $value : NULL;
475 }
476
477 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
478 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
479 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
480 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
481 $input['payment_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
482 }
483
484 /**
485 * Handle payment express IPNs
486 * For one off IPNS no actual response is required
487 * Recurring is more difficult as we have limited confirmation material
488 */
489 function handlePaymentExpress() {
490 throw new CRM_Core_Exception('Payment Express IPNS not currently handled');
491 }
492 }
493