Merge pull request #6567 from eileenmcnaughton/CRM-17064
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
34
35 /**
36 * Create recurring contribution.
37 *
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
40 *
41 * @return object
42 * activity contact object
43 */
44 public static function create(&$params) {
45 return self::add($params);
46 }
47
48 /**
49 * Takes an associative array and creates a contribution object.
50 *
51 * the function extract all the params it needs to initialize the create a
52 * contribution object. the params array could contain additional unused name/value
53 * pairs
54 *
55 * @param array $params
56 * (reference ) an assoc array of name/value pairs.
57 *
58 * @return CRM_Contribute_BAO_Contribution
59 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
60 */
61 public static function add(&$params) {
62 if (!empty($params['id'])) {
63 CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
64 }
65 else {
66 CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
67 }
68
69 // make sure we're not creating a new recurring contribution with the same transaction ID
70 // or invoice ID as an existing recurring contribution
71 $duplicates = array();
72 if (self::checkDuplicate($params, $duplicates)) {
73 $error = CRM_Core_Error::singleton();
74 $d = implode(', ', $duplicates);
75 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
76 'Fatal',
77 array($d),
78 "Found matching recurring contribution(s): $d"
79 );
80 return $error;
81 }
82
83 $recurring = new CRM_Contribute_BAO_ContributionRecur();
84 $recurring->copyValues($params);
85 $recurring->id = CRM_Utils_Array::value('id', $params);
86
87 // set currency for CRM-1496
88 if (!isset($recurring->currency)) {
89 $config = CRM_Core_Config::singleton();
90 $recurring->currency = $config->defaultCurrency;
91 }
92 $result = $recurring->save();
93
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
96 }
97 else {
98 CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
99 }
100
101 return $result;
102 }
103
104 /**
105 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
106 *
107 * @param array $params
108 * (reference ) an assoc array of name/value pairs.
109 * @param array $duplicates
110 * (reference ) store ids of duplicate contribs.
111 *
112 * @return bool
113 * true if duplicate, false otherwise
114 */
115 public static function checkDuplicate($params, &$duplicates) {
116 $id = CRM_Utils_Array::value('id', $params);
117 $trxn_id = CRM_Utils_Array::value('trxn_id', $params);
118 $invoice_id = CRM_Utils_Array::value('invoice_id', $params);
119
120 $clause = array();
121 $params = array();
122
123 if ($trxn_id) {
124 $clause[] = "trxn_id = %1";
125 $params[1] = array($trxn_id, 'String');
126 }
127
128 if ($invoice_id) {
129 $clause[] = "invoice_id = %2";
130 $params[2] = array($invoice_id, 'String');
131 }
132
133 if (empty($clause)) {
134 return FALSE;
135 }
136
137 $clause = implode(' OR ', $clause);
138 if ($id) {
139 $clause = "( $clause ) AND id != %3";
140 $params[3] = array($id, 'Integer');
141 }
142
143 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
144 $dao = CRM_Core_DAO::executeQuery($query, $params);
145 $result = FALSE;
146 while ($dao->fetch()) {
147 $duplicates[] = $dao->id;
148 $result = TRUE;
149 }
150 return $result;
151 }
152
153 /**
154 * @param int $id
155 * @param $mode
156 *
157 * @return array|null
158 */
159 public static function getPaymentProcessor($id, $mode) {
160 //FIX ME:
161 $sql = "
162 SELECT r.payment_processor_id
163 FROM civicrm_contribution_recur r
164 WHERE r.id = %1";
165 $params = array(1 => array($id, 'Integer'));
166 $paymentProcessorID = &CRM_Core_DAO::singleValueQuery($sql,
167 $params
168 );
169 if (!$paymentProcessorID) {
170 return NULL;
171 }
172
173 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
174 }
175
176 /**
177 * Get the number of installment done/completed for each recurring contribution
178 *
179 * @param array $ids
180 * (reference ) an array of recurring contribution ids.
181 *
182 * @return array
183 * an array of recurring ids count
184 */
185 public static function getCount(&$ids) {
186 $recurID = implode(',', $ids);
187 $totalCount = array();
188
189 $query = "
190 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
191 FROM civicrm_contribution
192 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
193 GROUP BY contribution_recur_id";
194
195 $res = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
196
197 while ($res->fetch()) {
198 $totalCount[$res->contribution_recur_id] = $res->commpleted;
199 }
200 return $totalCount;
201 }
202
203 /**
204 * Delete Recurring contribution.
205 *
206 * @param int $recurId
207 *
208 * @return bool
209 */
210 public static function deleteRecurContribution($recurId) {
211 $result = FALSE;
212 if (!$recurId) {
213 return $result;
214 }
215
216 $recur = new CRM_Contribute_DAO_ContributionRecur();
217 $recur->id = $recurId;
218 $result = $recur->delete();
219
220 return $result;
221 }
222
223 /**
224 * Cancel Recurring contribution.
225 *
226 * @param int $recurId
227 * Recur contribution id.
228 * @param array $objects
229 * An array of objects that is to be cancelled like.
230 * contribution, membership, event. At least contribution object is a must.
231 *
232 * @param array $activityParams
233 *
234 * @return bool
235 */
236 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
237 if (!$recurId) {
238 return FALSE;
239 }
240
241 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
242 $canceledId = array_search('Cancelled', $contributionStatus);
243 $recur = new CRM_Contribute_DAO_ContributionRecur();
244 $recur->id = $recurId;
245 $recur->whereAdd("contribution_status_id != $canceledId");
246
247 if ($recur->find(TRUE)) {
248 $transaction = new CRM_Core_Transaction();
249 $recur->contribution_status_id = $canceledId;
250 $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
251 $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
252 $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
253 $recur->cancel_date = date('YmdHis');
254 $recur->save();
255
256 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
257 if ($dao && $dao->recur_id) {
258 $details = CRM_Utils_Array::value('details', $activityParams);
259 if ($dao->auto_renew && $dao->membership_id) {
260 // its auto-renewal membership mode
261 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
262 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
263 $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
264 $details .= '
265 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
266 }
267 else {
268 $details .= '
269 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
270 1 => $dao->amount,
271 2 => $dao->frequency_interval,
272 3 => $dao->frequency_unit,
273 ));
274 }
275 $activityParams = array(
276 'source_contact_id' => $dao->contact_id,
277 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
278 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
279 'Cancel Recurring Contribution',
280 'name'
281 ),
282 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
283 'details' => $details,
284 'activity_date_time' => date('YmdHis'),
285 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
286 'Completed',
287 'name'
288 ),
289 );
290 $session = CRM_Core_Session::singleton();
291 $cid = $session->get('userID');
292 if ($cid) {
293 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
294 $activityParams['source_contact_id'] = $cid;
295 }
296 CRM_Activity_BAO_Activity::create($activityParams);
297 }
298
299 // if there are associated objects, cancel them as well
300 if ($objects == CRM_Core_DAO::$_nullObject) {
301 $transaction->commit();
302 return TRUE;
303 }
304 else {
305 $baseIPN = new CRM_Core_Payment_BaseIPN();
306 return $baseIPN->cancelled($objects, $transaction);
307 }
308 }
309 else {
310 // if already cancelled, return true
311 $recur->whereAdd();
312 $recur->whereAdd("contribution_status_id = $canceledId");
313 if ($recur->find(TRUE)) {
314 return TRUE;
315 }
316 }
317
318 return FALSE;
319 }
320
321 /**
322 * Get list of recurring contribution of contact Ids.
323 *
324 * @param int $contactId
325 * Contact ID.
326 *
327 * @return array
328 * list of recurring contribution fields
329 *
330 */
331 public static function getRecurContributions($contactId) {
332 $params = array();
333 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
334 $recurDAO->contact_id = $contactId;
335 $recurDAO->find();
336 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
337
338 while ($recurDAO->fetch()) {
339 $params[$recurDAO->id]['id'] = $recurDAO->id;
340 $params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
341 $params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
342 $params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
343 $params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
344 $params[$recurDAO->id]['amount'] = $recurDAO->amount;
345 $params[$recurDAO->id]['currency'] = $recurDAO->currency;
346 $params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
347 $params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
348 $params[$recurDAO->id]['installments'] = $recurDAO->installments;
349 $params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
350 $params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
351 $params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
352 $params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
353 }
354
355 return $params;
356 }
357
358 /**
359 * @param int $entityID
360 * @param string $entity
361 *
362 * @return null|Object
363 */
364 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
365 $sql = "
366 SELECT rec.id as recur_id,
367 rec.processor_id as subscription_id,
368 rec.frequency_interval,
369 rec.installments,
370 rec.frequency_unit,
371 rec.amount,
372 rec.is_test,
373 rec.auto_renew,
374 rec.currency,
375 con.id as contribution_id,
376 con.contribution_page_id,
377 rec.contact_id,
378 mp.membership_id";
379
380 if ($entity == 'recur') {
381 $sql .= "
382 FROM civicrm_contribution_recur rec
383 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
384 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
385 WHERE rec.id = %1
386 GROUP BY rec.id";
387 }
388 elseif ($entity == 'contribution') {
389 $sql .= "
390 FROM civicrm_contribution con
391 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
392 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
393 WHERE con.id = %1";
394 }
395 elseif ($entity == 'membership') {
396 $sql .= "
397 FROM civicrm_membership_payment mp
398 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
399 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
400 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
401 WHERE mp.membership_id = %1";
402 }
403
404 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
405 if ($dao->fetch()) {
406 return $dao;
407 }
408 else {
409 return CRM_Core_DAO::$_nullObject;
410 }
411 }
412
413 public static function setSubscriptionContext() {
414 // handle context redirection for subscription url
415 $session = CRM_Core_Session::singleton();
416 if ($session->get('userID')) {
417 $url = FALSE;
418 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
419 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
420 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
421 $context = CRM_Utils_Request::retrieve('context', 'String');
422 if ($cid) {
423 switch ($context) {
424 case 'contribution':
425 $url = CRM_Utils_System::url('civicrm/contact/view',
426 "reset=1&selectedChild=contribute&cid={$cid}"
427 );
428 break;
429
430 case 'membership':
431 $url = CRM_Utils_System::url('civicrm/contact/view',
432 "reset=1&selectedChild=member&cid={$cid}"
433 );
434 break;
435
436 case 'dashboard':
437 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
438 break;
439 }
440 }
441 if ($mid) {
442 switch ($context) {
443 case 'dashboard':
444 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
445 break;
446
447 case 'search':
448 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
449 break;
450 }
451 }
452 if ($url) {
453 $session->pushUserContext($url);
454 }
455 }
456 }
457
458 /**
459 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
460 * @param array $fields
461 * The input form values.
462 * @param array $files
463 * The uploaded files if any.
464 * @param $self
465 */
466 public static function validateRecurContribution($fields, $files, $self, &$errors) {
467 if (!empty($fields['is_recur'])) {
468 if ($fields['frequency_interval'] <= 0) {
469 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
470 }
471 if ($fields['frequency_unit'] == '0') {
472 $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
473 }
474 }
475 }
476
477 /**
478 * Send start or end notification for recurring payments.
479 *
480 * @param array $ids
481 * @param CRM_Contribute_BAO_ContributionRecur $recur
482 * @param bool $isFirstOrLastRecurringPayment
483 */
484 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
485 if ($isFirstOrLastRecurringPayment) {
486 $autoRenewMembership = FALSE;
487 if ($recur->id &&
488 isset($ids['membership']) && $ids['membership']
489 ) {
490 $autoRenewMembership = TRUE;
491 }
492
493 //send recurring Notification email for user
494 CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
495 $ids['contact'],
496 $ids['contributionPage'],
497 $recur,
498 $autoRenewMembership
499 );
500 }
501 }
502
503 /**
504 * Copy custom data of the initial contribution into its recurring contributions.
505 *
506 * @param int $recurId
507 * @param int $targetContributionId
508 */
509 static public function copyCustomValues($recurId, $targetContributionId) {
510 if ($recurId && $targetContributionId) {
511 // get the initial contribution id of recur id
512 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
513
514 // if the same contribution is being processed then return
515 if ($sourceContributionId == $targetContributionId) {
516 return;
517 }
518 // check if proper recurring contribution record is being processed
519 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
520 if ($targetConRecurId != $recurId) {
521 return;
522 }
523
524 // copy custom data
525 $extends = array('Contribution');
526 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
527 if ($groupTree) {
528 foreach ($groupTree as $groupID => $group) {
529 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
530 foreach ($group['fields'] as $fieldID => $field) {
531 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
532 }
533 }
534
535 foreach ($table as $tableName => $tableColumns) {
536 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
537 $tableColumns[0] = $targetContributionId;
538 $select = 'SELECT ' . implode(', ', $tableColumns);
539 $from = ' FROM ' . $tableName;
540 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
541 $query = $insert . $select . $from . $where;
542 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
543 }
544 }
545 }
546 }
547
548 /**
549 * Add soft credit to for recurring payment.
550 *
551 * copy soft credit record of first recurring contribution.
552 * and add new soft credit against $targetContributionId
553 *
554 * @param int $recurId
555 * @param int $targetContributionId
556 */
557 public static function addrecurSoftCredit($recurId, $targetContributionId) {
558 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
559 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
560
561 // Check if first recurring contribution has any associated soft credit.
562 if ($soft_contribution->find(TRUE)) {
563 $soft_contribution->contribution_id = $targetContributionId;
564 unset($soft_contribution->id);
565 $soft_contribution->save();
566 }
567 }
568
569 /**
570 * Add line items for recurring contribution.
571 *
572 * @param int $recurId
573 * @param $contribution
574 *
575 * @return array
576 */
577 public static function addRecurLineItems($recurId, $contribution) {
578 $lineSets = array();
579
580 $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
581 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
582 if (count($lineItems) == 1) {
583 foreach ($lineItems as $index => $lineItem) {
584 if ($lineItem['line_total'] != $contribution->total_amount) {
585 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
586 // if there is only one line item, and the UI should prevent this situation for those with more than one.
587 $lineItems[$index]['line_total'] = $contribution->total_amount;
588 $lineItems[$index]['unit_price'] = round($contribution->total_amount / $lineItems[$index]['qty'], 2);
589 }
590 }
591 }
592 if (!empty($lineItems)) {
593 foreach ($lineItems as $key => $value) {
594 $priceField = new CRM_Price_DAO_PriceField();
595 $priceField->id = $value['price_field_id'];
596 $priceField->find(TRUE);
597 $lineSets[$priceField->price_set_id][] = $value;
598
599 if ($value['entity_table'] == 'civicrm_membership') {
600 try {
601 civicrm_api3('membership_payment', 'create', array(
602 'membership_id' => $value['entity_id'],
603 'contribution_id' => $contribution->id,
604 ));
605 }
606 catch (CiviCRM_API3_Exception $e) {
607 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
608 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
609 }
610 }
611 }
612 }
613 else {
614 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
615 }
616 return $lineSets;
617 }
618
619 /**
620 * Update pledge associated with a recurring contribution.
621 *
622 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
623 *
624 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
625 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
626 * it should be assumed they
627 * do so with the intention that all payments will be linked
628 *
629 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
630 * If not the contribution will also need to be linked to the pledge
631 *
632 * @param CRM_Contribute_BAO_Contribution $contribution
633 */
634 public static function updateRecurLinkedPledge($contribution) {
635 $returnProperties = array('id', 'pledge_id');
636 $paymentDetails = $paymentIDs = array();
637
638 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
639 $paymentDetails, $returnProperties
640 )
641 ) {
642 foreach ($paymentDetails as $key => $value) {
643 $paymentIDs[] = $value['id'];
644 $pledgeId = $value['pledge_id'];
645 }
646 }
647 else {
648 //payment is not already linked - if it is linked with a pledge we need to create a link.
649 // return if it is not recurring contribution
650 if (!$contribution->contribution_recur_id) {
651 return;
652 }
653
654 $relatedContributions = new CRM_Contribute_DAO_Contribution();
655 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
656 $relatedContributions->find();
657
658 while ($relatedContributions->fetch()) {
659 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
660 $paymentDetails, $returnProperties
661 );
662 }
663
664 if (empty($paymentDetails)) {
665 // payment is not linked with a pledge and neither are any other contributions on this
666 return;
667 }
668
669 foreach ($paymentDetails as $key => $value) {
670 $pledgeId = $value['pledge_id'];
671 }
672
673 // we have a pledge now we need to get the oldest unpaid payment
674 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
675 if (empty($paymentDetails['id'])) {
676 // we can assume this pledge is now completed
677 // return now so we don't create a core error & roll back
678 return;
679 }
680 $paymentDetails['contribution_id'] = $contribution->id;
681 $paymentDetails['status_id'] = $contribution->contribution_status_id;
682 $paymentDetails['actual_amount'] = $contribution->total_amount;
683
684 // put contribution against it
685 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
686 $paymentIDs[] = $payment->id;
687 }
688
689 // update pledge and corresponding payment statuses
690 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
691 NULL, $contribution->total_amount
692 );
693 }
694
695 }