dev/core#128 Add deprecated warning helper function
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
34
35 /**
fe482240 36 * Create recurring contribution.
6a488035 37 *
014c4014
TO
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
6a488035 40 *
a6c01b45
CW
41 * @return object
42 * activity contact object
6a488035 43 */
00be9182 44 public static function create(&$params) {
6a488035
TO
45 return self::add($params);
46 }
47
48 /**
fe482240 49 * Takes an associative array and creates a contribution object.
6a488035
TO
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 *
014c4014
TO
55 * @param array $params
56 * (reference ) an assoc array of name/value pairs.
fd31fa4c 57 *
81716ddb 58 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
6a488035
TO
59 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
60 */
00be9182 61 public static function add(&$params) {
a7488080 62 if (!empty($params['id'])) {
6a488035
TO
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
8f7b45b0 88 if (empty($params['id']) && !isset($recurring->currency)) {
6a488035
TO
89 $config = CRM_Core_Config::singleton();
90 $recurring->currency = $config->defaultCurrency;
91 }
92 $result = $recurring->save();
93
a7488080 94 if (!empty($params['id'])) {
6a488035
TO
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
95974e8e
DG
101 if (!empty($params['custom']) &&
102 is_array($params['custom'])
103 ) {
104 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution_recur', $recurring->id);
105 }
106
6a488035
TO
107 return $result;
108 }
109
110 /**
fe482240 111 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
6a488035 112 *
014c4014
TO
113 * @param array $params
114 * (reference ) an assoc array of name/value pairs.
115 * @param array $duplicates
c0f62075 116 * (reference ) store ids of duplicate contributions.
6a488035 117 *
e7483cbe 118 * @return bool
a6c01b45 119 * true if duplicate, false otherwise
6a488035 120 */
00be9182 121 public static function checkDuplicate($params, &$duplicates) {
353ffa53
TO
122 $id = CRM_Utils_Array::value('id', $params);
123 $trxn_id = CRM_Utils_Array::value('trxn_id', $params);
6a488035
TO
124 $invoice_id = CRM_Utils_Array::value('invoice_id', $params);
125
126 $clause = array();
127 $params = array();
128
129 if ($trxn_id) {
130 $clause[] = "trxn_id = %1";
131 $params[1] = array($trxn_id, 'String');
132 }
133
134 if ($invoice_id) {
135 $clause[] = "invoice_id = %2";
136 $params[2] = array($invoice_id, 'String');
137 }
138
139 if (empty($clause)) {
140 return FALSE;
141 }
142
143 $clause = implode(' OR ', $clause);
144 if ($id) {
145 $clause = "( $clause ) AND id != %3";
146 $params[3] = array($id, 'Integer');
147 }
148
353ffa53
TO
149 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
150 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
151 $result = FALSE;
152 while ($dao->fetch()) {
153 $duplicates[] = $dao->id;
154 $result = TRUE;
155 }
156 return $result;
157 }
158
186c9c17 159 /**
c0f62075 160 * Get the payment processor (array) for a recurring processor.
161 *
100fef9d 162 * @param int $id
c0f62075 163 * @param string $mode
164 * - Test or NULL - all other variants are ignored.
186c9c17
EM
165 *
166 * @return array|null
167 */
c0f62075 168 public static function getPaymentProcessor($id, $mode = NULL) {
6a488035
TO
169 $sql = "
170SELECT r.payment_processor_id
171 FROM civicrm_contribution_recur r
172 WHERE r.id = %1";
173 $params = array(1 => array($id, 'Integer'));
c0f62075 174 $paymentProcessorID = CRM_Core_DAO::singleValueQuery($sql,
6a488035
TO
175 $params
176 );
177 if (!$paymentProcessorID) {
178 return NULL;
179 }
180
181 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
182 }
183
184 /**
c0f62075 185 * Get the number of installment done/completed for each recurring contribution.
6a488035 186 *
014c4014
TO
187 * @param array $ids
188 * (reference ) an array of recurring contribution ids.
6a488035 189 *
a6c01b45
CW
190 * @return array
191 * an array of recurring ids count
6a488035 192 */
00be9182 193 public static function getCount(&$ids) {
6a488035
TO
194 $recurID = implode(',', $ids);
195 $totalCount = array();
196
d5828a02 197 $query = "
6a488035
TO
198 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
199 FROM civicrm_contribution
200 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
201 GROUP BY contribution_recur_id";
202
33621c4f 203 $res = CRM_Core_DAO::executeQuery($query);
6a488035
TO
204
205 while ($res->fetch()) {
206 $totalCount[$res->contribution_recur_id] = $res->commpleted;
207 }
208 return $totalCount;
209 }
210
211 /**
212 * Delete Recurring contribution.
213 *
100fef9d 214 * @param int $recurId
da6b46f4 215 *
ca26cb52 216 * @return bool
6a488035 217 */
00be9182 218 public static function deleteRecurContribution($recurId) {
6a488035
TO
219 $result = FALSE;
220 if (!$recurId) {
221 return $result;
222 }
223
353ffa53 224 $recur = new CRM_Contribute_DAO_ContributionRecur();
6a488035 225 $recur->id = $recurId;
353ffa53 226 $result = $recur->delete();
6a488035
TO
227
228 return $result;
229 }
230
231 /**
232 * Cancel Recurring contribution.
233 *
014c4014
TO
234 * @param int $recurId
235 * Recur contribution id.
236 * @param array $objects
237 * An array of objects that is to be cancelled like.
6a488035
TO
238 * contribution, membership, event. At least contribution object is a must.
239 *
dd244018
EM
240 * @param array $activityParams
241 *
ca26cb52 242 * @return bool
6a488035 243 */
00be9182 244 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
6a488035
TO
245 if (!$recurId) {
246 return FALSE;
247 }
248
249 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
353ffa53
TO
250 $canceledId = array_search('Cancelled', $contributionStatus);
251 $recur = new CRM_Contribute_DAO_ContributionRecur();
252 $recur->id = $recurId;
6a488035
TO
253 $recur->whereAdd("contribution_status_id != $canceledId");
254
255 if ($recur->find(TRUE)) {
256 $transaction = new CRM_Core_Transaction();
257 $recur->contribution_status_id = $canceledId;
258 $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
259 $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
260 $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
261 $recur->cancel_date = date('YmdHis');
262 $recur->save();
263
264 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
bbf58b03 265 if ($dao && $dao->recur_id) {
6a488035
TO
266 $details = CRM_Utils_Array::value('details', $activityParams);
267 if ($dao->auto_renew && $dao->membership_id) {
268 // its auto-renewal membership mode
269 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
353ffa53
TO
270 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
271 $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
6a488035
TO
272 $details .= '
273<br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
274 }
275 else {
276 $details .= '
277<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
353ffa53 278 1 => $dao->amount,
6a488035 279 2 => $dao->frequency_interval,
21dfd5f5 280 3 => $dao->frequency_unit,
6a488035
TO
281 ));
282 }
283 $activityParams = array(
284 'source_contact_id' => $dao->contact_id,
285 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
d66c61b6 286 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Cancel Recurring Contribution'),
6a488035
TO
287 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
288 'details' => $details,
289 'activity_date_time' => date('YmdHis'),
d66c61b6 290 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
6a488035
TO
291 );
292 $session = CRM_Core_Session::singleton();
293 $cid = $session->get('userID');
294 if ($cid) {
295 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
296 $activityParams['source_contact_id'] = $cid;
297 }
d66c61b6 298 // @todo use the api & do less wrangling above
6a488035
TO
299 CRM_Activity_BAO_Activity::create($activityParams);
300 }
301
302 // if there are associated objects, cancel them as well
1273d77c 303 if (!$objects) {
6a488035
TO
304 $transaction->commit();
305 return TRUE;
306 }
307 else {
d66c61b6 308 // @todo - this is bad! Get the function out of the ipn.
6a488035
TO
309 $baseIPN = new CRM_Core_Payment_BaseIPN();
310 return $baseIPN->cancelled($objects, $transaction);
311 }
312 }
313 else {
314 // if already cancelled, return true
315 $recur->whereAdd();
316 $recur->whereAdd("contribution_status_id = $canceledId");
317 if ($recur->find(TRUE)) {
318 return TRUE;
319 }
320 }
321
322 return FALSE;
323 }
324
325 /**
9e475c2d 326 * @deprecated Get list of recurring contribution of contact Ids.
6a488035 327 *
014c4014
TO
328 * @param int $contactId
329 * Contact ID.
6a488035 330 *
a6c01b45
CW
331 * @return array
332 * list of recurring contribution fields
6a488035 333 *
6a488035 334 */
00be9182 335 public static function getRecurContributions($contactId) {
496320c3 336 CRM_Core_Error::deprecatedFunctionWarning('ContributionRecur.get API instead');
6a488035
TO
337 $params = array();
338 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
339 $recurDAO->contact_id = $contactId;
340 $recurDAO->find();
341 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
342
343 while ($recurDAO->fetch()) {
344 $params[$recurDAO->id]['id'] = $recurDAO->id;
345 $params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
346 $params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
347 $params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
0d4bfc19 348 $params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
6a488035
TO
349 $params[$recurDAO->id]['amount'] = $recurDAO->amount;
350 $params[$recurDAO->id]['currency'] = $recurDAO->currency;
351 $params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
352 $params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
353 $params[$recurDAO->id]['installments'] = $recurDAO->installments;
354 $params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
355 $params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
356 $params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
357 $params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
358 }
359
360 return $params;
361 }
362
186c9c17 363 /**
100fef9d 364 * @param int $entityID
186c9c17
EM
365 * @param string $entity
366 *
367 * @return null|Object
368 */
00be9182 369 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
6a488035 370 $sql = "
d5828a02
DL
371SELECT rec.id as recur_id,
372 rec.processor_id as subscription_id,
6a488035
TO
373 rec.frequency_interval,
374 rec.installments,
375 rec.frequency_unit,
376 rec.amount,
377 rec.is_test,
378 rec.auto_renew,
379 rec.currency,
7083dc2a 380 rec.campaign_id,
467fe956 381 rec.financial_type_id,
0c6c47a5 382 rec.next_sched_contribution_date,
383 rec.failure_retry_date,
384 rec.cycle_day,
467fe956 385 con.id as contribution_id,
6a488035 386 con.contribution_page_id,
f0a7bcb5 387 rec.contact_id,
6a488035
TO
388 mp.membership_id";
389
390 if ($entity == 'recur') {
391 $sql .= "
d5828a02 392 FROM civicrm_contribution_recur rec
f0a7bcb5 393LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
6a488035 394LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
0ee5581e 395 WHERE rec.id = %1";
6a488035
TO
396 }
397 elseif ($entity == 'contribution') {
398 $sql .= "
399 FROM civicrm_contribution con
d5828a02 400INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
6a488035
TO
401LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
402 WHERE con.id = %1";
403 }
404 elseif ($entity == 'membership') {
405 $sql .= "
d5828a02
DL
406 FROM civicrm_membership_payment mp
407INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
6a488035
TO
408INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
409INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
410 WHERE mp.membership_id = %1";
411 }
412
413 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
414 if ($dao->fetch()) {
415 return $dao;
416 }
d5828a02 417 else {
467fe956 418 return NULL;
419 }
420 }
421
422 /**
423 * Does the recurring contribution support financial type change.
424 *
425 * This is conditional on there being only one line item or if there are no contributions as yet.
426 *
427 * (This second is a bit of an unusual condition but might occur in the context of a
428 *
429 * @param int $id
430 *
431 * @return bool
432 */
433 public static function supportsFinancialTypeChange($id) {
434 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
435 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
436 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
437 return FALSE;
438 }
439 $contribution = self::getTemplateContribution($id);
440 return CRM_Contribute_BAO_Contribution::isSingleLineItem($contribution['id']);
441 }
442
443 /**
444 * Get the contribution to be used as the template for later contributions.
445 *
446 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
447 *
448 * @param int $id
43c8d1dd 449 * @param array $overrides
450 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
467fe956 451 *
452 * @return array
453 * @throws \CiviCRM_API3_Exception
454 */
43c8d1dd 455 public static function getTemplateContribution($id, $overrides = array()) {
467fe956 456 $templateContribution = civicrm_api3('Contribution', 'get', array(
457 'contribution_recur_id' => $id,
458 'options' => array('limit' => 1, 'sort' => array('id DESC')),
459 'sequential' => 1,
893a550c 460 'contribution_test' => '',
467fe956 461 ));
462 if ($templateContribution['count']) {
43c8d1dd 463 $result = array_merge($templateContribution['values'][0], $overrides);
464 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
465 return $result;
d5828a02 466 }
467fe956 467 return array();
6a488035
TO
468 }
469
00be9182 470 public static function setSubscriptionContext() {
6a488035
TO
471 // handle context redirection for subscription url
472 $session = CRM_Core_Session::singleton();
473 if ($session->get('userID')) {
c490a46a
CW
474 $url = FALSE;
475 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
476 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
477 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
478 $context = CRM_Utils_Request::retrieve('context', 'String');
6a488035
TO
479 if ($cid) {
480 switch ($context) {
481 case 'contribution':
482 $url = CRM_Utils_System::url('civicrm/contact/view',
483 "reset=1&selectedChild=contribute&cid={$cid}"
484 );
485 break;
486
487 case 'membership':
488 $url = CRM_Utils_System::url('civicrm/contact/view',
489 "reset=1&selectedChild=member&cid={$cid}"
490 );
491 break;
492
493 case 'dashboard':
494 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
495 break;
496 }
497 }
498 if ($mid) {
499 switch ($context) {
500 case 'dashboard':
501 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
502 break;
503
504 case 'search':
505 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
506 break;
507 }
508 }
509 if ($url) {
510 $session->pushUserContext($url);
511 }
512 }
513 }
96025800 514
0223e233
WA
515 /**
516 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
ea3ddccf 517 *
0223e233
WA
518 * @param array $fields
519 * The input form values.
520 * @param array $files
521 * The uploaded files if any.
ea3ddccf 522 * @param CRM_Core_Form $self
523 * @param array $errors
0223e233 524 */
577d1236
WA
525 public static function validateRecurContribution($fields, $files, $self, &$errors) {
526 if (!empty($fields['is_recur'])) {
527 if ($fields['frequency_interval'] <= 0) {
528 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
529 }
530 if ($fields['frequency_unit'] == '0') {
531 $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).');
532 }
533 }
534 }
0223e233 535
e577770c
EM
536 /**
537 * Send start or end notification for recurring payments.
538 *
539 * @param array $ids
540 * @param CRM_Contribute_BAO_ContributionRecur $recur
541 * @param bool $isFirstOrLastRecurringPayment
542 */
543 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
544 if ($isFirstOrLastRecurringPayment) {
545 $autoRenewMembership = FALSE;
546 if ($recur->id &&
547 isset($ids['membership']) && $ids['membership']
548 ) {
549 $autoRenewMembership = TRUE;
550 }
551
552 //send recurring Notification email for user
553 CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
554 $ids['contact'],
555 $ids['contributionPage'],
556 $recur,
557 $autoRenewMembership
558 );
559 }
560 }
561
562 /**
563 * Copy custom data of the initial contribution into its recurring contributions.
564 *
565 * @param int $recurId
566 * @param int $targetContributionId
567 */
568 static public function copyCustomValues($recurId, $targetContributionId) {
569 if ($recurId && $targetContributionId) {
570 // get the initial contribution id of recur id
571 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
572
573 // if the same contribution is being processed then return
574 if ($sourceContributionId == $targetContributionId) {
575 return;
576 }
577 // check if proper recurring contribution record is being processed
578 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
579 if ($targetConRecurId != $recurId) {
580 return;
581 }
582
583 // copy custom data
584 $extends = array('Contribution');
585 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
586 if ($groupTree) {
587 foreach ($groupTree as $groupID => $group) {
588 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
589 foreach ($group['fields'] as $fieldID => $field) {
590 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
591 }
592 }
593
594 foreach ($table as $tableName => $tableColumns) {
d4721930 595 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
e577770c
EM
596 $tableColumns[0] = $targetContributionId;
597 $select = 'SELECT ' . implode(', ', $tableColumns);
598 $from = ' FROM ' . $tableName;
599 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
600 $query = $insert . $select . $from . $where;
33621c4f 601 CRM_Core_DAO::executeQuery($query);
e577770c
EM
602 }
603 }
604 }
605 }
606
607 /**
608 * Add soft credit to for recurring payment.
609 *
610 * copy soft credit record of first recurring contribution.
611 * and add new soft credit against $targetContributionId
612 *
613 * @param int $recurId
614 * @param int $targetContributionId
615 */
616 public static function addrecurSoftCredit($recurId, $targetContributionId) {
617 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
618 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
619
620 // Check if first recurring contribution has any associated soft credit.
621 if ($soft_contribution->find(TRUE)) {
622 $soft_contribution->contribution_id = $targetContributionId;
623 unset($soft_contribution->id);
624 $soft_contribution->save();
625 }
626 }
627
628 /**
629 * Add line items for recurring contribution.
630 *
631 * @param int $recurId
81716ddb 632 * @param \CRM_Contribute_BAO_Contribution $contribution
e577770c
EM
633 *
634 * @return array
635 */
636 public static function addRecurLineItems($recurId, $contribution) {
43c8d1dd 637 $foundLineItems = FALSE;
638
639 $lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
640 foreach ($lineSets as $lineItems) {
641 if (!empty($lineItems)) {
642 foreach ($lineItems as $key => $value) {
643 if ($value['entity_table'] == 'civicrm_membership') {
644 try {
645 // @todo this should be done by virtue of editing the line item as this link
646 // is deprecated. This may be the case but needs testing.
647 civicrm_api3('membership_payment', 'create', array(
648 'membership_id' => $value['entity_id'],
649 'contribution_id' => $contribution->id,
0e0da23f 650 'is_transactional' => FALSE,
43c8d1dd 651 ));
652 }
653 catch (CiviCRM_API3_Exception $e) {
654 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
655 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
656 }
e577770c
EM
657 }
658 }
43c8d1dd 659 $foundLineItems = TRUE;
e577770c
EM
660 }
661 }
43c8d1dd 662 if (!$foundLineItems) {
e577770c
EM
663 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
664 }
665 return $lineSets;
666 }
667
668 /**
669 * Update pledge associated with a recurring contribution.
670 *
671 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
672 *
673 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
674 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
675 * it should be assumed they
676 * do so with the intention that all payments will be linked
677 *
678 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
679 * If not the contribution will also need to be linked to the pledge
680 *
294cc627 681 * @param int $contributionID
682 * @param int $contributionRecurID
683 * @param int $contributionStatusID
684 * @param float $contributionAmount
685 *
686 * @throws \CiviCRM_API3_Exception
e577770c 687 */
294cc627 688 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
e577770c
EM
689 $returnProperties = array('id', 'pledge_id');
690 $paymentDetails = $paymentIDs = array();
691
294cc627 692 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
e577770c
EM
693 $paymentDetails, $returnProperties
694 )
695 ) {
696 foreach ($paymentDetails as $key => $value) {
697 $paymentIDs[] = $value['id'];
698 $pledgeId = $value['pledge_id'];
699 }
700 }
701 else {
702 //payment is not already linked - if it is linked with a pledge we need to create a link.
703 // return if it is not recurring contribution
294cc627 704 if (!$contributionRecurID) {
e577770c
EM
705 return;
706 }
707
708 $relatedContributions = new CRM_Contribute_DAO_Contribution();
294cc627 709 $relatedContributions->contribution_recur_id = $contributionRecurID;
e577770c
EM
710 $relatedContributions->find();
711
712 while ($relatedContributions->fetch()) {
713 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
714 $paymentDetails, $returnProperties
715 );
716 }
717
718 if (empty($paymentDetails)) {
719 // payment is not linked with a pledge and neither are any other contributions on this
720 return;
721 }
722
723 foreach ($paymentDetails as $key => $value) {
724 $pledgeId = $value['pledge_id'];
725 }
726
727 // we have a pledge now we need to get the oldest unpaid payment
728 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
729 if (empty($paymentDetails['id'])) {
730 // we can assume this pledge is now completed
731 // return now so we don't create a core error & roll back
732 return;
733 }
294cc627 734 $paymentDetails['contribution_id'] = $contributionID;
735 $paymentDetails['status_id'] = $contributionStatusID;
736 $paymentDetails['actual_amount'] = $contributionAmount;
e577770c
EM
737
738 // put contribution against it
294cc627 739 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
740 $paymentIDs[] = $payment['id'];
e577770c
EM
741 }
742
743 // update pledge and corresponding payment statuses
294cc627 744 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
745 NULL, $contributionAmount
e577770c
EM
746 );
747 }
748
24782d26 749 /**
81716ddb 750 * @param CRM_Core_Form $form
24782d26 751 */
752 public static function recurringContribution(&$form) {
753 // Recurring contribution fields
754 foreach (self::getRecurringFields() as $key => $label) {
55feaf27 755 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
24782d26 756 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
757 ) {
758 $form->assign('contribution_recur_pane_open', TRUE);
759 break;
760 }
761 CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
762 // If data has been entered for a recurring field, tell the tpl layer to open the pane
55feaf27 763 if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
24782d26 764 $form->assign('contribution_recur_pane_open', TRUE);
765 break;
766 }
767 }
768
24782d26 769 // Add field to check if payment is made for recurring contribution
770 $recurringPaymentOptions = array(
c6021c27
ML
771 1 => ts('All recurring contributions'),
772 2 => ts('Recurring contributions with at least one payment'),
24782d26 773 );
5aae2a90 774 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
24782d26 775 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
776 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
777 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
778 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
779 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
780 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
5af1389d
VH
781
782 // Add field for contribution status
783 $form->addSelect('contribution_recur_contribution_status_id',
784 array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant::contributionStatus())
785 );
786
24782d26 787 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
788 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
86a0d21e
CW
789
790 CRM_Core_BAO_Query::addCustomFormFields($form, array('ContributionRecur'));
791
24782d26 792 }
793
794 /**
795 * Get fields for recurring contributions.
796 *
797 * @return array
798 */
799 public static function getRecurringFields() {
800 return array(
801 'contribution_recur_payment_made' => ts(''),
802 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
803 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
804 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
805 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
806 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
807 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
808 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
809 );
810 }
811
91259407 812 /**
813 * Update recurring contribution based on incoming payment.
814 *
815 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
816 *
817 * @param int $recurringContributionID
818 * @param string $paymentStatus
819 * Payment status - this correlates to the machine name of the contribution status ID ie
820 * - Completed
821 * - Failed
822 *
823 * @throws \CiviCRM_API3_Exception
824 */
050e11d5 825 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
46f459f2 826
827 $effectiveDate = $effectiveDate ? date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
91259407 828 if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
829 return;
830 }
831 $params = array(
832 'id' => $recurringContributionID,
833 'return' => array(
834 'contribution_status_id',
835 'next_sched_contribution_date',
836 'frequency_unit',
837 'frequency_interval',
838 'installments',
839 'failure_count',
840 ),
841 );
842
843 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
844
845 if ($paymentStatus == 'Completed'
846 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
847 $params['contribution_status_id'] = 'In Progress';
848 }
849 if ($paymentStatus == 'Failed') {
850 $params['failure_count'] = $existing['failure_count'];
851 }
852 $params['modified_date'] = date('Y-m-d H:i:s');
853
854 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
855 $params['contribution_status_id'] = 'Completed';
856 }
857 else {
858 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
859 // the scheduled date themselves as core did not previously provide any help.
48f50324 860 if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) ==
050e11d5 861 strtotime($effectiveDate)) {
862 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
91259407 863 }
864 }
865 civicrm_api3('ContributionRecur', 'create', $params);
866 }
867
868 /**
869 * Is this recurring contribution now complete.
870 *
871 * Have all the payments expected been received now.
872 *
873 * @param int $recurringContributionID
874 * @param int $installments
875 *
876 * @return bool
877 */
878 protected static function isComplete($recurringContributionID, $installments) {
879 $paidInstallments = CRM_Core_DAO::singleValueQuery(
050e11d5 880 'SELECT count(*) FROM civicrm_contribution
881 WHERE contribution_recur_id = %1
882 AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
91259407 883 array(1 => array($recurringContributionID, 'Integer'))
884 );
885 if ($paidInstallments >= $installments) {
886 return TRUE;
887 }
888 return FALSE;
889 }
890
43c8d1dd 891 /**
892 * Calculate line items for the relevant recurring calculation.
893 *
894 * @param int $recurId
895 * @param string $total_amount
896 * @param int $financial_type_id
897 *
898 * @return array
899 */
900 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
2b0de476
E
901 $originalContribution = civicrm_api3('Contribution', 'getsingle', array(
902 'contribution_recur_id' => $recurId,
903 'contribution_test' => '',
904 'options' => ['limit' => 1],
905 'return' => ['id', 'financial_type_id'],
906 ));
907 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContribution['id']);
7150b1c8 908 $lineSets = array();
43c8d1dd 909 if (count($lineItems) == 1) {
910 foreach ($lineItems as $index => $lineItem) {
2b0de476
E
911 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
912 // CRM-20685, Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1, So this conditional will set the financial_type_id as the original if line_item and contribution comes with different data.
913 $financial_type_id = $lineItem['financial_type_id'];
914 }
43c8d1dd 915 if ($financial_type_id) {
916 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
917 $lineItem['financial_type_id'] = $financial_type_id;
918 }
919 if ($lineItem['line_total'] != $total_amount) {
920 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
921 // if there is only one line item, and the UI should prevent this situation for those with more than one.
922 $lineItem['line_total'] = $total_amount;
923 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
924 }
925 $priceField = new CRM_Price_DAO_PriceField();
926 $priceField->id = $lineItem['price_field_id'];
927 $priceField->find(TRUE);
928 $lineSets[$priceField->price_set_id][] = $lineItem;
929 }
930 }
7150b1c8 931 // CRM-19309 if more than one then just pass them through:
0e6ccb2e
K
932 elseif (count($lineItems) > 1) {
933 foreach ($lineItems as $index => $lineItem) {
934 $lineSets[$index][] = $lineItem;
935 }
936 }
937
43c8d1dd 938 return $lineSets;
939 }
940
6a488035 941}