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