Merge pull request #852 from eileenmcnaughton/CRM-12687
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35 class CRM_Core_Payment_BaseIPN {
36
37 static $_now = NULL;
38 function __construct() {
39 self::$_now = date('YmdHis');
40 }
41
42 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
43
44 // make sure contact exists and is valid
45 $contact = new CRM_Contact_DAO_Contact();
46 $contact->id = $ids['contact'];
47 if (!$contact->find(TRUE)) {
48 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
49 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
50 return FALSE;
51 }
52
53 // make sure contribution exists and is valid
54 $contribution = new CRM_Contribute_DAO_Contribution();
55 $contribution->id = $ids['contribution'];
56 if (!$contribution->find(TRUE)) {
57 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
58 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
59 return FALSE;
60 }
61 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
62
63 $objects['contact'] = &$contact;
64 $objects['contribution'] = &$contribution;
65 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
66 return FALSE;
67 }
68
69 return TRUE;
70 }
71
72 function createContact(&$input, &$ids, &$objects) {
73 $params = array();
74 $billingID = $ids['billing'];
75 $lookup = array(
76 'first_name',
77 'last_name',
78 "street_address-{$billingID}",
79 "city-{$billingID}",
80 "state-{$billingID}",
81 "postal_code-{$billingID}",
82 "country-{$billingID}",
83 );
84 foreach ($lookup as $name) {
85 $params[$name] = $input[$name];
86 }
87 if (!empty($params)) {
88 // update contact record
89 $contact = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray, $ids['contact']);
90 }
91
92 return TRUE;
93 }
94
95 /*
96 * Load objects related to contribution
97 *
98 * @input array information from Payment processor
99 */
100 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
101 if (empty($error_handling)) {
102 // default options are that we log an error & echo it out
103 // note that we should refactor this error handling into error code @ some point
104 // but for now setting up enough separation so we can do unit tests
105 $error_handling = array(
106 'log_error' => 1,
107 'echo_error' => 1,
108 );
109 }
110 $ids['paymentProcessor'] = $paymentProcessorID;
111 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
112 $contribution = &$objects['contribution'];
113 }
114 else {
115 //legacy support - functions are 'used' to be able to pass in a DAO
116 $contribution = new CRM_Contribute_BAO_Contribution();
117 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
118 $contribution->find(TRUE);
119 $objects['contribution'] = &$contribution;
120 }
121 try {
122 $success = $contribution->loadRelatedObjects($input, $ids, $required);
123 }
124 catch(Exception$e) {
125 if (CRM_Utils_Array::value('log_error', $error_handling)) {
126 CRM_Core_Error::debug_log_message($e->getMessage());
127 }
128 if (CRM_Utils_Array::value('echo_error', $error_handling)) {
129 echo ($e->getMessage());
130 }
131 if (CRM_Utils_Array::value('return_error', $error_handling)) {
132 return array(
133 'is_error' => 1,
134 'error_message' => ($e->getMessage()),
135 );
136 }
137 }
138 $objects = array_merge($objects, $contribution->_relatedObjects);
139 return $success;
140 }
141
142 function failed(&$objects, &$transaction, $input = array()) {
143 $contribution = &$objects['contribution'];
144 $memberships = array();
145 if (CRM_Utils_Array::value('membership', $objects)) {
146 $memberships = &$objects['membership'];
147 if (is_numeric($memberships)) {
148 $memberships = array($objects['membership']);
149 }
150 }
151
152 $addLineItems = FALSE;
153 if (empty($contribution->id)) {
154 $addLineItems = TRUE;
155 }
156 $participant = &$objects['participant'];
157
158 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
159 $contribution->contribution_status_id = array_search('Failed', $contributionStatus);
160 $contribution->save();
161
162 //add lineitems for recurring payments
163 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
164 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
165 }
166
167 //copy initial contribution custom fields for recurring contributions
168 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
169 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
170 }
171
172 if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
173 if (!empty($memberships)) {
174 foreach ($memberships as $membership) {
175 if ($membership) {
176 $membership->status_id = 4;
177 $membership->save();
178
179 //update related Memberships.
180 $params = array('status_id' => 4);
181 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
182 }
183 }
184 }
185
186 if ($participant) {
187 $participant->status_id = 4;
188 $participant->save();
189 }
190 }
191
192 $transaction->commit();
193 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
194 //echo "Success: Setting contribution status to failed<p>";
195 return TRUE;
196 }
197
198 function pending(&$objects, &$transaction) {
199 $transaction->commit();
200 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
201 echo "Success: Returning since contribution status is pending<p>";
202 return TRUE;
203 }
204
205 function cancelled(&$objects, &$transaction, $input = array()) {
206 $contribution = &$objects['contribution'];
207 $memberships = &$objects['membership'];
208 if (is_numeric($memberships)) {
209 $memberships = array($objects['membership']);
210 }
211
212 $participant = &$objects['participant'];
213 $addLineItems = FALSE;
214 if (empty($contribution->id)) {
215 $addLineItems = TRUE;
216 }
217 $contribution->contribution_status_id = 3;
218 $contribution->cancel_date = self::$_now;
219 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
220 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
221 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
222 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
223 $contribution->save();
224
225 //add lineitems for recurring payments
226 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
227 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
228 }
229
230 //copy initial contribution custom fields for recurring contributions
231 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
232 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
233 }
234
235 if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
236 if (!empty($memberships)) {
237 foreach ($memberships as $membership) {
238 if ($membership) {
239 $membership->status_id = 6;
240 $membership->save();
241
242 //update related Memberships.
243 $params = array('status_id' => 6);
244 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
245 }
246 }
247 }
248
249 if ($participant) {
250 $participant->status_id = 4;
251 $participant->save();
252 }
253 }
254 $transaction->commit();
255 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
256 //echo "Success: Setting contribution status to cancelled<p>";
257 return TRUE;
258 }
259
260 function unhandled(&$objects, &$transaction) {
261 $transaction->rollback();
262 // we dont handle this as yet
263 CRM_Core_Error::debug_log_message("returning since contribution status: $status is not handled");
264 echo "Failure: contribution status $status is not handled<p>";
265 return FALSE;
266 }
267
268 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
269 $contribution = &$objects['contribution'];
270 $memberships = &$objects['membership'];
271 if (is_numeric($memberships)) {
272 $memberships = array($objects['membership']);
273 }
274 $participant = &$objects['participant'];
275 $event = &$objects['event'];
276 $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
277 $recurContrib = &$objects['contributionRecur'];
278
279 $values = array();
280 $source = NULL;
281 if ($input['component'] == 'contribute') {
282 if ($contribution->contribution_page_id) {
283 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
284 $source = ts('Online Contribution') . ': ' . $values['title'];
285 }
286 elseif ($recurContrib && $recurContrib->id) {
287 $contribution->contribution_page_id = NULL;
288 $values['amount'] = $recurContrib->amount;
289 $values['financial_type_id'] = $objects['contributionType']->id;
290 $values['title'] = $source = ts('Offline Recurring Contribution');
291 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
292 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
293 $values['receipt_from_name'] = $domainValues[0];
294 $values['receipt_from_email'] = $domainValues[1];
295 }
296
297 $contribution->source = $source;
298 if (CRM_Utils_Array::value('is_email_receipt', $values)) {
299 $contribution->receipt_date = self::$_now;
300 }
301
302 if (!empty($memberships)) {
303 $membershipsUpdate = array( );
304 foreach ($memberships as $membershipTypeIdKey => $membership) {
305 if ($membership) {
306 $format = '%Y%m%d';
307
308 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
309 $membership->membership_type_id,
310 $membership->is_test, $membership->id
311 );
312
313 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
314 // this picks up membership type changes during renewals
315 $sql = "
316 SELECT membership_type_id
317 FROM civicrm_membership_log
318 WHERE membership_id=$membership->id
319 ORDER BY id DESC
320 LIMIT 1;";
321 $dao = new CRM_Core_DAO;
322 $dao->query($sql);
323 if ($dao->fetch()) {
324 if (!empty($dao->membership_type_id)) {
325 $membership->membership_type_id = $dao->membership_type_id;
326 $membership->save();
327 }
328 // else fall back to using current membership type
329 }
330 // else fall back to using current membership type
331 $dao->free();
332
333 if ($currentMembership) {
334 /*
335 * Fixed FOR CRM-4433
336 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
337 * when Contribution mode is notify and membership is for renewal )
338 */
339 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
340
341 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
342 $changeToday
343 );
344 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
345 }
346 else {
347 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
348 }
349
350 //get the status for membership.
351 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
352 $dates['end_date'],
353 $dates['join_date'],
354 'today',
355 TRUE
356 );
357
358 $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
359 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format),
360 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format),
361 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format),
362 );
363 //we might be renewing membership,
364 //so make status override false.
365 $formatedParams['is_override'] = FALSE;
366 $membership->copyValues($formatedParams);
367 $membership->save();
368
369 //updating the membership log
370 $membershipLog = array();
371 $membershipLog = $formatedParams;
372
373 $logStartDate = $formatedParams['start_date'];
374 if (CRM_Utils_Array::value('log_start_date', $dates)) {
375 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
376 $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
377 }
378
379 $membershipLog['start_date'] = $logStartDate;
380 $membershipLog['membership_id'] = $membership->id;
381 $membershipLog['modified_id'] = $membership->contact_id;
382 $membershipLog['modified_date'] = date('Ymd');
383 $membershipLog['membership_type_id'] = $membership->membership_type_id;
384
385 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
386
387 //update related Memberships.
388 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
389
390 //update the membership type key of membership relatedObjects array
391 //if it has changed after membership update
392 if ($membershipTypeIdKey != $membership->membership_type_id) {
393 $membershipsUpdate[$membership->membership_type_id] = $membership;
394 $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
395 unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
396 unset($memberships[$membershipTypeIdKey]);
397 }
398 }
399 }
400 //update the memberships object with updated membershipTypeId data
401 //if membershipTypeId has changed after membership update
402 if (!empty($membershipsUpdate)) {
403 $memberships = $memberships + $membershipsUpdate;
404 }
405 }
406 }
407 else {
408 // event
409 $eventParams = array('id' => $objects['event']->id);
410 $values['event'] = array();
411
412 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
413
414 //get location details
415 $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
416 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
417
418 $ufJoinParams = array(
419 'entity_table' => 'civicrm_event',
420 'entity_id' => $ids['event'],
421 'module' => 'CiviEvent',
422 );
423
424 list($custom_pre_id,
425 $custom_post_ids
426 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
427
428 $values['custom_pre_id'] = $custom_pre_id;
429 $values['custom_post_id'] = $custom_post_ids;
430
431 $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
432
433 if ($values['event']['is_email_confirm']) {
434 $contribution->receipt_date = self::$_now;
435 $values['is_email_receipt'] = 1;
436 }
437 if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
438 $participant->status_id = 1;
439 }
440 $participant->save();
441 }
442
443 if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 &&
444 CRM_Utils_Array::value('fee_amount', $input, 0) != 0
445 ) {
446 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
447 }
448 $addLineItems = FALSE;
449 if (empty($contribution->id)) {
450 $addLineItems = TRUE;
451 }
452
453 $contribution->contribution_status_id = 1;
454 $contribution->is_test = $input['is_test'];
455 $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
456 $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
457 $contribution->trxn_id = $input['trxn_id'];
458 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
459 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
460 $contribution->cancel_date = 'null';
461
462 if (CRM_Utils_Array::value('check_number', $input)) {
463 $contribution->check_number = $input['check_number'];
464 }
465
466 if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
467 $contribution->payment_instrument_id = $input['payment_instrument_id'];
468 }
469
470 if ($contribution->id) {
471 $contributionId['id'] = $contribution->id;
472 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
473 }
474 $contribution->save();
475
476 //add lineitems for recurring payments
477 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
478 $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
479 }
480
481 //copy initial contribution custom fields for recurring contributions
482 if ($recurContrib && $recurContrib->id) {
483 $this->copyCustomValues($recurContrib->id, $contribution->id);
484 }
485
486 // next create the transaction record
487 $paymentProcessor = $paymentProcessorId = '';
488 if (isset($objects['paymentProcessor'])) {
489 if (is_array($objects['paymentProcessor'])) {
490 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
491 $paymentProcessorId = $objects['paymentProcessor']['id'];
492 }
493 else {
494 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
495 $paymentProcessorId = $objects['paymentProcessor']->id;
496 }
497 }
498
499 if ($contribution->id) {
500 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
501 if (!$input['prevContribution']->is_pay_later &&
502 $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
503 $input['payment_processor'] = $paymentProcessorId;
504 }
505 $input['total_amount'] = $input['amount'];
506 $input['contribution'] = $contribution;
507 $input['financial_type_id'] = $contribution->financial_type_id;
508
509 if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
510 $input['contribution_mode'] = 'participant';
511 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
512 $input['skipLineItem'] = 1;
513 }
514
515 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
516 }
517
518 self::updateRecurLinkedPledge($contribution);
519
520 // create an activity record
521 if ($input['component'] == 'contribute') {
522 //CRM-4027
523 $targetContactID = NULL;
524 if (CRM_Utils_Array::value('related_contact', $ids)) {
525 $targetContactID = $contribution->contact_id;
526 $contribution->contact_id = $ids['related_contact'];
527 }
528 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
529 // event
530 }
531 else {
532 CRM_Activity_BAO_Activity::addActivity($participant);
533 }
534
535 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
536 $transaction->commit();
537
538 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
539 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
540 if (!array_key_exists('is_email_receipt', $values) ||
541 $values['is_email_receipt'] == 1
542 ) {
543 self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
544 CRM_Core_Error::debug_log_message("Receipt sent");
545 }
546
547 CRM_Core_Error::debug_log_message("Success: Database updated");
548 }
549
550 function getBillingID(&$ids) {
551 // get the billing location type
552 $locationTypes = CRM_Core_PseudoConstant::locationType();
553 // CRM-8108 remove the ts around the Billing locationtype
554 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
555 $ids['billing'] = array_search('Billing', $locationTypes);
556 if (!$ids['billing']) {
557 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
558 echo "Failure: Could not find billing location type<p>";
559 return FALSE;
560 }
561 return TRUE;
562 }
563
564 /*
565 * Send receipt from contribution. Note that the compose message part has been moved to contribution
566 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
567 *
568 * @params array $input Incoming data from Payment processor
569 * @params array $ids Related object IDs
570 * @params array $values values related to objects that have already been loaded
571 * @params bool $recur is it part of a recurring contribution
572 * @params bool $returnMessageText Should text be returned instead of sent. This
573 * is because the function is also used to generate pdfs
574 */
575 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
576 $contribution = &$objects['contribution'];
577 $input['is_recur'] = $recur;
578 // set receipt from e-mail and name in value
579 if (!$returnMessageText) {
580 $session = CRM_Core_Session::singleton();
581 $userID = $session->get('userID');
582 if (!empty($userID)) {
583 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
584 $values['receipt_from_email'] = $userEmail;
585 $values['receipt_from_name'] = $userName;
586 }
587 }
588 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
589 }
590
591 function updateContributionStatus(&$params) {
592 // get minimum required values.
593 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
594 $componentId = CRM_Utils_Array::value('component_id', $params);
595 $componentName = CRM_Utils_Array::value('componentName', $params);
596 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
597
598 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
599 return;
600 }
601
602 $input = $ids = $objects = array();
603
604 //get the required ids.
605 $ids['contribution'] = $contributionId;
606
607 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
608 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
609 $contributionId,
610 'contact_id'
611 );
612 }
613
614 if ($componentName == 'Event') {
615 $name = 'event';
616 $ids['participant'] = $componentId;
617
618 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
619 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
620 $componentId,
621 'event_id'
622 );
623 }
624 }
625
626 if ($componentName == 'Membership') {
627 $name = 'contribute';
628 $ids['membership'] = $componentId;
629 }
630 $ids['contributionPage'] = NULL;
631 $ids['contributionRecur'] = NULL;
632 $input['component'] = $name;
633
634 $baseIPN = new CRM_Core_Payment_BaseIPN();
635 $transaction = new CRM_Core_Transaction();
636
637 // reset template values.
638 $template = CRM_Core_Smarty::singleton();
639 $template->clearTemplateVars();
640
641 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
642 CRM_Core_Error::fatal();
643 }
644
645 $contribution = &$objects['contribution'];
646
647 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
648 $input['skipComponentSync'] = CRM_Utils_Array::value('skipComponentSync', $params);
649 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
650 $baseIPN->cancelled($objects, $transaction, $input);
651 $transaction->commit();
652 return $statusId;
653 }
654 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
655 $baseIPN->failed($objects, $transaction, $input);
656 $transaction->commit();
657 return $statusId;
658 }
659
660 // status is not pending
661 if ($contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
662 $transaction->commit();
663 return;
664 }
665
666 //set values for ipn code.
667 foreach (array(
668 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
669 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
670 $input[$field] = $contribution->$field;
671 }
672 }
673 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
674 $input['trxn_id'] = $contribution->invoice_id;
675 }
676 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
677 $input['amount'] = $contribution->total_amount;
678 }
679 $input['is_test'] = $contribution->is_test;
680 $input['net_amount'] = $contribution->net_amount;
681 if (CRM_Utils_Array::value('fee_amount', $input) && CRM_Utils_Array::value('amount', $input)) {
682 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
683 }
684
685 //complete the contribution.
686 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
687
688 // reset template values before processing next transactions
689 $template->clearTemplateVars();
690
691 return $statusId;
692 }
693
694 /*
695 * Update pledge associated with a recurring contribution
696 *
697 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
698 *
699 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
700 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
701 * it should be assumed they
702 * do so with the intention that all payments will be linked
703 *
704 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
705 * If not the contribution will also need to be linked to the pledge
706 */
707 function updateRecurLinkedPledge(&$contribution) {
708 $returnProperties = array('id', 'pledge_id');
709 $paymentDetails = $paymentIDs = array();
710
711 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
712 $paymentDetails, $returnProperties
713 )) {
714 foreach ($paymentDetails as $key => $value) {
715 $paymentIDs[] = $value['id'];
716 $pledgeId = $value['pledge_id'];
717 }
718 }
719 else {
720 //payment is not already linked - if it is linked with a pledge we need to create a link.
721 // return if it is not recurring contribution
722 if (!$contribution->contribution_recur_id) {
723 return;
724 }
725
726 $relatedContributions = new CRM_Contribute_DAO_Contribution();
727 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
728 $relatedContributions->find();
729
730 while ($relatedContributions->fetch()) {
731 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
732 $paymentDetails, $returnProperties
733 );
734 }
735
736 if (empty($paymentDetails)) {
737 // payment is not linked with a pledge and neither are any other contributions on this
738 return;
739 }
740
741 foreach ($paymentDetails as $key => $value) {
742 $pledgeId = $value['pledge_id'];
743 }
744
745 // we have a pledge now we need to get the oldest unpaid payment
746 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
747 if(empty($paymentDetails['id'])){
748 // we can assume this pledge is now completed
749 // return now so we don't create a core error & roll back
750 return;
751 }
752 $paymentDetails['contribution_id'] = $contribution->id;
753 $paymentDetails['status_id'] = $contribution->contribution_status_id;
754 $paymentDetails['actual_amount'] = $contribution->total_amount;
755
756 // put contribution against it
757 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
758 $paymentIDs[] = $payment->id;
759 }
760
761 // update pledge and corresponding payment statuses
762 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
763 NULL, $contribution->total_amount
764 );
765 }
766
767 function addrecurLineItems($recurId, $contributionId) {
768 $lineSets = $lineItems = array();
769
770 //Get the first contribution id with recur id
771 if ($recurId) {
772 $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
773 $lineItems = CRM_Price_BAO_LineItem::getLineItems($contriID, 'contribution');
774 if (!empty($lineItems)) {
775 foreach ($lineItems as $key => $value) {
776 $pricesetID = new CRM_Price_DAO_Field();
777 $pricesetID->id = $value['price_field_id'];
778 $pricesetID->find(TRUE);
779 $lineSets[$pricesetID->price_set_id][] = $value;
780 }
781 }
782
783 CRM_Price_BAO_LineItem::processPriceSet($contributionId, $lineSets);
784 }
785 }
786
787 // function to copy custom data of the
788 // initial contribution into its recurring contributions
789 function copyCustomValues($recurId, $targetContributionId) {
790 if ($recurId && $targetContributionId) {
791 // get the initial contribution id of recur id
792 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
793
794 // if the same contribution is being proccessed then return
795 if ($sourceContributionId == $targetContributionId) {
796 return;
797 }
798 // check if proper recurring contribution record is being processed
799 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
800 if ($targetConRecurId != $recurId) {
801 return;
802 }
803
804 // copy custom data
805 $extends = array('Contribution');
806 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
807 if ($groupTree) {
808 foreach ($groupTree as $groupID => $group) {
809 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
810 foreach ($group['fields'] as $fieldID => $field) {
811 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
812 }
813 }
814
815 foreach ($table as $tableName => $tableColumns) {
816 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
817 $tableColumns[0] = $targetContributionId;
818 $select = 'SELECT ' . implode(', ', $tableColumns);
819 $from = ' FROM ' . $tableName;
820 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
821 $query = $insert . $select . $from . $where;
822 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
823 }
824 }
825 }
826 }
827 }