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