commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / CRM / Core / Payment / BaseIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 * Class CRM_Core_Payment_BaseIPN.
30 */
31 class CRM_Core_Payment_BaseIPN {
32
33 static $_now = NULL;
34
35 /**
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
38 * @var array
39 */
40 protected $_inputParameters = array();
41
42 protected $_isRecurring = FALSE;
43
44 protected $_isFirstOrLastRecurringPayment = FALSE;
45
46 /**
47 * Constructor.
48 */
49 public 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 public 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 /**
68 * Validate incoming data.
69 *
70 * This function is intended to ensure that incoming data matches
71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
76 *
77 * @param array $input
78 * Interpreted values from the values returned through the IPN.
79 * @param array $ids
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
87 *
88 * @return bool
89 */
90 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
91
92 // make sure contact exists and is valid
93 $contact = new CRM_Contact_BAO_Contact();
94 $contact->id = $ids['contact'];
95 if (!$contact->find(TRUE)) {
96 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
97 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
98 return FALSE;
99 }
100
101 // make sure contribution exists and is valid
102 $contribution = new CRM_Contribute_BAO_Contribution();
103 $contribution->id = $ids['contribution'];
104 if (!$contribution->find(TRUE)) {
105 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
106 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
107 return FALSE;
108 }
109 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
110
111 $objects['contact'] = &$contact;
112 $objects['contribution'] = &$contribution;
113 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
114 return FALSE;
115 }
116 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
117 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
118 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
119 if (isset($objects['contributionRecur'])) {
120 $objects['first_contribution'] = $objects['contribution'];
121 }
122 return TRUE;
123 }
124
125 /**
126 * Load objects related to contribution.
127 *
128 * @input array information from Payment processor
129 *
130 * @param $input
131 * @param array $ids
132 * @param array $objects
133 * @param bool $required
134 * @param int $paymentProcessorID
135 * @param array $error_handling
136 *
137 * @return bool
138 */
139 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
140 if (empty($error_handling)) {
141 // default options are that we log an error & echo it out
142 // note that we should refactor this error handling into error code @ some point
143 // but for now setting up enough separation so we can do unit tests
144 $error_handling = array(
145 'log_error' => 1,
146 'echo_error' => 1,
147 );
148 }
149 $ids['paymentProcessor'] = $paymentProcessorID;
150 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
151 $contribution = &$objects['contribution'];
152 }
153 else {
154 //legacy support - functions are 'used' to be able to pass in a DAO
155 $contribution = new CRM_Contribute_BAO_Contribution();
156 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
157 $contribution->find(TRUE);
158 $objects['contribution'] = &$contribution;
159 }
160 try {
161 $success = $contribution->loadRelatedObjects($input, $ids, $required);
162 }
163 catch (Exception $e) {
164 $success = FALSE;
165 if (!empty($error_handling['log_error'])) {
166 CRM_Core_Error::debug_log_message($e->getMessage());
167 }
168 if (!empty($error_handling['echo_error'])) {
169 echo $e->getMessage();
170 }
171 if (!empty($error_handling['return_error'])) {
172 return array(
173 'is_error' => 1,
174 'error_message' => ($e->getMessage()),
175 );
176 }
177 }
178 $objects = array_merge($objects, $contribution->_relatedObjects);
179 return $success;
180 }
181
182 /**
183 * Set contribution to failed.
184 *
185 * @param array $objects
186 * @param object $transaction
187 * @param array $input
188 *
189 * @return bool
190 */
191 public function failed(&$objects, &$transaction, $input = array()) {
192 $contribution = &$objects['contribution'];
193 $memberships = array();
194 if (!empty($objects['membership'])) {
195 $memberships = &$objects['membership'];
196 if (is_numeric($memberships)) {
197 $memberships = array($objects['membership']);
198 }
199 }
200
201 $addLineItems = FALSE;
202 if (empty($contribution->id)) {
203 $addLineItems = TRUE;
204 }
205 $participant = &$objects['participant'];
206
207 //CRM-15546
208 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
209 'labelColumn' => 'name',
210 'flip' => 1,
211 ));
212 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
213 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
214 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
215 $contribution->contribution_status_id = $contributionStatuses['Failed'];
216 $contribution->save();
217
218 // Add line items for recurring payments.
219 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
220 $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
221 }
222
223 //add new soft credit against current contribution id and
224 //copy initial contribution custom fields for recurring contributions
225 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
226 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
227 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
228 }
229
230 if (empty($input['skipComponentSync'])) {
231 if (!empty($memberships)) {
232 // if transaction is failed then set "Cancelled" as membership status
233 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
234 'labelColumn' => 'name',
235 'flip' => 1,
236 ));
237 foreach ($memberships as $membership) {
238 if ($membership) {
239 $membership->status_id = $membershipStatuses['Cancelled'];
240 $membership->save();
241
242 //update related Memberships.
243 $params = array('status_id' => $membershipStatuses['Cancelled']);
244 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
245 }
246 }
247 }
248
249 if ($participant) {
250 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
251 'labelColumn' => 'name',
252 'flip' => 1,
253 ));
254 $participant->status_id = $participantStatuses['Cancelled'];
255 $participant->save();
256 }
257 }
258
259 $transaction->commit();
260 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
261 //echo "Success: Setting contribution status to failed<p>";
262 return TRUE;
263 }
264
265 /**
266 * Handled pending contribution status.
267 *
268 * @param array $objects
269 * @param object $transaction
270 *
271 * @return bool
272 */
273 public function pending(&$objects, &$transaction) {
274 $transaction->commit();
275 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
276 echo "Success: Returning since contribution status is pending<p>";
277 return TRUE;
278 }
279
280 /**
281 * Process cancelled payment outcome.
282 *
283 * @param $objects
284 * @param $transaction
285 * @param array $input
286 *
287 * @return bool
288 */
289 public function cancelled(&$objects, &$transaction, $input = array()) {
290 $contribution = &$objects['contribution'];
291 $memberships = &$objects['membership'];
292 if (is_numeric($memberships)) {
293 $memberships = array($objects['membership']);
294 }
295
296 $participant = &$objects['participant'];
297 $addLineItems = FALSE;
298 if (empty($contribution->id)) {
299 $addLineItems = TRUE;
300 }
301 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
302 'labelColumn' => 'name',
303 'flip' => 1,
304 ));
305 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
306 $contribution->cancel_date = self::$_now;
307 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
308 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
309 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
310 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
311 $contribution->save();
312
313 //add lineitems for recurring payments
314 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
315 $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
316 }
317
318 //add new soft credit against current $contribution and
319 //copy initial contribution custom fields for recurring contributions
320 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
321 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
322 $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
323 }
324
325 if (empty($input['skipComponentSync'])) {
326 if (!empty($memberships)) {
327 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
328 'labelColumn' => 'name',
329 'flip' => 1,
330 ));
331 // Cancel only Pending memberships
332 // CRM-18688
333 $pendingStatusId = $membershipStatuses['Pending'];
334 foreach ($memberships as $membership) {
335 if ($membership && ($membership->status_id == $pendingStatusId)) {
336 $membership->status_id = $membershipStatuses['Cancelled'];
337 $membership->save();
338
339 //update related Memberships.
340 $params = array('status_id' => $membershipStatuses['Cancelled']);
341 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
342 }
343 }
344 }
345
346 if ($participant) {
347 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
348 'labelColumn' => 'name',
349 'flip' => 1,
350 ));
351 $participant->status_id = $participantStatuses['Cancelled'];
352 $participant->save();
353 }
354 }
355 $transaction->commit();
356 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
357 //echo "Success: Setting contribution status to cancelled<p>";
358 return TRUE;
359 }
360
361 /**
362 * Rollback unhandled outcomes.
363 *
364 * @param $objects
365 * @param $transaction
366 *
367 * @return bool
368 */
369 public function unhandled(&$objects, &$transaction) {
370 $transaction->rollback();
371 CRM_Core_Error::debug_log_message("returning since contribution status: is not handled");
372 echo "Failure: contribution status is not handled<p>";
373 return FALSE;
374 }
375
376 /**
377 * Jumbled up function.
378 *
379 * The purpose of this function is to transition a pending transaction to Completed including updating any
380 * related entities.
381 *
382 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
383 * updating related entities.
384 *
385 * It is recommended to avoid calling this function directly and call the api functions:
386 * - contribution.completetransaction
387 * - contribution.repeattransaction
388 *
389 * These functions are the focus of testing efforts and more accurately reflect the division of roles
390 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
391 * and from there it should be possible to pass off transaction management.)
392 *
393 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
394 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
395 *
396 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
397 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
398 * a shared function that updates related components.
399 *
400 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
401 * IPN class is better accessed through the api which de-jumbles it a bit.
402 *
403 * e.g the payment class can have a function like (based on Omnipay extension):
404 *
405 * public function handlePaymentNotification() {
406 * $response = $this->getValidatedOutcome();
407 * if ($response->isSuccessful()) {
408 * try {
409 * // @todo check if it is a repeat transaction & call repeattransaction instead.
410 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
411 * }
412 * catch (CiviCRM_API3_Exception $e) {
413 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
414 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
415 * have occurred. Please check your receipt is correct');
416 * $this->redirectOrExit('success');
417 * }
418 * elseif ($this->transaction_id) {
419 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
420 * 'Failed'));
421 * }
422 *
423 * @param array $input
424 * @param array $ids
425 * @param array $objects
426 * @param $transaction
427 * @param bool $recur
428 */
429 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
430 $contribution = &$objects['contribution'];
431
432 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
433
434 $memberships = &$objects['membership'];
435 if (is_numeric($memberships)) {
436 $memberships = array($objects['membership']);
437 }
438 $participant = &$objects['participant'];
439
440 $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
441 $recurContrib = &$objects['contributionRecur'];
442
443 $values = array();
444 if (isset($input['is_email_receipt'])) {
445 $values['is_email_receipt'] = $input['is_email_receipt'];
446 }
447 $source = NULL;
448 if ($input['component'] == 'contribute') {
449 if ($contribution->contribution_page_id) {
450 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
451 $source = ts('Online Contribution') . ': ' . $values['title'];
452 }
453 elseif ($recurContrib && $recurContrib->id) {
454 $contribution->contribution_page_id = NULL;
455 $values['amount'] = $recurContrib->amount;
456 $values['financial_type_id'] = $objects['contributionType']->id;
457 $values['title'] = $source = ts('Offline Recurring Contribution');
458 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
459 $values['receipt_from_name'] = $domainValues[0];
460 $values['receipt_from_email'] = $domainValues[1];
461 }
462
463 if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
464 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
465 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
466 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
467 }
468
469 $contribution->source = $source;
470 if (!empty($values['is_email_receipt'])) {
471 $contribution->receipt_date = self::$_now;
472 }
473
474 if (!empty($memberships)) {
475 $membershipsUpdate = array();
476 foreach ($memberships as $membershipTypeIdKey => $membership) {
477 if ($membership) {
478 $format = '%Y%m%d';
479
480 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
481 $membership->membership_type_id,
482 $membership->is_test, $membership->id
483 );
484
485 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
486 // this picks up membership type changes during renewals
487 $sql = "
488 SELECT membership_type_id
489 FROM civicrm_membership_log
490 WHERE membership_id=$membership->id
491 ORDER BY id DESC
492 LIMIT 1;";
493 $dao = new CRM_Core_DAO();
494 $dao->query($sql);
495 if ($dao->fetch()) {
496 if (!empty($dao->membership_type_id)) {
497 $membership->membership_type_id = $dao->membership_type_id;
498 $membership->save();
499 }
500 // else fall back to using current membership type
501 }
502 // else fall back to using current membership type
503 $dao->free();
504
505 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
506 if ($currentMembership) {
507 /*
508 * Fixed FOR CRM-4433
509 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
510 * when Contribution mode is notify and membership is for renewal )
511 */
512 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
513
514 // @todo - we should pass membership_type_id instead of null here but not
515 // adding as not sure of testing
516 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
517 $changeToday, NULL, $num_terms
518 );
519
520 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
521 }
522 else {
523 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
524 }
525
526 //get the status for membership.
527 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
528 $dates['end_date'],
529 $dates['join_date'],
530 'today',
531 TRUE,
532 $membership->membership_type_id,
533 (array) $membership
534 );
535
536 $formatedParams = array(
537 'status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
538 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format),
539 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format),
540 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format),
541 );
542 //we might be renewing membership,
543 //so make status override false.
544 $formatedParams['is_override'] = FALSE;
545 $membership->copyValues($formatedParams);
546 $membership->save();
547
548 //updating the membership log
549 $membershipLog = array();
550 $membershipLog = $formatedParams;
551
552 $logStartDate = $formatedParams['start_date'];
553 if (!empty($dates['log_start_date'])) {
554 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
555 $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
556 }
557
558 $membershipLog['start_date'] = $logStartDate;
559 $membershipLog['membership_id'] = $membership->id;
560 $membershipLog['modified_id'] = $membership->contact_id;
561 $membershipLog['modified_date'] = date('Ymd');
562 $membershipLog['membership_type_id'] = $membership->membership_type_id;
563
564 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
565
566 //update related Memberships.
567 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
568
569 //update the membership type key of membership relatedObjects array
570 //if it has changed after membership update
571 if ($membershipTypeIdKey != $membership->membership_type_id) {
572 $membershipsUpdate[$membership->membership_type_id] = $membership;
573 $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
574 unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
575 unset($memberships[$membershipTypeIdKey]);
576 }
577 }
578 }
579 //update the memberships object with updated membershipTypeId data
580 //if membershipTypeId has changed after membership update
581 if (!empty($membershipsUpdate)) {
582 $memberships = $memberships + $membershipsUpdate;
583 }
584 }
585 }
586 else {
587 // event
588 $eventParams = array('id' => $objects['event']->id);
589 $values['event'] = array();
590
591 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
592
593 //get location details
594 $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
595 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
596
597 $ufJoinParams = array(
598 'entity_table' => 'civicrm_event',
599 'entity_id' => $ids['event'],
600 'module' => 'CiviEvent',
601 );
602
603 list($custom_pre_id,
604 $custom_post_ids
605 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
606
607 $values['custom_pre_id'] = $custom_pre_id;
608 $values['custom_post_id'] = $custom_post_ids;
609 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
610 //and cases involving status updation through ipn
611 $values['totalAmount'] = $input['amount'];
612
613 $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
614
615 if ($values['event']['is_email_confirm']) {
616 $contribution->receipt_date = self::$_now;
617 $values['is_email_receipt'] = 1;
618 }
619 if (empty($input['skipComponentSync'])) {
620 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
621 'labelColumn' => 'name',
622 'flip' => 1,
623 ));
624 $participant->status_id = $participantStatuses['Registered'];
625 }
626 $participant->save();
627 }
628
629 if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 &&
630 CRM_Utils_Array::value('fee_amount', $input, 0) != 0
631 ) {
632 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
633 }
634 // This complete transaction function is being overloaded to create new contributions too.
635 // here we record if it is a new contribution.
636 // @todo separate the 2 more appropriately.
637 $isNewContribution = FALSE;
638 if (empty($contribution->id)) {
639 $isNewContribution = TRUE;
640 if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
641 $contribution->total_amount = $input['amount'];
642 // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
643 // so we have to handle net_amount in this (naughty) code.
644 if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
645 $contribution->fee_amount = $input['fee_amount'];
646 }
647 $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
648 }
649 if (!empty($input['campaign_id'])) {
650 $contribution->campaign_id = $input['campaign_id'];
651 }
652 elseif (!empty($recurContrib->campaign_id)) {
653 $contribution->campaign_id = $recurContrib->campaign_id;
654 }
655 if (CRM_Contribute_BAO_Contribution::isSingleLineItem($primaryContributionID) && !empty($input['financial_type_id'])) {
656 $contribution->financial_type_id = $input['financial_type_id'];
657 }
658 }
659
660 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
661 'labelColumn' => 'name',
662 'flip' => 1,
663 ));
664
665 // @todo this section should call the api in order to have hooks called &
666 // because all this 'messiness' setting variables could be avoided
667 // by letting the api resolve pseudoconstants & copy set values and format dates.
668 $contribution->contribution_status_id = $contributionStatuses['Completed'];
669 $contribution->is_test = $input['is_test'];
670
671 // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
672 if (isset($input['net_amount'])) {
673 $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
674 }
675 if (isset($input['net_amount'])) {
676 $contribution->net_amount = $input['net_amount'];
677 }
678
679 $contribution->trxn_id = $input['trxn_id'];
680 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
681 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
682 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
683 $contribution->cancel_date = 'null';
684
685 if (!empty($input['check_number'])) {
686 $contribution->check_number = $input['check_number'];
687 }
688
689 if (!empty($input['payment_instrument_id'])) {
690 $contribution->payment_instrument_id = $input['payment_instrument_id'];
691 }
692
693 if (!empty($contribution->id)) {
694 $contributionId['id'] = $contribution->id;
695 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
696 }
697
698 $contribution->save();
699
700 // Add new soft credit against current $contribution.
701 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
702 $this->addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
703 }
704
705 //add line items for recurring payments
706 if (!empty($contribution->contribution_recur_id)) {
707 if ($isNewContribution) {
708 $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
709 }
710 else {
711 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
712 $input['line_item'] = array();
713 }
714 }
715
716 //copy initial contribution custom fields for recurring contributions
717 if ($recurContrib && $recurContrib->id) {
718 $this->copyCustomValues($recurContrib->id, $contribution->id);
719 }
720
721 // next create the transaction record
722 $paymentProcessor = $paymentProcessorId = '';
723 if (isset($objects['paymentProcessor'])) {
724 if (is_array($objects['paymentProcessor'])) {
725 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
726 $paymentProcessorId = $objects['paymentProcessor']['id'];
727 }
728 else {
729 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
730 $paymentProcessorId = $objects['paymentProcessor']->id;
731 }
732 }
733 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
734 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
735 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
736 // it would be good if someone added some comments or refactored this
737 if ($contribution->id) {
738 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
739 'labelColumn' => 'name',
740 'flip' => 1,
741 ));
742 if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
743 $input['payment_processor'] = $paymentProcessorId;
744 }
745 $input['contribution_status_id'] = $contributionStatuses['Completed'];
746 $input['total_amount'] = $input['amount'];
747 $input['contribution'] = $contribution;
748 $input['financial_type_id'] = $contribution->financial_type_id;
749
750 if (!empty($contribution->_relatedObjects['participant'])) {
751 $input['contribution_mode'] = 'participant';
752 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
753 $input['skipLineItem'] = 1;
754 }
755 elseif (!empty($contribution->_relatedObjects['membership'])) {
756 $input['skipLineItem'] = TRUE;
757 $input['contribution_mode'] = 'membership';
758 }
759 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
760 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
761 // and since the contribution is saved prior to this line there is always a contribution-id,
762 // however there is never a prevContribution (which appears to mean original contribution not previous
763 // contribution - or preUpdateContributionObject most accurately)
764 // so, this is always called & only appears to succeed when prevContribution exists - which appears
765 // to mean "are we updating an exisitng pending contribution"
766 //I was able to make the unit test complete as fataling here doesn't prevent
767 // the contribution being created - but activities would not be created or emails sent
768
769 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
770 }
771
772 self::updateRecurLinkedPledge($contribution);
773
774 // create an activity record
775 if ($input['component'] == 'contribute') {
776 //CRM-4027
777 $targetContactID = NULL;
778 if (!empty($ids['related_contact'])) {
779 $targetContactID = $contribution->contact_id;
780 $contribution->contact_id = $ids['related_contact'];
781 }
782 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
783 // event
784 }
785 else {
786 CRM_Activity_BAO_Activity::addActivity($participant);
787 }
788
789 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
790 $transaction->commit();
791
792 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
793 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
794 if (!array_key_exists('is_email_receipt', $values) ||
795 $values['is_email_receipt'] == 1
796 ) {
797 self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
798 CRM_Core_Error::debug_log_message("Receipt sent");
799 }
800
801 CRM_Core_Error::debug_log_message("Success: Database updated");
802 if ($this->_isRecurring) {
803 $this->sendRecurringStartOrEndNotification($ids, $recur);
804 }
805 }
806
807 /**
808 * Get site billing ID.
809 *
810 * @param array $ids
811 *
812 * @return bool
813 */
814 public function getBillingID(&$ids) {
815 // get the billing location type
816 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
817 // CRM-8108 remove the ts around the Billing location type
818 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
819 $ids['billing'] = array_search('Billing', $locationTypes);
820 if (!$ids['billing']) {
821 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
822 echo "Failure: Could not find billing location type<p>";
823 return FALSE;
824 }
825 return TRUE;
826 }
827
828 /**
829 * Send receipt from contribution.
830 *
831 * Note that the compose message part has been moved to contribution
832 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
833 *
834 * @param array $input
835 * Incoming data from Payment processor.
836 * @param array $ids
837 * Related object IDs.
838 * @param $objects
839 * @param array $values
840 * Values related to objects that have already been loaded.
841 * @param bool $recur
842 * Is it part of a recurring contribution.
843 * @param bool $returnMessageText
844 * Should text be returned instead of sent. This.
845 * is because the function is also used to generate pdfs
846 *
847 * @return array
848 */
849 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
850 $contribution = &$objects['contribution'];
851 $input['is_recur'] = $recur;
852 // set receipt from e-mail and name in value
853 if (!$returnMessageText) {
854 $session = CRM_Core_Session::singleton();
855 $userID = $session->get('userID');
856 if (!empty($userID)) {
857 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
858 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail);
859 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName);
860 }
861 }
862 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
863 }
864
865 /**
866 * Send start or end notification for recurring payments.
867 *
868 * @param array $ids
869 * @param $recur
870 */
871 public function sendRecurringStartOrEndNotification($ids, $recur) {
872 if ($this->_isFirstOrLastRecurringPayment) {
873 $autoRenewMembership = FALSE;
874 if ($recur->id &&
875 isset($ids['membership']) && $ids['membership']
876 ) {
877 $autoRenewMembership = TRUE;
878 }
879
880 //send recurring Notification email for user
881 CRM_Contribute_BAO_ContributionPage::recurringNotify($this->_isFirstOrLastRecurringPayment,
882 $ids['contact'],
883 $ids['contributionPage'],
884 $recur,
885 $autoRenewMembership
886 );
887 }
888 }
889
890 /**
891 * Update contribution status.
892 *
893 * @deprecated
894 * This is only called from one place in the code &
895 * it is unclear whether it is a function on the way in or on the way out
896 *
897 * @param array $params
898 *
899 * @return void|NULL|int
900 */
901 public function updateContributionStatus(&$params) {
902 // get minimum required values.
903 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
904 $componentId = CRM_Utils_Array::value('component_id', $params);
905 $componentName = CRM_Utils_Array::value('componentName', $params);
906 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
907
908 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
909 return NULL;
910 }
911
912 $input = $ids = $objects = array();
913
914 //get the required ids.
915 $ids['contribution'] = $contributionId;
916
917 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
918 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
919 $contributionId,
920 'contact_id'
921 );
922 }
923
924 if ($componentName == 'Event') {
925 $name = 'event';
926 $ids['participant'] = $componentId;
927
928 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
929 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
930 $componentId,
931 'event_id'
932 );
933 }
934 }
935
936 if ($componentName == 'Membership') {
937 $name = 'contribute';
938 $ids['membership'] = $componentId;
939 }
940 $ids['contributionPage'] = NULL;
941 $ids['contributionRecur'] = NULL;
942 $input['component'] = $name;
943
944 $baseIPN = new CRM_Core_Payment_BaseIPN();
945 $transaction = new CRM_Core_Transaction();
946
947 // reset template values.
948 $template = CRM_Core_Smarty::singleton();
949 $template->clearTemplateVars();
950
951 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
952 CRM_Core_Error::fatal();
953 }
954
955 $contribution = &$objects['contribution'];
956
957 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
958 'labelColumn' => 'name',
959 'flip' => 1,
960 ));
961 $input['skipComponentSync'] = CRM_Utils_Array::value('skipComponentSync', $params);
962 if ($statusId == $contributionStatuses['Cancelled']) {
963 $baseIPN->cancelled($objects, $transaction, $input);
964 $transaction->commit();
965 return $statusId;
966 }
967 elseif ($statusId == $contributionStatuses['Failed']) {
968 $baseIPN->failed($objects, $transaction, $input);
969 $transaction->commit();
970 return $statusId;
971 }
972
973 // status is not pending
974 if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
975 $transaction->commit();
976 return;
977 }
978
979 //set values for ipn code.
980 foreach (array(
981 'fee_amount',
982 'check_number',
983 'payment_instrument_id',
984 ) as $field) {
985 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
986 $input[$field] = $contribution->$field;
987 }
988 }
989 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
990 $input['trxn_id'] = $contribution->invoice_id;
991 }
992 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
993 $input['amount'] = $contribution->total_amount;
994 }
995 $input['is_test'] = $contribution->is_test;
996 $input['net_amount'] = $contribution->net_amount;
997 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
998 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
999 }
1000
1001 //complete the contribution.
1002 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
1003
1004 // reset template values before processing next transactions
1005 $template->clearTemplateVars();
1006
1007 return $statusId;
1008 }
1009
1010 /**
1011 * Update pledge associated with a recurring contribution.
1012 *
1013 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
1014 *
1015 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
1016 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
1017 * it should be assumed they
1018 * do so with the intention that all payments will be linked
1019 *
1020 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
1021 * If not the contribution will also need to be linked to the pledge
1022 *
1023 * @param CRM_Contribute_BAO_Contribution $contribution
1024 */
1025 public function updateRecurLinkedPledge(&$contribution) {
1026 $returnProperties = array('id', 'pledge_id');
1027 $paymentDetails = $paymentIDs = array();
1028
1029 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
1030 $paymentDetails, $returnProperties
1031 )
1032 ) {
1033 foreach ($paymentDetails as $key => $value) {
1034 $paymentIDs[] = $value['id'];
1035 $pledgeId = $value['pledge_id'];
1036 }
1037 }
1038 else {
1039 //payment is not already linked - if it is linked with a pledge we need to create a link.
1040 // return if it is not recurring contribution
1041 if (!$contribution->contribution_recur_id) {
1042 return;
1043 }
1044
1045 $relatedContributions = new CRM_Contribute_DAO_Contribution();
1046 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
1047 $relatedContributions->find();
1048
1049 while ($relatedContributions->fetch()) {
1050 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
1051 $paymentDetails, $returnProperties
1052 );
1053 }
1054
1055 if (empty($paymentDetails)) {
1056 // payment is not linked with a pledge and neither are any other contributions on this
1057 return;
1058 }
1059
1060 foreach ($paymentDetails as $key => $value) {
1061 $pledgeId = $value['pledge_id'];
1062 }
1063
1064 // we have a pledge now we need to get the oldest unpaid payment
1065 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
1066 if (empty($paymentDetails['id'])) {
1067 // we can assume this pledge is now completed
1068 // return now so we don't create a core error & roll back
1069 return;
1070 }
1071 $paymentDetails['contribution_id'] = $contribution->id;
1072 $paymentDetails['status_id'] = $contribution->contribution_status_id;
1073 $paymentDetails['actual_amount'] = $contribution->total_amount;
1074
1075 // put contribution against it
1076 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
1077 $paymentIDs[] = $payment->id;
1078 }
1079
1080 // update pledge and corresponding payment statuses
1081 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
1082 NULL, $contribution->total_amount
1083 );
1084 }
1085
1086 /**
1087 * Add line items for recurring contribution.
1088 *
1089 * @param int $recurId
1090 * @param $contribution
1091 *
1092 * @return array
1093 */
1094 public function addRecurLineItems($recurId, $contribution) {
1095 $lineSets = array();
1096
1097 $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1098 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
1099 if (count($lineItems) == 1) {
1100 foreach ($lineItems as $index => $lineItem) {
1101 if (isset($contribution->financial_type_id)) {
1102 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
1103 $lineItems[$index]['financial_type_id'] = $contribution->financial_type_id;
1104 }
1105 if ($lineItem['line_total'] != $contribution->total_amount) {
1106 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
1107 // if there is only one line item, and the UI should prevent this situation for those with more than one.
1108 $lineItems[$index]['line_total'] = $contribution->total_amount;
1109 $lineItems[$index]['unit_price'] = round($contribution->total_amount / $lineItems[$index]['qty'], 2);
1110 }
1111 }
1112 }
1113 CRM_Core_Error::debug_log_message("111111111");
1114 CRM_Core_Error::debug_log_message($recurId);
1115 CRM_Core_Error::debug_log_message($originalContributionID);
1116 CRM_Core_Error::debug_log_message(print_r($lineItems, TRUE));
1117 CRM_Core_Error::debug_log_message("111111111");
1118
1119 if (!empty($lineItems)) {
1120 foreach ($lineItems as $key => $value) {
1121 CRM_Core_Error::debug_log_message("222222");
1122 $priceField = new CRM_Price_DAO_PriceField();
1123 $priceField->id = $value['price_field_id'];
1124 $priceField->find(TRUE);
1125 $lineSets[$priceField->price_set_id][] = $value;
1126
1127 if ($value['entity_table'] == 'civicrm_membership') {
1128 CRM_Core_Error::debug_log_message("3333333:");
1129 try {
1130 civicrm_api3('membership_payment', 'create', array(
1131 'membership_id' => $value['entity_id'],
1132 'contribution_id' => $contribution->id,
1133 ));
1134 }
1135 catch (CiviCRM_API3_Exception $e) {
1136 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
1137 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
1138 }
1139 }
1140 }
1141 }
1142 else {
1143 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
1144 }
1145 return $lineSets;
1146 }
1147
1148 /**
1149 * Copy custom data of the initial contribution into its recurring contributions.
1150 *
1151 * @param int $recurId
1152 * @param int $targetContributionId
1153 */
1154 public function copyCustomValues($recurId, $targetContributionId) {
1155 if ($recurId && $targetContributionId) {
1156 // get the initial contribution id of recur id
1157 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1158
1159 // if the same contribution is being proccessed then return
1160 if ($sourceContributionId == $targetContributionId) {
1161 return;
1162 }
1163 // check if proper recurring contribution record is being processed
1164 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
1165 if ($targetConRecurId != $recurId) {
1166 return;
1167 }
1168
1169 // copy custom data
1170 $extends = array('Contribution');
1171 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
1172 if ($groupTree) {
1173 foreach ($groupTree as $groupID => $group) {
1174 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1175 foreach ($group['fields'] as $fieldID => $field) {
1176 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1177 }
1178 }
1179
1180 foreach ($table as $tableName => $tableColumns) {
1181 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1182 $tableColumns[0] = $targetContributionId;
1183 $select = 'SELECT ' . implode(', ', $tableColumns);
1184 $from = ' FROM ' . $tableName;
1185 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1186 $query = $insert . $select . $from . $where;
1187 CRM_Core_DAO::executeQuery($query);
1188 }
1189 }
1190 }
1191 }
1192
1193 /**
1194 * Add soft credit to for recurring payment.
1195 *
1196 * copy soft credit record of first recurring contribution.
1197 * and add new soft credit against $targetContributionId
1198 *
1199 * @param int $recurId
1200 * @param int $targetContributionId
1201 */
1202 public function addrecurSoftCredit($recurId, $targetContributionId) {
1203 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1204 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1205
1206 // Check if first recurring contribution has any associated soft credit.
1207 if ($soft_contribution->find(TRUE)) {
1208 $soft_contribution->contribution_id = $targetContributionId;
1209 unset($soft_contribution->id);
1210 $soft_contribution->save();
1211 }
1212 }
1213
1214 }