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