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