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