Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-10-26-14-28-29
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.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_Contribution extends CRM_Contribute_DAO_Contribution {
34
35 /**
36 * Static field for all the contribution information that we can potentially import
37 *
38 * @var array
39 */
40 static $_importableFields = NULL;
41
42 /**
43 * Static field for all the contribution information that we can potentially export
44 *
45 * @var array
46 */
47 static $_exportableFields = NULL;
48
49 /**
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
52 */
53 public $_relatedObjects = array();
54
55 /**
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
60 *
61 * @var string component or event
62 */
63 public $_component = NULL;
64
65 /**
66 * Possibly obsolete variable.
67 *
68 * If you use it please explain why it is set in the create function here.
69 *
70 * @var string
71 */
72 public $trxn_result_code;
73
74 /**
75 * Class constructor.
76 *
77 * @return \CRM_Contribute_DAO_Contribution
78 */
79 /**
80 */
81 public function __construct() {
82 parent::__construct();
83 }
84
85 /**
86 * Takes an associative array and creates a contribution object.
87 *
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
90 * pairs
91 *
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
94 * @param array $ids
95 * The array that holds all the db ids.
96 *
97 * @return CRM_Contribute_BAO_Contribution|void
98 */
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
101 return NULL;
102 }
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
105 $duplicates = array();
106 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
110 'Fatal',
111 array($d),
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
113 );
114 return $error;
115 }
116
117 // first clean up all the money fields
118 $moneyFields = array(
119 'total_amount',
120 'net_amount',
121 'fee_amount',
122 'non_deductible_amount',
123 );
124
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
128 }
129
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
133 }
134 }
135
136 //if contribution is created with cancelled or refunded status, add credit note id
137 if (!empty($params['contribution_status_id'])) {
138 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
139
140 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
141 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
142 ) {
143 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
144 $params['creditnote_id'] = self::createCreditNoteId();
145 }
146 }
147 }
148
149 //set defaults in create mode
150 if (!$contributionID) {
151 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
152 }
153 self::calculateMissingAmountParams($params, $contributionID);
154
155 if (!empty($params['payment_instrument_id'])) {
156 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
157 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
158 $params['check_number'] = 'null';
159 }
160 }
161
162 $setPrevContribution = TRUE;
163 // CRM-13964 partial payment
164 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
165 $partialAmtTotal = $params['partial_payment_total'];
166 $partialAmtPay = $params['partial_amount_pay'];
167 $params['total_amount'] = $partialAmtTotal;
168 if ($partialAmtPay < $partialAmtTotal) {
169 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
170 $params['is_pay_later'] = 0;
171 $setPrevContribution = FALSE;
172 }
173 }
174 if ($contributionID && $setPrevContribution) {
175 $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
176 }
177
178 if ($contributionID) {
179 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
180 }
181 else {
182 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
183 }
184 $contribution = new CRM_Contribute_BAO_Contribution();
185 $contribution->copyValues($params);
186
187 $contribution->id = $contributionID;
188
189 if (empty($contribution->id)) {
190 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
191 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
192 $config = CRM_Core_Config::singleton();
193 $contribution->currency = $config->defaultCurrency;
194 }
195 }
196
197 $result = $contribution->save();
198
199 // Add financial_trxn details as part of fix for CRM-4724
200 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
201 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
202
203 //add Account details
204 $params['contribution'] = $contribution;
205 self::recordFinancialAccounts($params);
206
207 // reset the group contact cache for this group
208 CRM_Contact_BAO_GroupContactCache::remove();
209
210 if ($contributionID) {
211 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
212 }
213 else {
214 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
215 }
216
217 return $result;
218 }
219
220 /**
221 * Get defaults for new entity.
222 * @return array
223 */
224 public static function getDefaults() {
225 return array(
226 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
227 FALSE, FALSE, FALSE, 'AND is_default = 1')
228 ),
229 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
230 );
231 }
232
233 /**
234 * Given the list of params in the params array, fetch the object
235 * and store the values in the values array
236 *
237 * @param array $params
238 * Input parameters to find object.
239 * @param array $values
240 * Output values of the object.
241 * @param array $ids
242 * The array that holds all the db ids.
243 *
244 * @return CRM_Contribute_BAO_Contribution|null
245 * The found object or null
246 */
247 public static function getValues($params, &$values, &$ids) {
248 if (empty($params)) {
249 return NULL;
250 }
251 $contribution = new CRM_Contribute_BAO_Contribution();
252
253 $contribution->copyValues($params);
254
255 if ($contribution->find(TRUE)) {
256 $ids['contribution'] = $contribution->id;
257
258 CRM_Core_DAO::storeValues($contribution, $values);
259
260 return $contribution;
261 }
262 $null = NULL; // return by reference
263 return $null;
264 }
265
266 /**
267 * Calculate net_amount & fee_amount if they are not set.
268 *
269 * Net amount should be total - fee.
270 * This should only be called for new contributions.
271 *
272 * @param array $params
273 * Params for a new contribution before they are saved.
274 * @param int|null $contributionID
275 * Contribution ID if we are dealing with an update.
276 *
277 * @throws \CiviCRM_API3_Exception
278 */
279 public static function calculateMissingAmountParams(&$params, $contributionID) {
280 if (!$contributionID && !isset($params['fee_amount'])) {
281 if (isset($params['total_amount']) && isset($params['net_amount'])) {
282 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
283 }
284 else {
285 $params['fee_amount'] = 0;
286 }
287 }
288 if (!isset($params['net_amount'])) {
289 if (!$contributionID) {
290 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
291 }
292 else {
293 if (isset($params['fee_amount']) || isset($params['total_amount'])) {
294 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
295 // net_amount may need adjusting.
296 $contribution = civicrm_api3('Contribution', 'getsingle', array(
297 'id' => $contributionID,
298 'return' => array('total_amount', 'net_amount'),
299 ));
300 $totalAmount = isset($params['total_amount']) ? $params['total_amount'] : CRM_Utils_Array::value('total_amount', $contribution);
301 $feeAmount = isset($params['fee_amount']) ? $params['fee_amount'] : CRM_Utils_Array::value('fee_amount', $contribution);
302 $params['net_amount'] = $totalAmount - $feeAmount;
303 }
304 }
305 }
306 }
307
308 /**
309 * @param $params
310 * @param $billingLocationTypeID
311 *
312 * @return array
313 */
314 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
315 $hasBillingField = FALSE;
316 $billingFields = array(
317 'street_address',
318 'city',
319 'state_province_id',
320 'postal_code',
321 'country_id',
322 );
323
324 //build address array
325 $addressParams = array();
326 $addressParams['location_type_id'] = $billingLocationTypeID;
327 $addressParams['is_billing'] = 1;
328
329 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
330 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
331 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
332 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
333
334 foreach ($billingFields as $value) {
335 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
336 if (!empty($addressParams[$value])) {
337 $hasBillingField = TRUE;
338 }
339 }
340 return array($hasBillingField, $addressParams);
341 }
342
343 /**
344 * Get address params ready to be passed to the payment processor.
345 *
346 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
347 * To create an address we need state_province_id.
348 *
349 * @param array $params
350 * @param int $billingLocationTypeID
351 *
352 * @return array
353 */
354 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
355 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
356 foreach ($addressParams as $name => $field) {
357 if (substr($name, 0, 8) == 'billing_') {
358 $addressParams[substr($name, 9)] = $addressParams[$field];
359 }
360 }
361 return array($hasBillingField, $addressParams);
362 }
363
364 /**
365 * Get the number of terms for this contribution for a given membership type
366 * based on querying the line item table and relevant price field values
367 * Note that any one contribution should only be able to have one line item relating to a particular membership
368 * type
369 *
370 * @param int $membershipTypeID
371 *
372 * @param int $contributionID
373 *
374 * @return int
375 */
376 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
377 $numTerms = CRM_Core_DAO::singleValueQuery("
378 SELECT membership_num_terms FROM civicrm_line_item li
379 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
380 WHERE contribution_id = %1 AND membership_type_id = %2",
381 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
382 );
383 // default of 1 is precautionary
384 return empty($numTerms) ? 1 : $numTerms;
385 }
386
387 /**
388 * Takes an associative array and creates a contribution object.
389 *
390 * @param array $params
391 * (reference ) an assoc array of name/value pairs.
392 * @param array $ids
393 * The array that holds all the db ids.
394 *
395 * @return CRM_Contribute_BAO_Contribution
396 */
397 public static function create(&$params, $ids = array()) {
398 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
399 foreach ($dateFields as $df) {
400 if (isset($params[$df])) {
401 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
402 }
403 }
404
405 //if contribution is created with cancelled or refunded status, add credit note id
406 if (!empty($params['contribution_status_id'])) {
407 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
408
409 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
410 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
411 ) {
412 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
413 $params['creditnote_id'] = self::createCreditNoteId();
414 }
415 }
416 }
417
418 $transaction = new CRM_Core_Transaction();
419
420 $contribution = self::add($params, $ids);
421
422 if (is_a($contribution, 'CRM_Core_Error')) {
423 $transaction->rollback();
424 return $contribution;
425 }
426
427 $params['contribution_id'] = $contribution->id;
428
429 if (!empty($params['custom']) &&
430 is_array($params['custom'])
431 ) {
432 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
433 }
434
435 $session = CRM_Core_Session::singleton();
436
437 if (!empty($params['note'])) {
438 $noteParams = array(
439 'entity_table' => 'civicrm_contribution',
440 'note' => $params['note'],
441 'entity_id' => $contribution->id,
442 'contact_id' => $session->get('userID'),
443 'modified_date' => date('Ymd'),
444 );
445 if (!$noteParams['contact_id']) {
446 $noteParams['contact_id'] = $params['contact_id'];
447 }
448 CRM_Core_BAO_Note::add($noteParams);
449 }
450
451 // make entry in batch entity batch table
452 if (!empty($params['batch_id'])) {
453 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
454 $titleFields = array(
455 'contact_id',
456 'total_amount',
457 'currency',
458 'financial_type_id',
459 );
460 $retrieveRequired = 0;
461 foreach ($titleFields as $titleField) {
462 if (!isset($contribution->$titleField)) {
463 $retrieveRequired = 1;
464 break;
465 }
466 }
467 if ($retrieveRequired == 1) {
468 $contribution->find(TRUE);
469 }
470 }
471
472 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
473
474 $transaction->commit();
475
476 // check if activity record exist for this contribution, if
477 // not add activity
478 $activity = new CRM_Activity_DAO_Activity();
479 $activity->source_record_id = $contribution->id;
480 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
481 'Contribution',
482 'name'
483 );
484 if (!$activity->find(TRUE)) {
485 if (empty($contribution->contact_id)) {
486 $contribution->find(TRUE);
487 }
488 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
489 }
490 else {
491 // CRM-13237 : if activity record found, update it with campaign id of contribution
492 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
493 }
494
495 // do not add to recent items for import, CRM-4399
496 if (empty($params['skipRecentView'])) {
497 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
498 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
499 );
500 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
501 $titleFields = array(
502 'contact_id',
503 'total_amount',
504 'currency',
505 'financial_type_id',
506 );
507 $retrieveRequired = 0;
508 foreach ($titleFields as $titleField) {
509 if (!isset($contribution->$titleField)) {
510 $retrieveRequired = 1;
511 break;
512 }
513 }
514 if ($retrieveRequired == 1) {
515 $contribution->find(TRUE);
516 }
517 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
518 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
519
520 $recentOther = array();
521 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
522 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
523 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
524 );
525 }
526
527 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
528 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
529 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
530 );
531 }
532
533 // add the recently created Contribution
534 CRM_Utils_Recent::add($title,
535 $url,
536 $contribution->id,
537 'Contribution',
538 $contribution->contact_id,
539 NULL,
540 $recentOther
541 );
542 }
543
544 return $contribution;
545 }
546
547 /**
548 * Get the values for pseudoconstants for name->value and reverse.
549 *
550 * @param array $defaults
551 * (reference) the default values, some of which need to be resolved.
552 * @param bool $reverse
553 * True if we want to resolve the values in the reverse direction (value -> name).
554 */
555 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
556 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
557 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
558 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
559 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
560 }
561
562 /**
563 * Convert associative array names to values and vice-versa.
564 *
565 * This function is used by both the web form layer and the api. Note that
566 * the api needs the name => value conversion, also the view layer typically
567 * requires value => name conversion
568 *
569 * @param array $defaults
570 * @param string $property
571 * @param array $lookup
572 * @param bool $reverse
573 *
574 * @return bool
575 */
576 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
577 $id = $property . '_id';
578
579 $src = $reverse ? $property : $id;
580 $dst = $reverse ? $id : $property;
581
582 if (!array_key_exists($src, $defaults)) {
583 return FALSE;
584 }
585
586 $look = $reverse ? array_flip($lookup) : $lookup;
587
588 if (is_array($look)) {
589 if (!array_key_exists($defaults[$src], $look)) {
590 return FALSE;
591 }
592 }
593 $defaults[$dst] = $look[$defaults[$src]];
594 return TRUE;
595 }
596
597 /**
598 * Retrieve DB object based on input parameters.
599 *
600 * It also stores all the retrieved values in the default array.
601 *
602 * @param array $params
603 * (reference ) an assoc array of name/value pairs.
604 * @param array $defaults
605 * (reference ) an assoc array to hold the name / value pairs.
606 * in a hierarchical manner
607 * @param array $ids
608 * (reference) the array that holds all the db ids.
609 *
610 * @return CRM_Contribute_BAO_Contribution
611 */
612 public static function retrieve(&$params, &$defaults, &$ids) {
613 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
614 return $contribution;
615 }
616
617 /**
618 * Combine all the importable fields from the lower levels object.
619 *
620 * The ordering is important, since currently we do not have a weight
621 * scheme. Adding weight is super important and should be done in the
622 * next week or so, before this can be called complete.
623 *
624 * @param string $contactType
625 * @param bool $status
626 *
627 * @return array
628 * array of importable Fields
629 */
630 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
631 if (!self::$_importableFields) {
632 if (!self::$_importableFields) {
633 self::$_importableFields = array();
634 }
635
636 if (!$status) {
637 $fields = array('' => array('title' => ts('- do not import -')));
638 }
639 else {
640 $fields = array('' => array('title' => ts('- Contribution Fields -')));
641 }
642
643 $note = CRM_Core_DAO_Note::import();
644 $tmpFields = CRM_Contribute_DAO_Contribution::import();
645 unset($tmpFields['option_value']);
646 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
647 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
648
649 // Using new Dedupe rule.
650 $ruleParams = array(
651 'contact_type' => $contactType,
652 'used' => 'Unsupervised',
653 );
654 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
655 $tmpContactField = array();
656 if (is_array($fieldsArray)) {
657 foreach ($fieldsArray as $value) {
658 //skip if there is no dupe rule
659 if ($value == 'none') {
660 continue;
661 }
662 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
663 $value,
664 'id',
665 'column_name'
666 );
667 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
668 $tmpContactField[trim($value)] = $contactFields[trim($value)];
669 if (!$status) {
670 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
671 }
672 else {
673 $title = $tmpContactField[trim($value)]['title'];
674 }
675 $tmpContactField[trim($value)]['title'] = $title;
676 }
677 }
678
679 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
680 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
681 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
682 $fields = array_merge($fields, $tmpContactField);
683 $fields = array_merge($fields, $tmpFields);
684 $fields = array_merge($fields, $note);
685 $fields = array_merge($fields, $optionFields);
686 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
687 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
688 self::$_importableFields = $fields;
689 }
690 return self::$_importableFields;
691 }
692
693 /**
694 * @return array
695 */
696 public static function &exportableFields() {
697 if (!self::$_exportableFields) {
698 if (!self::$_exportableFields) {
699 self::$_exportableFields = array();
700 }
701
702 $impFields = CRM_Contribute_DAO_Contribution::export();
703 $expFieldProduct = CRM_Contribute_DAO_Product::export();
704 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
705 $typeField = CRM_Financial_DAO_FinancialType::export();
706 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
707 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
708 $contributionStatus = array(
709 'contribution_status' => array(
710 'title' => ts('Contribution Status'),
711 'name' => 'contribution_status',
712 'data_type' => CRM_Utils_Type::T_STRING,
713 ),
714 );
715
716 $contributionPage = array(
717 'contribution_page' => array(
718 'title' => ts('Contribution Page'),
719 'name' => 'contribution_page',
720 'where' => 'civicrm_contribution_page.title',
721 'data_type' => CRM_Utils_Type::T_STRING,
722 ),
723 );
724
725 $contributionNote = array(
726 'contribution_note' => array(
727 'title' => ts('Contribution Note'),
728 'name' => 'contribution_note',
729 'data_type' => CRM_Utils_Type::T_TEXT,
730 ),
731 );
732
733 $contributionRecurId = array(
734 'contribution_recur_id' => array(
735 'title' => ts('Recurring Contributions ID'),
736 'name' => 'contribution_recur_id',
737 'where' => 'civicrm_contribution.contribution_recur_id',
738 'data_type' => CRM_Utils_Type::T_INT,
739 ),
740 );
741
742 $extraFields = array(
743 'contribution_batch' => array(
744 'title' => ts('Batch Name'),
745 ),
746 );
747
748 $softCreditFields = array(
749 'contribution_soft_credit_name' => array(
750 'name' => 'contribution_soft_credit_name',
751 'title' => 'Soft Credit For',
752 'where' => 'civicrm_contact_d.display_name',
753 'data_type' => CRM_Utils_Type::T_STRING,
754 ),
755 'contribution_soft_credit_amount' => array(
756 'name' => 'contribution_soft_credit_amount',
757 'title' => 'Soft Credit Amount',
758 'where' => 'civicrm_contribution_soft.amount',
759 'data_type' => CRM_Utils_Type::T_MONEY,
760 ),
761 'contribution_soft_credit_type' => array(
762 'name' => 'contribution_soft_credit_type',
763 'title' => 'Soft Credit Type',
764 'where' => 'contribution_softcredit_type.label',
765 'data_type' => CRM_Utils_Type::T_STRING,
766 ),
767 'contribution_soft_credit_contribution_id' => array(
768 'name' => 'contribution_soft_credit_contribution_id',
769 'title' => 'Soft Credit For Contribution ID',
770 'where' => 'civicrm_contribution_soft.contribution_id',
771 'data_type' => CRM_Utils_Type::T_INT,
772 ),
773 'contribution_soft_credit_contact_id' => array(
774 'name' => 'contribution_soft_credit_contact_id',
775 'title' => 'Soft Credit For Contact ID',
776 'where' => 'civicrm_contact_d.id',
777 'data_type' => CRM_Utils_Type::T_INT,
778 ),
779 );
780
781 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
782 $premiums = array(
783 'contribution_product_id' => array(
784 'title' => ts('Premium'),
785 'name' => 'contribution_product_id',
786 'where' => 'civicrm_product.id',
787 'data_type' => CRM_Utils_Type::T_INT,
788 ),
789 );
790
791 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
792 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
793 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
794 );
795
796 self::$_exportableFields = $fields;
797 }
798
799 return self::$_exportableFields;
800 }
801
802 /**
803 * @param null $status
804 * @param null $startDate
805 * @param null $endDate
806 *
807 * @return array|null
808 */
809 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
810 $where = array();
811 switch ($status) {
812 case 'Valid':
813 $where[] = 'contribution_status_id = 1';
814 break;
815
816 case 'Cancelled':
817 $where[] = 'contribution_status_id = 3';
818 break;
819 }
820
821 if ($startDate) {
822 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
823 }
824 if ($endDate) {
825 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
826 }
827 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
828 if ($financialTypes) {
829 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
830 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
831 }
832 else {
833 $where[] = "c.financial_type_id IN (0)";
834 }
835
836 $whereCond = implode(' AND ', $where);
837
838 $query = "
839 SELECT sum( total_amount ) as total_amount,
840 count( c.id ) as total_count,
841 currency
842 FROM civicrm_contribution c
843 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
844 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
845 WHERE $whereCond
846 AND ( is_test = 0 OR is_test IS NULL )
847 AND contact.is_deleted = 0
848 GROUP BY currency
849 ";
850
851 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
852 $amount = array();
853 $count = 0;
854 while ($dao->fetch()) {
855 $count += $dao->total_count;
856 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
857 }
858 if ($count) {
859 return array(
860 'amount' => implode(', ', $amount),
861 'count' => $count,
862 );
863 }
864 return NULL;
865 }
866
867 /**
868 * Delete the indirect records associated with this contribution first.
869 *
870 * @param int $id
871 *
872 * @return mixed|null
873 * $results no of deleted Contribution on success, false otherwise
874 */
875 public static function deleteContribution($id) {
876 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
877
878 $transaction = new CRM_Core_Transaction();
879
880 $results = NULL;
881 //delete activity record
882 $params = array(
883 'source_record_id' => $id,
884 // activity type id for contribution
885 'activity_type_id' => 6,
886 );
887
888 CRM_Activity_BAO_Activity::deleteActivity($params);
889
890 //delete billing address if exists for this contribution.
891 self::deleteAddress($id);
892
893 //update pledge and pledge payment, CRM-3961
894 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
895
896 // remove entry from civicrm_price_set_entity, CRM-5095
897 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
898 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
899 }
900 // cleanup line items.
901 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
902
903 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
904 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
905
906 if ($participantId) {
907 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
908 }
909 else {
910 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
911 }
912
913 //delete note.
914 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
915 $noteId = key($note);
916 if ($noteId) {
917 CRM_Core_BAO_Note::del($noteId, FALSE);
918 }
919
920 $dao = new CRM_Contribute_DAO_Contribution();
921 $dao->id = $id;
922
923 $results = $dao->delete();
924
925 $transaction->commit();
926
927 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
928
929 // delete the recently created Contribution
930 $contributionRecent = array(
931 'id' => $id,
932 'type' => 'Contribution',
933 );
934 CRM_Utils_Recent::del($contributionRecent);
935
936 return $results;
937 }
938
939 /**
940 * React to a financial transaction (payment) failure.
941 *
942 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
943 * payments is important for forensic and outreach reasons.
944 *
945 * @param int $contributionID
946 * @param int $contactID
947 * @param string $message
948 *
949 * @throws \CiviCRM_API3_Exception
950 */
951 public static function failPayment($contributionID, $contactID, $message) {
952 civicrm_api3('activity', 'create', array(
953 'activity_type_id' => 'Failed Payment',
954 'details' => $message,
955 'subject' => ts('Payment failed at payment processor'),
956 'source_record_id' => $contributionID,
957 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
958 $contactID,
959 ));
960 }
961
962 /**
963 * Check if there is a contribution with the same trxn_id or invoice_id.
964 *
965 * @param array $input
966 * An assoc array of name/value pairs.
967 * @param array $duplicates
968 * (reference) store ids of duplicate contribs.
969 * @param int $id
970 *
971 * @return bool
972 * true if duplicate, false otherwise
973 */
974 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
975 if (!$id) {
976 $id = CRM_Utils_Array::value('id', $input);
977 }
978 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
979 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
980
981 $clause = array();
982 $input = array();
983
984 if ($trxn_id) {
985 $clause[] = "trxn_id = %1";
986 $input[1] = array($trxn_id, 'String');
987 }
988
989 if ($invoice_id) {
990 $clause[] = "invoice_id = %2";
991 $input[2] = array($invoice_id, 'String');
992 }
993
994 if (empty($clause)) {
995 return FALSE;
996 }
997
998 $clause = implode(' OR ', $clause);
999 if ($id) {
1000 $clause = "( $clause ) AND id != %3";
1001 $input[3] = array($id, 'Integer');
1002 }
1003
1004 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1005 $dao = CRM_Core_DAO::executeQuery($query, $input);
1006 $result = FALSE;
1007 while ($dao->fetch()) {
1008 $duplicates[] = $dao->id;
1009 $result = TRUE;
1010 }
1011 return $result;
1012 }
1013
1014 /**
1015 * Takes an associative array and creates a contribution_product object.
1016 *
1017 * the function extract all the params it needs to initialize the create a
1018 * contribution_product object. the params array could contain additional unused name/value
1019 * pairs
1020 *
1021 * @param array $params
1022 * (reference) an assoc array of name/value pairs.
1023 *
1024 * @return CRM_Contribute_DAO_ContributionProduct
1025 */
1026 public static function addPremium(&$params) {
1027 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1028 $contributionProduct->copyValues($params);
1029 return $contributionProduct->save();
1030 }
1031
1032 /**
1033 * Get list of contribution fields for profile.
1034 * For now we only allow custom contribution fields to be in
1035 * profile
1036 *
1037 * @param bool $addExtraFields
1038 * True if special fields needs to be added.
1039 *
1040 * @return array
1041 * the list of contribution fields
1042 */
1043 public static function getContributionFields($addExtraFields = TRUE) {
1044 $contributionFields = CRM_Contribute_DAO_Contribution::export();
1045 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
1046
1047 if ($addExtraFields) {
1048 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
1049 }
1050
1051 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
1052
1053 foreach ($contributionFields as $key => $var) {
1054 if ($key == 'contribution_contact_id') {
1055 continue;
1056 }
1057 elseif ($key == 'contribution_campaign_id') {
1058 $var['title'] = ts('Campaign');
1059 }
1060 $fields[$key] = $var;
1061 }
1062
1063 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
1064 return $fields;
1065 }
1066
1067 /**
1068 * Add extra fields specific to contribution.
1069 */
1070 public static function getSpecialContributionFields() {
1071 $extraFields = array(
1072 'contribution_soft_credit_name' => array(
1073 'name' => 'contribution_soft_credit_name',
1074 'title' => 'Soft Credit Name',
1075 'headerPattern' => '/^soft_credit_name$/i',
1076 'where' => 'civicrm_contact_d.display_name',
1077 ),
1078 'contribution_soft_credit_email' => array(
1079 'name' => 'contribution_soft_credit_email',
1080 'title' => 'Soft Credit Email',
1081 'headerPattern' => '/^soft_credit_email$/i',
1082 'where' => 'soft_email.email',
1083 ),
1084 'contribution_soft_credit_phone' => array(
1085 'name' => 'contribution_soft_credit_phone',
1086 'title' => 'Soft Credit Phone',
1087 'headerPattern' => '/^soft_credit_phone$/i',
1088 'where' => 'soft_phone.phone',
1089 ),
1090 'contribution_soft_credit_contact_id' => array(
1091 'name' => 'contribution_soft_credit_contact_id',
1092 'title' => 'Soft Credit Contact ID',
1093 'headerPattern' => '/^soft_credit_contact_id$/i',
1094 'where' => 'civicrm_contribution_soft.contact_id',
1095 ),
1096 );
1097
1098 return $extraFields;
1099 }
1100
1101 /**
1102 * @param int $pageID
1103 *
1104 * @return array
1105 */
1106 public static function getCurrentandGoalAmount($pageID) {
1107 $query = "
1108 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1109 FROM civicrm_contribution_page p,
1110 civicrm_contribution c
1111 WHERE p.id = c.contribution_page_id
1112 AND p.id = %1
1113 AND c.cancel_date is null
1114 GROUP BY p.id
1115 ";
1116
1117 $config = CRM_Core_Config::singleton();
1118 $params = array(1 => array($pageID, 'Integer'));
1119 $dao = CRM_Core_DAO::executeQuery($query, $params);
1120
1121 if ($dao->fetch()) {
1122 return array($dao->goal, $dao->total);
1123 }
1124 else {
1125 return array(NULL, NULL);
1126 }
1127 }
1128
1129 /**
1130 * Get list of contribution In Honor of contact Ids.
1131 *
1132 * @param int $honorId
1133 * In Honor of Contact ID.
1134 *
1135 * @return array
1136 * list of contribution fields
1137 */
1138 public static function getHonorContacts($honorId) {
1139 $params = array();
1140 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1141 $honorDAO->contact_id = $honorId;
1142 $honorDAO->find();
1143
1144 $type = CRM_Contribute_PseudoConstant::financialType();
1145
1146 while ($honorDAO->fetch()) {
1147 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1148 $contributionDAO->id = $honorDAO->contribution_id;
1149
1150 if ($contributionDAO->find(TRUE)) {
1151 $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id);
1152 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1153 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1154 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1155 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1156 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1157 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1158 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1159 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1160 }
1161 }
1162
1163 return $params;
1164 }
1165
1166 /**
1167 * Get the sort name of a contact for a particular contribution.
1168 *
1169 * @param int $id
1170 * Id of the contribution.
1171 *
1172 * @return null|string
1173 * sort name of the contact if found
1174 */
1175 public static function sortName($id) {
1176 $id = CRM_Utils_Type::escape($id, 'Integer');
1177
1178 $query = "
1179 SELECT civicrm_contact.sort_name
1180 FROM civicrm_contribution, civicrm_contact
1181 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1182 AND civicrm_contribution.id = {$id}
1183 ";
1184 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1185 }
1186
1187 /**
1188 * @param int $contactID
1189 *
1190 * @return array
1191 */
1192 public static function annual($contactID) {
1193 if (is_array($contactID)) {
1194 $contactIDs = implode(',', $contactID);
1195 }
1196 else {
1197 $contactIDs = $contactID;
1198 }
1199
1200 $config = CRM_Core_Config::singleton();
1201 $startDate = $endDate = NULL;
1202
1203 $currentMonth = date('m');
1204 $currentDay = date('d');
1205 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1206 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1207 (int ) $config->fiscalYearStart['d'] > $currentDay
1208 )
1209 ) {
1210 $year = date('Y') - 1;
1211 }
1212 else {
1213 $year = date('Y');
1214 }
1215 $nextYear = $year + 1;
1216
1217 if ($config->fiscalYearStart) {
1218 $newFiscalYearStart = $config->fiscalYearStart;
1219 if ($newFiscalYearStart['M'] < 10) {
1220 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1221 }
1222 if ($newFiscalYearStart['d'] < 10) {
1223 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1224 }
1225 $config->fiscalYearStart = $newFiscalYearStart;
1226 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1227 }
1228 else {
1229 $monthDay = '0101';
1230 }
1231 $startDate = "$year$monthDay";
1232 $endDate = "$nextYear$monthDay";
1233 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
1234 $additionalWhere = " AND b.financial_type_id IN (0)";
1235 $liWhere = " AND i.financial_type_id IN (0)";
1236 if (!empty($financialTypes)) {
1237 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1238 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1239 }
1240 $query = "
1241 SELECT count(*) as count,
1242 sum(total_amount) as amount,
1243 avg(total_amount) as average,
1244 currency
1245 FROM civicrm_contribution b
1246 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1247 WHERE b.contact_id IN ( $contactIDs )
1248 AND b.contribution_status_id = 1
1249 AND b.is_test = 0
1250 AND b.receive_date >= $startDate
1251 AND b.receive_date < $endDate
1252 $additionalWhere
1253 GROUP BY currency
1254 ";
1255 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1256 $count = 0;
1257 $amount = $average = array();
1258 while ($dao->fetch()) {
1259 if ($dao->count > 0 && $dao->amount > 0) {
1260 $count += $dao->count;
1261 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1262 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1263 }
1264 }
1265 if ($count > 0) {
1266 return array(
1267 $count,
1268 implode(',&nbsp;', $amount),
1269 implode(',&nbsp;', $average),
1270 );
1271 }
1272 return array(0, 0, 0);
1273 }
1274
1275 /**
1276 * Check if there is a contribution with the params passed in.
1277 *
1278 * Used for trxn_id,invoice_id and contribution_id
1279 *
1280 * @param array $params
1281 * An assoc array of name/value pairs.
1282 *
1283 * @return array
1284 * contribution id if success else NULL
1285 */
1286 public static function checkDuplicateIds($params) {
1287 $dao = new CRM_Contribute_DAO_Contribution();
1288
1289 $clause = array();
1290 $input = array();
1291 foreach ($params as $k => $v) {
1292 if ($v) {
1293 $clause[] = "$k = '$v'";
1294 }
1295 }
1296 $clause = implode(' AND ', $clause);
1297 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1298 $dao = CRM_Core_DAO::executeQuery($query, $input);
1299
1300 while ($dao->fetch()) {
1301 $result = $dao->id;
1302 return $result;
1303 }
1304 return NULL;
1305 }
1306
1307 /**
1308 * Get the contribution details for component export.
1309 *
1310 * @param int $exportMode
1311 * Export mode.
1312 * @param string $componentIds
1313 * Component ids.
1314 *
1315 * @return array
1316 * associated array
1317 */
1318 public static function getContributionDetails($exportMode, $componentIds) {
1319 $paymentDetails = array();
1320 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1321
1322 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1323 $componentSelect = " civicrm_participant_payment.participant_id id";
1324 $additionalClause = "
1325 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1326 AND civicrm_participant_payment.participant_id {$componentClause} )
1327 ";
1328 }
1329 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1330 $componentSelect = " civicrm_membership_payment.membership_id id";
1331 $additionalClause = "
1332 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1333 AND civicrm_membership_payment.membership_id {$componentClause} )
1334 ";
1335 }
1336 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1337 $componentSelect = " civicrm_pledge_payment.id id";
1338 $additionalClause = "
1339 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1340 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1341 ";
1342 }
1343
1344 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1345 trxn_id, {$componentSelect}
1346 FROM civicrm_contribution
1347 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1348 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1349 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1350 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1351 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1352 AND option_group_contribution_status.id = contribution_status.option_group_id )
1353 {$additionalClause}
1354 ";
1355
1356 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1357
1358 while ($dao->fetch()) {
1359 $paymentDetails[$dao->id] = array(
1360 'total_amount' => $dao->total_amount,
1361 'contribution_status' => $dao->status,
1362 'receive_date' => $dao->receive_date,
1363 'pay_instru' => $dao->payment_instrument,
1364 'trxn_id' => $dao->trxn_id,
1365 );
1366 }
1367
1368 return $paymentDetails;
1369 }
1370
1371 /**
1372 * Create address associated with contribution record.
1373 *
1374 * As long as there is one or more billing field in the parameters we will create the address.
1375 *
1376 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1377 * thought).
1378 *
1379 * @param array $params
1380 * @param int $billingLocationTypeID
1381 *
1382 * @return int
1383 * address id
1384 */
1385 public static function createAddress($params, $billingLocationTypeID) {
1386 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
1387 if ($hasBillingField) {
1388 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1389 return $address->id;
1390 }
1391 return NULL;
1392
1393 }
1394
1395 /**
1396 * Delete billing address record related contribution.
1397 *
1398 * @param int $contributionId
1399 * @param int $contactId
1400 */
1401 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1402 $clauses = array();
1403 $contactJoin = NULL;
1404
1405 if ($contributionId) {
1406 $clauses[] = "cc.id = {$contributionId}";
1407 }
1408
1409 if ($contactId) {
1410 $clauses[] = "cco.id = {$contactId}";
1411 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1412 }
1413
1414 if (empty($clauses)) {
1415 CRM_Core_Error::fatal();
1416 }
1417
1418 $condition = implode(' OR ', $clauses);
1419
1420 $query = "
1421 SELECT ca.id
1422 FROM civicrm_address ca
1423 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1424 $contactJoin
1425 WHERE $condition
1426 ";
1427 $dao = CRM_Core_DAO::executeQuery($query);
1428
1429 while ($dao->fetch()) {
1430 $params = array('id' => $dao->id);
1431 CRM_Core_BAO_Block::blockDelete('Address', $params);
1432 }
1433 }
1434
1435 /**
1436 * This function check online pending contribution associated w/
1437 * Online Event Registration or Online Membership signup.
1438 *
1439 * @param int $componentId
1440 * Participant/membership id.
1441 * @param string $componentName
1442 * Event/Membership.
1443 *
1444 * @return int
1445 * pending contribution id.
1446 */
1447 public static function checkOnlinePendingContribution($componentId, $componentName) {
1448 $contributionId = NULL;
1449 if (!$componentId ||
1450 !in_array($componentName, array('Event', 'Membership'))
1451 ) {
1452 return $contributionId;
1453 }
1454
1455 if ($componentName == 'Event') {
1456 $idName = 'participant_id';
1457 $componentTable = 'civicrm_participant';
1458 $paymentTable = 'civicrm_participant_payment';
1459 $source = ts('Online Event Registration');
1460 }
1461
1462 if ($componentName == 'Membership') {
1463 $idName = 'membership_id';
1464 $componentTable = 'civicrm_membership';
1465 $paymentTable = 'civicrm_membership_payment';
1466 $source = ts('Online Contribution');
1467 }
1468
1469 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1470
1471 $query = "
1472 SELECT component.id as {$idName},
1473 componentPayment.contribution_id as contribution_id,
1474 contribution.source source,
1475 contribution.contribution_status_id as contribution_status_id,
1476 contribution.is_pay_later as is_pay_later
1477 FROM $componentTable component
1478 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1479 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1480 WHERE component.id = {$componentId}";
1481
1482 $dao = CRM_Core_DAO::executeQuery($query);
1483
1484 while ($dao->fetch()) {
1485 if ($dao->contribution_id &&
1486 $dao->is_pay_later &&
1487 $dao->contribution_status_id == $pendingStatusId &&
1488 strpos($dao->source, $source) !== FALSE
1489 ) {
1490 $contributionId = $dao->contribution_id;
1491 $dao->free();
1492 }
1493 }
1494
1495 return $contributionId;
1496 }
1497
1498 /**
1499 * Update contribution as well as related objects.
1500 *
1501 * This function by-passes hooks - to address this - don't use this function.
1502 *
1503 * @deprecated
1504 *
1505 * Use api contribute.completetransaction
1506 * For failures use failPayment (preferably exposing by api in the process).
1507 *
1508 * @param array $params
1509 * @param bool $processContributionObject
1510 *
1511 * @return array
1512 * @throws \Exception
1513 */
1514 public static function transitionComponents($params, $processContributionObject = FALSE) {
1515 // get minimum required values.
1516 $contactId = CRM_Utils_Array::value('contact_id', $params);
1517 $componentId = CRM_Utils_Array::value('component_id', $params);
1518 $componentName = CRM_Utils_Array::value('componentName', $params);
1519 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1520 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1521
1522 // if we already processed contribution object pass previous status id.
1523 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1524
1525 $updateResult = array();
1526
1527 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1528
1529 // we process only ( Completed, Cancelled, or Failed ) contributions.
1530 if (!$contributionId ||
1531 !in_array($contributionStatusId, array(
1532 array_search('Completed', $contributionStatuses),
1533 array_search('Cancelled', $contributionStatuses),
1534 array_search('Failed', $contributionStatuses),
1535 ))
1536 ) {
1537 return $updateResult;
1538 }
1539
1540 if (!$componentName || !$componentId) {
1541 // get the related component details.
1542 $componentDetails = self::getComponentDetails($contributionId);
1543 }
1544 else {
1545 $componentDetails['contact_id'] = $contactId;
1546 $componentDetails['component'] = $componentName;
1547
1548 if ($componentName == 'event') {
1549 $componentDetails['participant'] = $componentId;
1550 }
1551 else {
1552 $componentDetails['membership'] = $componentId;
1553 }
1554 }
1555
1556 if (!empty($componentDetails['contact_id'])) {
1557 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1558 $contributionId,
1559 'contact_id'
1560 );
1561 }
1562
1563 // do check for required ids.
1564 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1565 return $updateResult;
1566 }
1567
1568 //now we are ready w/ required ids, start processing.
1569
1570 $baseIPN = new CRM_Core_Payment_BaseIPN();
1571
1572 $input = $ids = $objects = array();
1573
1574 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1575 $ids['contribution'] = $contributionId;
1576 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1577 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1578 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1579 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1580 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1581 $ids['contributionRecur'] = NULL;
1582 $ids['contributionPage'] = NULL;
1583
1584 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1585 CRM_Core_Error::fatal();
1586 }
1587
1588 $memberships = &$objects['membership'];
1589 $participant = &$objects['participant'];
1590 $pledgePayment = &$objects['pledge_payment'];
1591 $contribution = &$objects['contribution'];
1592
1593 if ($pledgePayment) {
1594 $pledgePaymentIDs = array();
1595 foreach ($pledgePayment as $key => $object) {
1596 $pledgePaymentIDs[] = $object->id;
1597 }
1598 $pledgeID = $pledgePayment[0]->pledge_id;
1599 }
1600
1601 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1602
1603 if ($participant) {
1604 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1605 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1606 $participant->id,
1607 'status_id'
1608 );
1609 }
1610 // we might want to process contribution object.
1611 $processContribution = FALSE;
1612 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1613 if (is_array($memberships)) {
1614 foreach ($memberships as $membership) {
1615 if ($membership) {
1616 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1617 $membership->save();
1618
1619 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1620 if ($processContributionObject) {
1621 $processContribution = TRUE;
1622 }
1623 }
1624 }
1625 }
1626
1627 if ($participant) {
1628 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1629 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1630
1631 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1632 if ($processContributionObject) {
1633 $processContribution = TRUE;
1634 }
1635 }
1636
1637 if ($pledgePayment) {
1638 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1639
1640 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1641 if ($processContributionObject) {
1642 $processContribution = TRUE;
1643 }
1644 }
1645 }
1646 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1647 if (is_array($memberships)) {
1648 foreach ($memberships as $membership) {
1649 if ($membership) {
1650 $membership->status_id = array_search('Expired', $membershipStatuses);
1651 $membership->save();
1652
1653 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1654 if ($processContributionObject) {
1655 $processContribution = TRUE;
1656 }
1657 }
1658 }
1659 }
1660 if ($participant) {
1661 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1662 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1663
1664 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1665 if ($processContributionObject) {
1666 $processContribution = TRUE;
1667 }
1668 }
1669
1670 if ($pledgePayment) {
1671 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1672
1673 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1674 if ($processContributionObject) {
1675 $processContribution = TRUE;
1676 }
1677 }
1678 }
1679 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1680
1681 // only pending contribution related object processed.
1682 if ($previousContriStatusId &&
1683 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1684 ) {
1685 // this is case when we already processed contribution object.
1686 return $updateResult;
1687 }
1688 elseif (!$previousContriStatusId &&
1689 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1690 ) {
1691 // this is case when we are going to process contribution object later.
1692 return $updateResult;
1693 }
1694
1695 if (is_array($memberships)) {
1696 foreach ($memberships as $membership) {
1697 if ($membership) {
1698 $format = '%Y%m%d';
1699
1700 //CRM-4523
1701 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1702 $membership->membership_type_id,
1703 $membership->is_test, $membership->id
1704 );
1705
1706 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1707 // this picks up membership type changes during renewals
1708 $sql = "
1709 SELECT membership_type_id
1710 FROM civicrm_membership_log
1711 WHERE membership_id=$membership->id
1712 ORDER BY id DESC
1713 LIMIT 1;";
1714 $dao = new CRM_Core_DAO();
1715 $dao->query($sql);
1716 if ($dao->fetch()) {
1717 if (!empty($dao->membership_type_id)) {
1718 $membership->membership_type_id = $dao->membership_type_id;
1719 $membership->save();
1720 }
1721 }
1722 // else fall back to using current membership type
1723 $dao->free();
1724
1725 // Figure out number of terms
1726 $numterms = 1;
1727 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1728 foreach ($lineitems as $lineitem) {
1729 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1730 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1731
1732 // in case membership_num_terms comes through as null or zero
1733 $numterms = $numterms >= 1 ? $numterms : 1;
1734 break;
1735 }
1736 }
1737
1738 // CRM-15735-to update the membership status as per the contribution receive date
1739 $joinDate = NULL;
1740 if (!empty($params['receive_date'])) {
1741 $joinDate = $params['receive_date'];
1742 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1743 $membership->end_date,
1744 $membership->join_date,
1745 $params['receive_date'],
1746 FALSE,
1747 $membership->membership_type_id,
1748 (array) $membership
1749 );
1750 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1751 $membership->save();
1752 }
1753
1754 if ($currentMembership) {
1755 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1756 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1757 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1758 }
1759 else {
1760 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
1761 }
1762
1763 //get the status for membership.
1764 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1765 $dates['end_date'],
1766 $dates['join_date'],
1767 'today',
1768 TRUE,
1769 $membership->membership_type_id,
1770 (array) $membership
1771 );
1772
1773 $formattedParams = array(
1774 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1775 array_search('Current', $membershipStatuses)
1776 ),
1777 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1778 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1779 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1780 );
1781
1782 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1783
1784 $membership->copyValues($formattedParams);
1785 $membership->save();
1786
1787 //updating the membership log
1788 $membershipLog = array();
1789 $membershipLog = $formattedParams;
1790 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1791 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1792
1793 $membershipLog['start_date'] = $logStartDate;
1794 $membershipLog['membership_id'] = $membership->id;
1795 $membershipLog['modified_id'] = $membership->contact_id;
1796 $membershipLog['modified_date'] = date('Ymd');
1797 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1798
1799 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1800
1801 //update related Memberships.
1802 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1803
1804 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1805 '%B %E%f, %Y'
1806 );
1807 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1808 if ($processContributionObject) {
1809 $processContribution = TRUE;
1810 }
1811
1812 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1813 }
1814 }
1815 }
1816
1817 if ($participant) {
1818 $updatedStatusId = array_search('Registered', $participantStatuses);
1819 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1820
1821 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1822 if ($processContributionObject) {
1823 $processContribution = TRUE;
1824 }
1825 }
1826
1827 if ($pledgePayment) {
1828 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1829
1830 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1831 if ($processContributionObject) {
1832 $processContribution = TRUE;
1833 }
1834 }
1835 }
1836
1837 // process contribution object.
1838 if ($processContribution) {
1839 $contributionParams = array();
1840 $fields = array(
1841 'contact_id',
1842 'total_amount',
1843 'receive_date',
1844 'is_test',
1845 'campaign_id',
1846 'payment_instrument_id',
1847 'trxn_id',
1848 'invoice_id',
1849 'financial_type_id',
1850 'contribution_status_id',
1851 'non_deductible_amount',
1852 'receipt_date',
1853 'check_number',
1854 );
1855 foreach ($fields as $field) {
1856 if (empty($params[$field])) {
1857 continue;
1858 }
1859 $contributionParams[$field] = $params[$field];
1860 }
1861
1862 $ids = array('contribution' => $contributionId);
1863 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1864 }
1865
1866 return $updateResult;
1867 }
1868
1869 /**
1870 * Returns all contribution related object ids.
1871 *
1872 * @param $contributionId
1873 *
1874 * @return array
1875 */
1876 public static function getComponentDetails($contributionId) {
1877 $componentDetails = $pledgePayment = array();
1878 if (!$contributionId) {
1879 return $componentDetails;
1880 }
1881
1882 $query = "
1883 SELECT c.id as contribution_id,
1884 c.contact_id as contact_id,
1885 c.contribution_recur_id,
1886 mp.membership_id as membership_id,
1887 m.membership_type_id as membership_type_id,
1888 pp.participant_id as participant_id,
1889 p.event_id as event_id,
1890 pgp.id as pledge_payment_id
1891 FROM civicrm_contribution c
1892 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1893 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1894 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1895 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1896 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1897 WHERE c.id = $contributionId";
1898
1899 $dao = CRM_Core_DAO::executeQuery($query);
1900 $componentDetails = array();
1901
1902 while ($dao->fetch()) {
1903 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1904 $componentDetails['contact_id'] = $dao->contact_id;
1905 if ($dao->event_id) {
1906 $componentDetails['event'] = $dao->event_id;
1907 }
1908 if ($dao->participant_id) {
1909 $componentDetails['participant'] = $dao->participant_id;
1910 }
1911 if ($dao->membership_id) {
1912 if (!isset($componentDetails['membership'])) {
1913 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1914 }
1915 $componentDetails['membership'][] = $dao->membership_id;
1916 $componentDetails['membership_type'][] = $dao->membership_type_id;
1917 }
1918 if ($dao->pledge_payment_id) {
1919 $pledgePayment[] = $dao->pledge_payment_id;
1920 }
1921 if ($dao->contribution_recur_id) {
1922 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
1923 }
1924 }
1925
1926 if ($pledgePayment) {
1927 $componentDetails['pledge_payment'] = $pledgePayment;
1928 }
1929
1930 return $componentDetails;
1931 }
1932
1933 /**
1934 * @param int $contactId
1935 * @param bool $includeSoftCredit
1936 *
1937 * @return null|string
1938 */
1939 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1940 if (!$contactId) {
1941 return 0;
1942 }
1943 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
1944 $additionalWhere = " AND contribution.financial_type_id IN (0)";
1945 $liWhere = " AND i.financial_type_id IN (0)";
1946 if (!empty($financialTypes)) {
1947 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1948 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1949 }
1950 $contactContributionsSQL = "
1951 SELECT contribution.id AS id
1952 FROM civicrm_contribution contribution
1953 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
1954 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
1955 $additionalWhere
1956 AND i.id IS NULL";
1957
1958 $contactSoftCreditContributionsSQL = "
1959 SELECT contribution.id
1960 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1961 ON ( contribution.id = softContribution.contribution_id )
1962 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1963 $query = "SELECT count( x.id ) count FROM ( ";
1964 $query .= $contactContributionsSQL;
1965
1966 if ($includeSoftCredit) {
1967 $query .= " UNION ";
1968 $query .= $contactSoftCreditContributionsSQL;
1969 }
1970
1971 $query .= ") x";
1972
1973 return CRM_Core_DAO::singleValueQuery($query);
1974 }
1975
1976 /**
1977 * Repeat a transaction as part of a recurring series.
1978 *
1979 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
1980 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
1981 * subsequent call to the contribution.completetransaction api.
1982 *
1983 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
1984 *
1985 * @param CRM_Contribute_BAO_Contribution $contribution
1986 * @param array $input
1987 * @param array $contributionParams
1988 *
1989 * @return array
1990 */
1991 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
1992 if (!empty($contribution->id)) {
1993 return FALSE;
1994 }
1995 if (empty($contribution->id)) {
1996 // Unclear why this would only be set for repeats.
1997 if (!empty($input['amount'])) {
1998 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
1999 }
2000 $templateContribution = civicrm_api3('Contribution', 'getsingle', array(
2001 'contribution_recur_id' => $contributionParams['contribution_recur_id'],
2002 'options' => array('limit' => 1),
2003 ));
2004 $contributionParams['skipLineItem'] = TRUE;
2005 $contributionParams['status_id'] = 'Pending';
2006 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2007 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2008 $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source'];
2009 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2010 $contribution->id = $createContribution['id'];
2011 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($contribution->contribution_recur_id, $contribution);
2012 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id);
2013 return TRUE;
2014 }
2015 }
2016
2017 /**
2018 * Get individual id for onbehalf contribution.
2019 *
2020 * @param int $contributionId
2021 * Contribution id.
2022 * @param int $contributorId
2023 * Contributor id.
2024 *
2025 * @return array
2026 * containing organization id and individual id
2027 */
2028 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2029
2030 $ids = array();
2031
2032 if (!$contributionId) {
2033 return $ids;
2034 }
2035
2036 // fetch contributor id if null
2037 if (!$contributorId) {
2038 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2039 $contributionId, 'contact_id'
2040 );
2041 }
2042
2043 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2044 $activityTypeId = array_search('Contribution', $activityTypeIds);
2045
2046 if ($activityTypeId && $contributorId) {
2047 $activityQuery = "
2048 SELECT civicrm_activity_contact.contact_id
2049 FROM civicrm_activity_contact
2050 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2051 WHERE civicrm_activity.activity_type_id = %1
2052 AND civicrm_activity.source_record_id = %2
2053 AND civicrm_activity_contact.record_type_id = %3
2054 ";
2055
2056 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2057 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2058
2059 $params = array(
2060 1 => array($activityTypeId, 'Integer'),
2061 2 => array($contributionId, 'Integer'),
2062 3 => array($sourceID, 'Integer'),
2063 );
2064
2065 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2066
2067 // for on behalf contribution source is individual and contributor is organization
2068 if ($sourceContactId && $sourceContactId != $contributorId) {
2069 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2070 // get rel type id for employee of relation
2071 foreach ($relationshipTypeIds as $id => $typeVals) {
2072 if ($typeVals['name_a_b'] == 'Employee of') {
2073 $relationshipTypeId = $id;
2074 break;
2075 }
2076 }
2077
2078 $rel = new CRM_Contact_DAO_Relationship();
2079 $rel->relationship_type_id = $relationshipTypeId;
2080 $rel->contact_id_a = $sourceContactId;
2081 $rel->contact_id_b = $contributorId;
2082 if ($rel->find(TRUE)) {
2083 $ids['individual_id'] = $rel->contact_id_a;
2084 $ids['organization_id'] = $rel->contact_id_b;
2085 }
2086 }
2087 }
2088
2089 return $ids;
2090 }
2091
2092 /**
2093 * @return array
2094 */
2095 public static function getContributionDates() {
2096 $config = CRM_Core_Config::singleton();
2097 $currentMonth = date('m');
2098 $currentDay = date('d');
2099 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2100 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2101 (int ) $config->fiscalYearStart['d'] > $currentDay
2102 )
2103 ) {
2104 $year = date('Y') - 1;
2105 }
2106 else {
2107 $year = date('Y');
2108 }
2109 $year = array('Y' => $year);
2110 $yearDate = $config->fiscalYearStart;
2111 $yearDate = array_merge($year, $yearDate);
2112 $yearDate = CRM_Utils_Date::format($yearDate);
2113
2114 $monthDate = date('Ym') . '01';
2115
2116 $now = date('Ymd');
2117
2118 return array(
2119 'now' => $now,
2120 'yearDate' => $yearDate,
2121 'monthDate' => $monthDate,
2122 );
2123 }
2124
2125 /**
2126 * Load objects relations to contribution object.
2127 * Objects are stored in the $_relatedObjects property
2128 * In the first instance we are just moving functionality from BASEIpn -
2129 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2130 *
2131 * Note that the unit test for the BaseIPN class tests this function
2132 *
2133 * @param array $input
2134 * Input as delivered from Payment Processor.
2135 * @param array $ids
2136 * Ids as Loaded by Payment Processor.
2137 * @param bool $loadAll
2138 * Load all related objects - even where id not passed in? (allows API to call this).
2139 *
2140 * @return bool
2141 * @throws Exception
2142 */
2143 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2144 if ($loadAll) {
2145 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2146 if (empty($ids['contact']) && isset($this->contact_id)) {
2147 $ids['contact'] = $this->contact_id;
2148 }
2149 }
2150 if (empty($this->_component)) {
2151 if (!empty($ids['event'])) {
2152 $this->_component = 'event';
2153 }
2154 else {
2155 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2156 }
2157 }
2158
2159 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2160 // refactoring than anything else, and has unit test coverage.
2161 if (empty($this->financial_type_id)) {
2162 $this->find(TRUE);
2163 }
2164
2165 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2166 'paymentProcessor',
2167 $ids
2168 ));
2169
2170 if (!$paymentProcessorID && $this->contribution_page_id) {
2171 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2172 $this->contribution_page_id,
2173 'payment_processor'
2174 );
2175 if ($paymentProcessorID) {
2176 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2177 }
2178 }
2179
2180 $ids['contributionType'] = $this->financial_type_id;
2181 $ids['financialType'] = $this->financial_type_id;
2182
2183 $entities = array(
2184 'contact' => 'CRM_Contact_BAO_Contact',
2185 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2186 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2187 'financialType' => 'CRM_Financial_BAO_FinancialType',
2188 );
2189 foreach ($entities as $entity => $bao) {
2190 if (!empty($ids[$entity])) {
2191 $this->_relatedObjects[$entity] = new $bao();
2192 $this->_relatedObjects[$entity]->id = $ids[$entity];
2193 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
2194 throw new CRM_Core_Exception($entity . ' could not be loaded');
2195 }
2196 }
2197 }
2198
2199 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2200 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
2201 }
2202
2203 if (!empty($ids['pledge_payment'])) {
2204 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2205 if (empty($paymentID)) {
2206 continue;
2207 }
2208 $payment = new CRM_Pledge_BAO_PledgePayment();
2209 $payment->id = $paymentID;
2210 if (!$payment->find(TRUE)) {
2211 throw new Exception("Could not find pledge payment record: " . $paymentID);
2212 }
2213 $this->_relatedObjects['pledge_payment'][] = $payment;
2214 }
2215 }
2216
2217 if ($this->_component == 'contribute') {
2218 // retrieve the other optional objects first so
2219 // stuff down the line can use this info and do things
2220 // CRM-6056
2221 //in any case get the memberships associated with the contribution
2222 //because we now support multiple memberships w/ price set
2223 // see if there are any other memberships to be considered for same contribution.
2224 $query = "
2225 SELECT membership_id
2226 FROM civicrm_membership_payment
2227 WHERE contribution_id = %1 ";
2228 $params = array(1 => array($this->id, 'Integer'));
2229
2230 $dao = CRM_Core_DAO::executeQuery($query, $params);
2231 while ($dao->fetch()) {
2232 if ($dao->membership_id) {
2233 if (!is_array($ids['membership'])) {
2234 $ids['membership'] = array();
2235 }
2236 $ids['membership'][] = $dao->membership_id;
2237 }
2238 }
2239
2240 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2241 foreach ($ids['membership'] as $id) {
2242 if (!empty($id)) {
2243 $membership = new CRM_Member_BAO_Membership();
2244 $membership->id = $id;
2245 if (!$membership->find(TRUE)) {
2246 throw new Exception("Could not find membership record: $id");
2247 }
2248 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2249 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2250 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2251 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2252 $membership->free();
2253 }
2254 }
2255 }
2256 }
2257 else {
2258 // we are in event mode
2259 // make sure event exists and is valid
2260 $event = new CRM_Event_BAO_Event();
2261 $event->id = $ids['event'];
2262 if ($ids['event'] &&
2263 !$event->find(TRUE)
2264 ) {
2265 throw new Exception("Could not find event: " . $ids['event']);
2266 }
2267
2268 $this->_relatedObjects['event'] = &$event;
2269
2270 $participant = new CRM_Event_BAO_Participant();
2271 $participant->id = $ids['participant'];
2272 if ($ids['participant'] &&
2273 !$participant->find(TRUE)
2274 ) {
2275 throw new Exception("Could not find participant: " . $ids['participant']);
2276 }
2277 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2278
2279 $this->_relatedObjects['participant'] = &$participant;
2280
2281 // get the payment processor id from event - this is inaccurate see CRM-16923
2282 // in future we should look at throwing an exception here rather than an dubious guess.
2283 if (!$paymentProcessorID) {
2284 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2285 if ($paymentProcessorID) {
2286 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2287 }
2288 }
2289 }
2290
2291 if ($paymentProcessorID) {
2292 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2293 $this->is_test ? 'test' : 'live'
2294 );
2295 $ids['paymentProcessor'] = $paymentProcessorID;
2296 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
2297 }
2298 return TRUE;
2299 }
2300
2301 /**
2302 * Create array of message information - ie. return html version, txt version, to field
2303 *
2304 * @param array $input
2305 * Incoming information.
2306 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2307 * just check presence of recur object but maintaining legacy approach
2308 * to be careful)
2309 * @param array $ids
2310 * IDs of related objects.
2311 * @param array $values
2312 * Any values that may have already been compiled by calling process.
2313 * This is augmented by values 'gathered' by gatherMessageValues
2314 * @param bool $recur
2315 * @param bool $returnMessageText
2316 * Distinguishes between whether to send message or return.
2317 * message text. We are working towards this function ALWAYS returning message text & calling
2318 * function doing emails / pdfs with it
2319 *
2320 * @return array
2321 * messages
2322 * @throws Exception
2323 */
2324 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2325 $this->loadRelatedObjects($input, $ids);
2326
2327 if (empty($this->_component)) {
2328 $this->_component = CRM_Utils_Array::value('component', $input);
2329 }
2330
2331 //not really sure what params might be passed in but lets merge em into values
2332 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2333 $template = CRM_Core_Smarty::singleton();
2334 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2335 //what does recur 'mean here - to do with payment processor return functionality but
2336 // what is the importance
2337 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2338 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
2339
2340 $entityID = $entity = NULL;
2341 if (isset($ids['contribution'])) {
2342 $entity = 'contribution';
2343 $entityID = $ids['contribution'];
2344 }
2345 if (!empty($ids['membership'])) {
2346 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2347 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2348 // line having loaded an array
2349 $ids['membership'] = (array) $ids['membership'];
2350 $entity = 'membership';
2351 $entityID = $ids['membership'][0];
2352 }
2353
2354 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity));
2355 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2356 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2357
2358 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2359 //direct mode showing billing block, so use directIPN for temporary
2360 $template->assign('contributeMode', 'directIPN');
2361 }
2362 }
2363 // todo remove strtolower - check consistency
2364 if (strtolower($this->_component) == 'event') {
2365 $eventParams = array('id' => $this->_relatedObjects['participant']->event_id);
2366 $values['event'] = array();
2367
2368 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2369
2370 //get location details
2371 $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event');
2372 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2373
2374 $ufJoinParams = array(
2375 'entity_table' => 'civicrm_event',
2376 'entity_id' => $ids['event'],
2377 'module' => 'CiviEvent',
2378 );
2379
2380 list($custom_pre_id,
2381 $custom_post_ids
2382 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2383
2384 $values['custom_pre_id'] = $custom_pre_id;
2385 $values['custom_post_id'] = $custom_post_ids;
2386 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2387 //and cases involving status updation through ipn
2388 // whatever that means!
2389 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2390 // perhaps we should throw an e-notice if amount is set & force total_amount?
2391 if (!empty($input['amount'])) {
2392 $values['totalAmount'] = $input['amount'];
2393 }
2394
2395 if ($values['event']['is_email_confirm']) {
2396 $values['is_email_receipt'] = 1;
2397 }
2398 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2399 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2400 );
2401 }
2402 else {
2403 $values['contribution_id'] = $this->id;
2404 if (!empty($ids['related_contact'])) {
2405 $values['related_contact'] = $ids['related_contact'];
2406 if (isset($ids['onbehalf_dupe_alert'])) {
2407 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2408 }
2409 $entityBlock = array(
2410 'contact_id' => $ids['contact'],
2411 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2412 'Home', 'id', 'name'
2413 ),
2414 );
2415 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2416 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2417 }
2418 $isTest = FALSE;
2419 if ($this->is_test) {
2420 $isTest = TRUE;
2421 }
2422 if (!empty($this->_relatedObjects['membership'])) {
2423 foreach ($this->_relatedObjects['membership'] as $membership) {
2424 if ($membership->id) {
2425 $values['isMembership'] = TRUE;
2426
2427 // need to set the membership values here
2428 $template->assign('membership_assign', 1);
2429 $template->assign('membership_name',
2430 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2431 );
2432 $template->assign('mem_start_date', $membership->start_date);
2433 $template->assign('mem_join_date', $membership->join_date);
2434 $template->assign('mem_end_date', $membership->end_date);
2435 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2436 $template->assign('mem_status', $membership_status);
2437 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2438 $template->assign('is_pay_later', 1);
2439 }
2440
2441 // if separate payment there are two contributions recorded and the
2442 // admin will need to send a receipt for each of them separately.
2443 // we dont link the two in the db (but can potentially infer it if needed)
2444 $template->assign('is_separate_payment', 0);
2445
2446 if ($recur && $paymentObject) {
2447 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2448 $template->assign('cancelSubscriptionUrl', $url);
2449 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2450 $template->assign('updateSubscriptionBillingUrl', $url);
2451 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2452 $template->assign('updateSubscriptionUrl', $url);
2453 }
2454
2455 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2456
2457 return $result;
2458 // otherwise if its about sending emails, continue sending without return, as we
2459 // don't want to exit the loop.
2460 }
2461 }
2462 }
2463 else {
2464 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2465 }
2466 }
2467 }
2468
2469 /**
2470 * Gather values for contribution mail - this function has been created
2471 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2472 * Values related to the contribution in question are gathered
2473 *
2474 * @param array $input
2475 * Input into function (probably from payment processor).
2476 * @param array $values
2477 * @param array $ids
2478 * The set of ids related to the input.
2479 *
2480 * @return array
2481 */
2482 public function _gatherMessageValues($input, &$values, $ids = array()) {
2483 // set display address of contributor
2484 if ($this->address_id) {
2485 $addressParams = array('id' => $this->address_id);
2486 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2487 $addressDetails = array_values($addressDetails);
2488 $values['address'] = $addressDetails[0]['display'];
2489 }
2490 if ($this->_component == 'contribute') {
2491 //get soft contributions
2492 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
2493 if (!empty($softContributions)) {
2494 $values['softContributions'] = $softContributions['soft_credit'];
2495 }
2496 if (isset($this->contribution_page_id)) {
2497 CRM_Contribute_BAO_ContributionPage::setValues(
2498 $this->contribution_page_id,
2499 $values
2500 );
2501 if ($this->contribution_page_id) {
2502 // CRM-8254 - override default currency if applicable
2503 $config = CRM_Core_Config::singleton();
2504 $config->defaultCurrency = CRM_Utils_Array::value(
2505 'currency',
2506 $values,
2507 $config->defaultCurrency
2508 );
2509 }
2510 }
2511 // no contribution page -probably back office
2512 else {
2513 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2514 $values['is_email_receipt'] = 1;
2515 $values['title'] = 'Contribution';
2516 }
2517 // set lineItem for contribution
2518 if ($this->id) {
2519 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2520 if (!empty($lineItem)) {
2521 $itemId = key($lineItem);
2522 foreach ($lineItem as &$eachItem) {
2523 if (is_array($this->_relatedObjects['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2524 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2525 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2526 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2527 }
2528 }
2529 $values['lineItem'][0] = $lineItem;
2530 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2531 }
2532 }
2533
2534 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2535 $this->id,
2536 $this->contact_id
2537 );
2538 // if this is onbehalf of contribution then set related contact
2539 if (!empty($relatedContact['individual_id'])) {
2540 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2541 }
2542 }
2543 else {
2544 // event
2545 $eventParams = array(
2546 'id' => $this->_relatedObjects['event']->id,
2547 );
2548 $values['event'] = array();
2549
2550 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2551 // add custom fields for event
2552 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id);
2553
2554 $eventCustomGroup = array();
2555 foreach ($eventGroupTree as $key => $group) {
2556 if ($key === 'info') {
2557 continue;
2558 }
2559
2560 foreach ($group['fields'] as $k => $customField) {
2561 $groupLabel = $group['title'];
2562 if (!empty($customField['customValue'])) {
2563 foreach ($customField['customValue'] as $customFieldValues) {
2564 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2565 }
2566 }
2567 }
2568 }
2569 $values['event']['customGroup'] = $eventCustomGroup;
2570
2571 //get participant details
2572 $participantParams = array(
2573 'id' => $this->_relatedObjects['participant']->id,
2574 );
2575
2576 $values['participant'] = array();
2577
2578 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
2579 // add custom fields for event
2580 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id);
2581 $participantCustomGroup = array();
2582 foreach ($participantGroupTree as $key => $group) {
2583 if ($key === 'info') {
2584 continue;
2585 }
2586
2587 foreach ($group['fields'] as $k => $customField) {
2588 $groupLabel = $group['title'];
2589 if (!empty($customField['customValue'])) {
2590 foreach ($customField['customValue'] as $customFieldValues) {
2591 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2592 }
2593 }
2594 }
2595 }
2596 $values['participant']['customGroup'] = $participantCustomGroup;
2597
2598 //get location details
2599 $locationParams = array(
2600 'entity_id' => $this->_relatedObjects['event']->id,
2601 'entity_table' => 'civicrm_event',
2602 );
2603 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2604
2605 $ufJoinParams = array(
2606 'entity_table' => 'civicrm_event',
2607 'entity_id' => $ids['event'],
2608 'module' => 'CiviEvent',
2609 );
2610
2611 list($custom_pre_id,
2612 $custom_post_ids
2613 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2614
2615 $values['custom_pre_id'] = $custom_pre_id;
2616 $values['custom_post_id'] = $custom_post_ids;
2617
2618 // set lineItem for event contribution
2619 if ($this->id) {
2620 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2621 if (!empty($participantIds)) {
2622 foreach ($participantIds as $pIDs) {
2623 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2624 if (!CRM_Utils_System::isNull($lineItem)) {
2625 $values['lineItem'][] = $lineItem;
2626 }
2627 }
2628 }
2629 }
2630 }
2631
2632 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id);
2633
2634 $customGroup = array();
2635 foreach ($groupTree as $key => $group) {
2636 if ($key === 'info') {
2637 continue;
2638 }
2639
2640 foreach ($group['fields'] as $k => $customField) {
2641 $groupLabel = $group['title'];
2642 if (!empty($customField['customValue'])) {
2643 foreach ($customField['customValue'] as $customFieldValues) {
2644 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2645 }
2646 }
2647 }
2648 }
2649 $values['customGroup'] = $customGroup;
2650
2651 return $values;
2652 }
2653
2654 /**
2655 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2656 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2657 * Note we send directly from this function in some cases because it is only partly refactored
2658 * Don't call this function directly as the signature will change
2659 *
2660 * @param $values
2661 * @param $input
2662 * @param CRM_Core_SMARTY $template
2663 * @param bool $recur
2664 * @param bool $returnMessageText
2665 *
2666 * @return mixed
2667 */
2668 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2669 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2670 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2671 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2672 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2673 $template->assign('useForMember', TRUE);
2674 }
2675 //assign honor information to receipt message
2676 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2677
2678 if (isset($softRecord['soft_credit'])) {
2679 //if id of contribution page is present
2680 if (!empty($values['id'])) {
2681 $values['honor'] = array(
2682 'honor_profile_values' => array(),
2683 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2684 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2685 );
2686 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2687
2688 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2689 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2690 }
2691 else {
2692 //offline contribution
2693 $softCreditTypes = $softCredits = array();
2694 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2695 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2696 $softCredits[$key] = array(
2697 'Name' => $softCredit['contact_name'],
2698 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2699 );
2700 }
2701 $template->assign('softCreditTypes', $softCreditTypes);
2702 $template->assign('softCredits', $softCredits);
2703 }
2704 }
2705
2706 $dao = new CRM_Contribute_DAO_ContributionProduct();
2707 $dao->contribution_id = $this->id;
2708 if ($dao->find(TRUE)) {
2709 $premiumId = $dao->product_id;
2710 $template->assign('option', $dao->product_option);
2711
2712 $productDAO = new CRM_Contribute_DAO_Product();
2713 $productDAO->id = $premiumId;
2714 $productDAO->find(TRUE);
2715 $template->assign('selectPremium', TRUE);
2716 $template->assign('product_name', $productDAO->name);
2717 $template->assign('price', $productDAO->price);
2718 $template->assign('sku', $productDAO->sku);
2719 }
2720 $template->assign('title', CRM_Utils_Array::value('title', $values));
2721 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2722 if (empty($amount) && isset($this->total_amount)) {
2723 $amount = $this->total_amount;
2724 }
2725 $template->assign('amount', $amount);
2726 // add the new contribution values
2727 if (strtolower($this->_component) == 'contribute') {
2728 //PCP Info
2729 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2730 $softDAO->contribution_id = $this->id;
2731 if ($softDAO->find(TRUE)) {
2732 $template->assign('pcpBlock', TRUE);
2733 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2734 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2735 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2736
2737 //assign the pcp page title for email subject
2738 $pcpDAO = new CRM_PCP_DAO_PCP();
2739 $pcpDAO->id = $softDAO->pcp_id;
2740 if ($pcpDAO->find(TRUE)) {
2741 $template->assign('title', $pcpDAO->title);
2742 }
2743 }
2744 }
2745
2746 if ($this->financial_type_id) {
2747 $values['financial_type_id'] = $this->financial_type_id;
2748 }
2749
2750 $template->assign('trxn_id', $this->trxn_id);
2751 $template->assign('receive_date',
2752 CRM_Utils_Date::mysqlToIso($this->receive_date)
2753 );
2754 $template->assign('contributeMode', 'notify');
2755 $template->assign('action', $this->is_test ? 1024 : 1);
2756 $template->assign('receipt_text',
2757 CRM_Utils_Array::value('receipt_text',
2758 $values
2759 )
2760 );
2761 $template->assign('is_monetary', 1);
2762 $template->assign('is_recur', (bool) $recur);
2763 $template->assign('currency', $this->currency);
2764 $template->assign('address', CRM_Utils_Address::format($input));
2765 if (!empty($values['customGroup'])) {
2766 $template->assign('customGroup', $values['customGroup']);
2767 }
2768 if (!empty($values['softContributions'])) {
2769 $template->assign('softContributions', $values['softContributions']);
2770 }
2771 if ($this->_component == 'event') {
2772 $template->assign('title', $values['event']['title']);
2773 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2774 $viewRoles = array();
2775 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2776 $viewRoles[] = $participantRoles[$v];
2777 }
2778 $values['event']['participant_role'] = implode(', ', $viewRoles);
2779 $template->assign('event', $values['event']);
2780 $template->assign('participant', $values['participant']);
2781 $template->assign('location', $values['location']);
2782 $template->assign('customPre', $values['custom_pre_id']);
2783 $template->assign('customPost', $values['custom_post_id']);
2784
2785 $isTest = FALSE;
2786 if ($this->_relatedObjects['participant']->is_test) {
2787 $isTest = TRUE;
2788 }
2789
2790 $values['params'] = array();
2791 //to get email of primary participant.
2792 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2793 $primaryAmount[] = array(
2794 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2795 'amount' => $this->_relatedObjects['participant']->fee_amount,
2796 );
2797 //build an array of cId/pId of participants
2798 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2799 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2800 //send receipt to additional participant if exists
2801 if (count($additionalIDs)) {
2802 $template->assign('isPrimary', 0);
2803 $template->assign('customProfile', NULL);
2804 //set additionalParticipant true
2805 $values['params']['additionalParticipant'] = TRUE;
2806 foreach ($additionalIDs as $pId => $cId) {
2807 $amount = array();
2808 //to change the status pending to completed
2809 $additional = new CRM_Event_DAO_Participant();
2810 $additional->id = $pId;
2811 $additional->contact_id = $cId;
2812 $additional->find(TRUE);
2813 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2814 $additional->status_id = 1;
2815 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2816 //if additional participant dont have email
2817 //use display name.
2818 if (!$additionalParticipantInfo) {
2819 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2820 }
2821 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2822 $primaryAmount[] = array(
2823 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2824 'amount' => $additional->fee_amount,
2825 );
2826 $additional->save();
2827 $additional->free();
2828 $template->assign('amount', $amount);
2829 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2830 }
2831 }
2832
2833 //build an array of custom profile and assigning it to template
2834 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2835
2836 if (count($customProfile)) {
2837 $template->assign('customProfile', $customProfile);
2838 }
2839
2840 // for primary contact
2841 $values['params']['additionalParticipant'] = FALSE;
2842 $template->assign('isPrimary', 1);
2843 $template->assign('amount', $primaryAmount);
2844 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2845 if ($this->payment_instrument_id) {
2846 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2847 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2848 }
2849 // carry paylater, since we did not created billing,
2850 // so need to pull email from primary location, CRM-4395
2851 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2852 }
2853 return $template;
2854 }
2855
2856 /**
2857 * Check whether payment processor supports
2858 * cancellation of contribution subscription
2859 *
2860 * @param int $contributionId
2861 * Contribution id.
2862 *
2863 * @param bool $isNotCancelled
2864 *
2865 * @return bool
2866 */
2867 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2868 $cacheKeyString = "$contributionId";
2869 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2870
2871 static $supportsCancel = array();
2872
2873 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2874 $supportsCancel[$cacheKeyString] = FALSE;
2875 $isCancelled = FALSE;
2876
2877 if ($isNotCancelled) {
2878 $isCancelled = self::isSubscriptionCancelled($contributionId);
2879 }
2880
2881 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2882 if (!empty($paymentObject)) {
2883 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2884 }
2885 }
2886 return $supportsCancel[$cacheKeyString];
2887 }
2888
2889 /**
2890 * Check whether subscription is already cancelled.
2891 *
2892 * @param int $contributionId
2893 * Contribution id.
2894 *
2895 * @return string
2896 * contribution status
2897 */
2898 public static function isSubscriptionCancelled($contributionId) {
2899 $sql = "
2900 SELECT cr.contribution_status_id
2901 FROM civicrm_contribution_recur cr
2902 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2903 WHERE con.id = %1 LIMIT 1";
2904 $params = array(1 => array($contributionId, 'Integer'));
2905 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2906 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2907 if ($status == 'Cancelled') {
2908 return TRUE;
2909 }
2910 return FALSE;
2911 }
2912
2913 /**
2914 * Create all financial accounts entry.
2915 *
2916 * @param array $params
2917 * Contribution object, line item array and params for trxn.
2918 *
2919 *
2920 * @param array $financialTrxnValues
2921 *
2922 * @return null|object
2923 */
2924 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2925 $skipRecords = $update = $return = $isRelatedId = FALSE;
2926
2927 $additionalParticipantId = array();
2928 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2929
2930 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2931 $entityId = $params['participant_id'];
2932 $entityTable = 'civicrm_participant';
2933 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2934 }
2935 elseif (!empty($params['membership_id'])) {
2936 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2937 // are created off one contribution should be handled elsewhere
2938 $entityId = $params['membership_id'];
2939 $entityTable = 'civicrm_membership';
2940 }
2941 else {
2942 $entityId = $params['contribution']->id;
2943 $entityTable = 'civicrm_contribution';
2944 }
2945
2946 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2947 $isRelatedId = TRUE;
2948 }
2949
2950 $entityID[] = $entityId;
2951 if (!empty($additionalParticipantId)) {
2952 $entityID += $additionalParticipantId;
2953 }
2954 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2955 if (empty($params['prevContribution'])) {
2956 $entityID = NULL;
2957 }
2958 else {
2959 $update = TRUE;
2960 }
2961
2962 $statusId = $params['contribution']->contribution_status_id;
2963 // CRM-13964 partial payment
2964 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2965 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2966 ) {
2967 $partialAmtPay = $params['partial_amount_pay'];
2968 $partialAmtTotal = $params['partial_payment_total'];
2969
2970 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2971 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2972 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
2973 $params['total_amount'] = $partialAmtPay;
2974
2975 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
2976 if (empty($balanceTrxnInfo['trxn_id'])) {
2977 // create new balance transaction record
2978 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2979 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2980
2981 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2982 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2983 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2984 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis');
2985 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2986 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2987 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2988 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2989 $balanceTrxnParams['status_id'] = $statusId;
2990 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2991 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
2992 if (!empty($params['payment_processor'])) {
2993 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2994 }
2995 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
2996 }
2997 }
2998
2999 // build line item array if its not set in $params
3000 if (empty($params['line_item']) || $additionalParticipantId) {
3001 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3002 }
3003
3004 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
3005 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
3006 ) {
3007 $skipRecords = TRUE;
3008 $pendingStatus = array(
3009 array_search('Pending', $contributionStatuses),
3010 array_search('In Progress', $contributionStatuses),
3011 );
3012 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
3013 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3014 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
3015 }
3016 elseif (!empty($params['payment_processor'])) {
3017 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3018 }
3019 elseif (!empty($params['payment_instrument_id'])) {
3020 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3021 }
3022 else {
3023 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3024 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3025 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3026 }
3027
3028 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
3029 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3030 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3031 }
3032
3033 //build financial transaction params
3034 $trxnParams = array(
3035 'contribution_id' => $params['contribution']->id,
3036 'to_financial_account_id' => $params['to_financial_account_id'],
3037 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
3038 'total_amount' => $totalAmount,
3039 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
3040 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
3041 'currency' => $params['contribution']->currency,
3042 'trxn_id' => $params['contribution']->trxn_id,
3043 'status_id' => $statusId,
3044 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
3045 'check_number' => CRM_Utils_Array::value('check_number', $params),
3046 );
3047
3048 if (!empty($params['payment_processor'])) {
3049 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3050 }
3051
3052 if (isset($fromFinancialAccountId)) {
3053 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3054 }
3055
3056 // consider external values passed for recording transaction entry
3057 if (!empty($financialTrxnValues)) {
3058 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3059 }
3060
3061 $params['trxnParams'] = $trxnParams;
3062
3063 if (!empty($params['prevContribution'])) {
3064 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3065 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3066 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
3067 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3068 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
3069
3070 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
3071 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3072 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3073 ) {
3074 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3075 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3076 }
3077
3078 //if financial type is changed
3079 if (!empty($params['financial_type_id']) &&
3080 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3081 ) {
3082 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3083 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
3084 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
3085 if ($oldFinancialAccount != $newFinancialAccount) {
3086 $params['total_amount'] = 0;
3087 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
3088 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
3089 $params['prevContribution']->financial_type_id, $relationTypeId);
3090 }
3091 else {
3092 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3093 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3094 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3095 }
3096 }
3097 self::updateFinancialAccounts($params, 'changeFinancialType');
3098 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3099 $params['financial_account_id'] = $newFinancialAccount;
3100 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3101 self::updateFinancialAccounts($params);
3102 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3103 }
3104 }
3105
3106 //Update contribution status
3107 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
3108 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3109 if (!empty($params['contribution_status_id']) &&
3110 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3111 ) {
3112 //Update Financial Records
3113 self::updateFinancialAccounts($params, 'changedStatus');
3114 }
3115
3116 // change Payment Instrument for a Completed contribution
3117 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3118 // instrument is null and now new payment instrument is added along with the payment
3119 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3120 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
3121 if (array_key_exists('payment_instrument_id', $params)) {
3122 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3123 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
3124 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
3125 ) {
3126 //check if status is changed from Pending to Completed
3127 // do not update payment instrument changes for Pending to Completed
3128 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
3129 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
3130 ) {
3131 // for all other statuses create new financial records
3132 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3133 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3134 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3135 }
3136 }
3137 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
3138 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
3139 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
3140 ) {
3141 // for any other payment instrument changes create new financial records
3142 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3143 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3144 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3145 }
3146 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
3147 $params['contribution']->check_number != $params['prevContribution']->check_number
3148 ) {
3149 // another special case when check number is changed, create new financial records
3150 // create financial trxn with negative amount
3151 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3152 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3153 // create financial trxn with positive amount
3154 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
3155 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3156 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3157 }
3158 }
3159
3160 //if Change contribution amount
3161 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3162 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3163 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3164 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3165 if (isset($totalAmount) &&
3166 $totalAmount != $params['prevContribution']->total_amount
3167 ) {
3168 //Update Financial Records
3169 $params['trxnParams']['from_financial_account_id'] = NULL;
3170 self::updateFinancialAccounts($params, 'changedAmount');
3171 }
3172 }
3173
3174 if (!$update) {
3175 // records finanical trxn and entity financial trxn
3176 // also make it available as return value
3177 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3178 $params['entity_id'] = $financialTxn->id;
3179 }
3180 }
3181 // record line items and financial items
3182 if (empty($params['skipLineItem'])) {
3183 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
3184 }
3185
3186 // create batch entry if batch_id is passed and
3187 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3188 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3189 $entityParams = array(
3190 'batch_id' => $params['batch_id'],
3191 'entity_table' => 'civicrm_financial_trxn',
3192 'entity_id' => $financialTxn->id,
3193 );
3194 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
3195 }
3196
3197 // when a fee is charged
3198 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
3199 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3200 }
3201
3202 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3203 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3204 ) {
3205 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3206 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3207 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3208 }
3209 unset($params['line_item']);
3210
3211 return $return;
3212 }
3213
3214 /**
3215 * Update all financial accounts entry.
3216 *
3217 * @param array $params
3218 * Contribution object, line item array and params for trxn.
3219 *
3220 * @param string $context
3221 * Update scenarios.
3222 *
3223 * @param null $skipTrxn
3224 *
3225 */
3226 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3227 $itemAmount = $trxnID = NULL;
3228 //get all the statuses
3229 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3230 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3231 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
3232 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3233 && $context == 'changePaymentInstrument'
3234 ) {
3235 return;
3236 }
3237 if (($params['prevContribution']->contribution_status_id == array_search('Partially paid', $contributionStatus))
3238 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3239 && $context == 'changedStatus'
3240 ) {
3241 return;
3242 }
3243 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3244 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
3245 }
3246 if ($context == 'changedStatus') {
3247 //get all the statuses
3248 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3249
3250 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3251 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3252 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
3253 ) {
3254 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3255 if (empty($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
3256 $creditNoteId = self::createCreditNoteId();
3257 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
3258 }
3259 }
3260 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3261 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
3262 ) {
3263 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
3264 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3265 $arAccountId = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeID, $relationTypeId);
3266
3267 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
3268 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3269 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3270 if (is_null($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
3271 $creditNoteId = self::createCreditNoteId();
3272 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
3273 }
3274 }
3275 else {
3276 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3277 }
3278 }
3279 $itemAmount = $params['trxnParams']['total_amount'];
3280 }
3281 elseif ($context == 'changePaymentInstrument') {
3282 if ($params['trxnParams']['total_amount'] < 0) {
3283 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3284 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3285 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3286 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3287 }
3288 }
3289 else {
3290 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3291 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3292 }
3293 }
3294 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3295 $params['entity_id'] = $trxn->id;
3296
3297 if ($context == 'changedStatus') {
3298 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3299 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
3300 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3301 ) {
3302 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3303 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3304
3305 $entityParams = array(
3306 'entity_table' => 'civicrm_financial_item',
3307 'financial_trxn_id' => $trxn->id,
3308 );
3309 if (empty($params['line_item'])) {
3310 //CRM-15296
3311 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3312 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3313 // & this can be removed
3314 return;
3315 }
3316 foreach ($params['line_item'] as $fieldId => $fields) {
3317 foreach ($fields as $fieldValueId => $fieldValues) {
3318 $fparams = array(
3319 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3320 2 => array($fieldValues['id'], 'Integer'),
3321 );
3322 CRM_Core_DAO::executeQuery($query, $fparams);
3323 $fparams = array(
3324 1 => array($fieldValues['id'], 'Integer'),
3325 );
3326 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3327 while ($financialItem->fetch()) {
3328 $entityParams['entity_id'] = $financialItem->id;
3329 $entityParams['amount'] = $financialItem->amount;
3330 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3331 }
3332 }
3333 }
3334 return;
3335 }
3336 }
3337 if ($context != 'changePaymentInstrument') {
3338 $itemParams['entity_table'] = 'civicrm_line_item';
3339 $trxnIds['id'] = $params['entity_id'];
3340 foreach ($params['line_item'] as $fieldId => $fields) {
3341 foreach ($fields as $fieldValueId => $fieldValues) {
3342 $prevParams['entity_id'] = $fieldValues['id'];
3343 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3344
3345 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3346 if ($params['contribution']->receive_date) {
3347 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3348 }
3349
3350 $financialAccount = $prevfinancialItem->financial_account_id;
3351 if (!empty($params['financial_account_id'])) {
3352 $financialAccount = $params['financial_account_id'];
3353 }
3354
3355 $currency = $params['prevContribution']->currency;
3356 if ($params['contribution']->currency) {
3357 $currency = $params['contribution']->currency;
3358 }
3359 $diff = 1;
3360 if (!empty($params['is_quick_config'])) {
3361 $amount = $itemAmount;
3362 if (!$amount) {
3363 $amount = $params['total_amount'];
3364 }
3365 }
3366 else {
3367 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
3368 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3369 ) {
3370 $diff = -1;
3371 }
3372 $amount = $diff * $fieldValues['line_total'];
3373 }
3374
3375 $itemParams = array(
3376 'transaction_date' => $receiveDate,
3377 'contact_id' => $params['prevContribution']->contact_id,
3378 'currency' => $currency,
3379 'amount' => $amount,
3380 'description' => $prevfinancialItem->description,
3381 'status_id' => $prevfinancialItem->status_id,
3382 'financial_account_id' => $financialAccount,
3383 'entity_table' => 'civicrm_line_item',
3384 'entity_id' => $fieldValues['id'],
3385 );
3386 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3387
3388 if ($fieldValues['tax_amount']) {
3389 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3390 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3391 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3392 $itemParams['description'] = $taxTerm;
3393 if ($fieldValues['financial_type_id']) {
3394 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3395 }
3396 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3397 }
3398 }
3399 }
3400 }
3401 if ($context == 'changeFinancialType') {
3402 $params['skipLineItem'] = FALSE;
3403 foreach ($params['line_item'] as &$lineItems) {
3404 foreach ($lineItems as &$line) {
3405 $line['financial_type_id'] = $params['financial_type_id'];
3406 }
3407 }
3408 }
3409 }
3410
3411 /**
3412 * Check status validation on update of a contribution.
3413 *
3414 * @param array $values
3415 * Previous form values before submit.
3416 *
3417 * @param array $fields
3418 * The input form values.
3419 *
3420 * @param array $errors
3421 * List of errors.
3422 *
3423 * @return bool
3424 */
3425 public static function checkStatusValidation($values, &$fields, &$errors) {
3426 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3427 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3428 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3429 return FALSE;
3430 }
3431 }
3432 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3433 $checkStatus = array(
3434 'Cancelled' => array('Completed', 'Refunded'),
3435 'Completed' => array('Cancelled', 'Refunded'),
3436 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3437 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3438 'Refunded' => array('Cancelled', 'Completed'),
3439 'Partially paid' => array('Completed'),
3440 );
3441
3442 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3443 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3444 1 => $contributionStatuses[$values['contribution_status_id']],
3445 2 => $contributionStatuses[$fields['contribution_status_id']],
3446 ));
3447 }
3448 }
3449
3450 /**
3451 * Delete contribution of contact.
3452 *
3453 * CRM-12155
3454 *
3455 * @param int $contactId
3456 * Contact id.
3457 *
3458 */
3459 public static function deleteContactContribution($contactId) {
3460 $contribution = new CRM_Contribute_DAO_Contribution();
3461 $contribution->contact_id = $contactId;
3462 $contribution->find();
3463 while ($contribution->fetch()) {
3464 self::deleteContribution($contribution->id);
3465 }
3466 }
3467
3468 /**
3469 * Get options for a given contribution field.
3470 * @see CRM_Core_DAO::buildOptions
3471 *
3472 * @param string $fieldName
3473 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3474 * @param array $props whatever is known about this dao object.
3475 *
3476 * @return array|bool
3477 */
3478 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3479 $className = __CLASS__;
3480 $params = array();
3481 switch ($fieldName) {
3482 // This field is not part of this object but the api supports it
3483 case 'payment_processor':
3484 $className = 'CRM_Contribute_BAO_ContributionPage';
3485 // Filter results by contribution page
3486 if (!empty($props['contribution_page_id'])) {
3487 $page = civicrm_api('contribution_page', 'getsingle', array(
3488 'version' => 3,
3489 'id' => ($props['contribution_page_id']),
3490 ));
3491 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3492 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3493 }
3494 break;
3495
3496 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3497 case 'honor_type_id':
3498 $className = 'CRM_Contribute_BAO_ContributionSoft';
3499 $fieldName = 'soft_credit_type_id';
3500 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3501 break;
3502 }
3503 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3504 }
3505
3506 /**
3507 * Validate financial type.
3508 *
3509 * CRM-13231
3510 *
3511 * @param int $financialTypeId
3512 * Financial Type id.
3513 *
3514 * @param string $relationName
3515 *
3516 * @return array|bool
3517 */
3518 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3519 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3520 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3521
3522 if (!$financialAccount) {
3523 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3524 }
3525 return FALSE;
3526 }
3527
3528
3529 /**
3530 * Function to record additional payment for partial and refund contributions.
3531 *
3532 * @param int $contributionId
3533 * is the invoice contribution id (got created after processing participant payment).
3534 * @param array $trxnsData
3535 * to take user provided input of transaction details.
3536 * @param string $paymentType
3537 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3538 * @param int $participantId
3539 *
3540 * @return null|object
3541 */
3542 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3543 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3544 $getInfoOf['id'] = $contributionId;
3545 $defaults = array();
3546 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3547
3548 if ($paymentType == 'owed') {
3549 // build params for recording financial trxn entry
3550 $params['contribution'] = $contributionDAO;
3551 $params = array_merge($defaults, $params);
3552 $params['skipLineItem'] = TRUE;
3553 $params['partial_payment_total'] = $contributionDAO->total_amount;
3554 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3555 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3556 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3557
3558 // record the entry
3559 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3560 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3561 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3562
3563 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3564 if (!empty($trxnId)) {
3565 $trxnId = $trxnId['trxn_id'];
3566 }
3567 elseif (!empty($contributionDAO->payment_instrument_id)) {
3568 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3569 }
3570 else {
3571 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3572 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3573 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3574 }
3575
3576 // update statuses
3577 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3578 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3579 FROM civicrm_financial_trxn ft
3580 LEFT JOIN civicrm_entity_financial_trxn eft
3581 ON (ft.id = eft.financial_trxn_id)
3582 WHERE eft.entity_table = 'civicrm_contribution'
3583 AND eft.entity_id = {$contributionId}
3584 AND ft.to_financial_account_id != {$toFinancialAccount}
3585 AND ft.status_id = {$statusId}
3586 ";
3587 $query = CRM_Core_DAO::executeQuery($sql);
3588 $query->fetch();
3589 $sumOfPayments = $query->sum_of_payments;
3590
3591 // update statuses
3592 if ($contributionDAO->total_amount == $sumOfPayments) {
3593 // update contribution status and
3594 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3595 $contributionDAO->contribution_status_id = $statusId;
3596 $contributionDAO->cancel_date = 'null';
3597 $contributionDAO->cancel_reason = NULL;
3598 $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
3599 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
3600 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
3601 $contributionDAO->save();
3602
3603 //Change status of financial record too
3604 $financialTrxn->status_id = $statusId;
3605 $financialTrxn->save();
3606
3607 // note : not using the self::add method,
3608 // the reason because it performs 'status change' related code execution for financial records
3609 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3610 // are coded below i.e. just updating financial_item status to 'Paid'
3611
3612 if ($participantId) {
3613 // update participant status
3614 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3615 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3616 foreach ($ids as $val) {
3617 $participantUpdate['id'] = $val;
3618 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3619 CRM_Event_BAO_Participant::add($participantUpdate);
3620 }
3621 }
3622
3623 // update financial item statuses
3624 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3625 $paidStatus = array_search('Paid', $financialItemStatus);
3626
3627 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3628 $sqlFinancialItemUpdate = "
3629 UPDATE civicrm_financial_item fi
3630 LEFT JOIN civicrm_entity_financial_trxn eft
3631 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3632 SET status_id = {$paidStatus}
3633 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3634 ";
3635 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3636 }
3637 }
3638 elseif ($paymentType == 'refund') {
3639 // build params for recording financial trxn entry
3640 $params['contribution'] = $contributionDAO;
3641 $params = array_merge($defaults, $params);
3642 $params['skipLineItem'] = TRUE;
3643 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3644 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3645
3646 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3647 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3648 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3649 // record the entry
3650 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3651
3652 // note : not using the self::add method,
3653 // the reason because it performs 'status change' related code execution for financial records
3654 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3655 // are coded below i.e. just updating financial_item status to 'Paid'
3656 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3657
3658 // add financial item entry
3659 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3660 $getLine['entity_id'] = $contributionDAO->id;
3661 $getLine['entity_table'] = 'civicrm_contribution';
3662 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
3663 if (!empty($lineItemId->id)) {
3664 $addFinancialEntry = array(
3665 'transaction_date' => $financialTrxn->trxn_date,
3666 'contact_id' => $contributionDAO->contact_id,
3667 'amount' => $financialTrxn->total_amount,
3668 'status_id' => array_search('Paid', $financialItemStatus),
3669 'entity_id' => $lineItemId->id,
3670 'entity_table' => 'civicrm_line_item',
3671 );
3672 $trxnIds['id'] = $financialTrxn->id;
3673 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3674 }
3675 if ($participantId) {
3676 // update participant status
3677 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3678 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3679 foreach ($ids as $val) {
3680 $participantUpdate['id'] = $val;
3681 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3682 CRM_Event_BAO_Participant::add($participantUpdate);
3683 }
3684 }
3685 }
3686
3687 // activity creation
3688 if (!empty($financialTrxn)) {
3689 if ($participantId) {
3690 $inputParams['id'] = $participantId;
3691 $values = array();
3692 $ids = array();
3693 $component = 'event';
3694 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3695 $entityObj = $entityObj[$participantId];
3696 }
3697 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3698
3699 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3700 }
3701 return $financialTrxn;
3702 }
3703
3704 /**
3705 * @param $entityObj
3706 * @param $trxnObj
3707 * @param $activityType
3708 * @param $component
3709 * @param int $contributionId
3710 *
3711 * @throws CRM_Core_Exception
3712 */
3713 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3714 if ($component == 'event') {
3715 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3716 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3717 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3718 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3719 $targetCid = $entityObj->contact_id;
3720 // source record id would be the contribution id
3721 $srcRecId = $contributionId;
3722 }
3723
3724 // activity params
3725 $activityParams = array(
3726 'source_contact_id' => $targetCid,
3727 'source_record_id' => $srcRecId,
3728 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3729 $activityType,
3730 'name'
3731 ),
3732 'subject' => $subject,
3733 'activity_date_time' => $date,
3734 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3735 'Completed',
3736 'name'
3737 ),
3738 'skipRecentView' => TRUE,
3739 );
3740
3741 // create activity with target contacts
3742 $session = CRM_Core_Session::singleton();
3743 $id = $session->get('userID');
3744 if ($id) {
3745 $activityParams['source_contact_id'] = $id;
3746 $activityParams['target_contact_id'][] = $targetCid;
3747 }
3748 CRM_Activity_BAO_Activity::create($activityParams);
3749 }
3750
3751 /**
3752 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3753 *
3754 * @param int $id
3755 * @param $component
3756 * @param bool $getTrxnInfo
3757 * @param bool $usingLineTotal
3758 *
3759 * @return mixed
3760 */
3761 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3762 if ($component == 'event') {
3763 $entity = 'participant';
3764 $entityTable = 'civicrm_participant';
3765 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3766
3767 if (!$contributionId) {
3768 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3769 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3770 $id = $primaryParticipantId;
3771 }
3772 if (!$contributionId) {
3773 return;
3774 }
3775 }
3776 }
3777 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3778 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3779 $isBalance = NULL;
3780 if ($baseTrxnId) {
3781 $isBalance = TRUE;
3782 }
3783 else {
3784 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3785 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3786 $isBalance = FALSE;
3787 }
3788 if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
3789 // for additional participants
3790 if ($entityTable == 'civicrm_participant') {
3791 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3792 $total = 0;
3793 foreach ($ids as $val) {
3794 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3795 }
3796 }
3797 else {
3798 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3799 }
3800 }
3801 else {
3802 $baseTrxnId = $total['trxn_id'];
3803 $total = $total['total_amount'];
3804 }
3805
3806 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
3807 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3808
3809 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3810 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3811 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
3812
3813 if ($paymentBalance == 0 && $contributionIsPayLater) {
3814 $paymentBalance = $total;
3815 }
3816
3817 $info['total'] = $total;
3818 $info['paid'] = $total - $paymentBalance;
3819 $info['balance'] = $paymentBalance;
3820 $info['id'] = $id;
3821 $info['component'] = $component;
3822 $info['payLater'] = $contributionIsPayLater;
3823 $rows = array();
3824 if ($getTrxnInfo && $baseTrxnId) {
3825 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3826 $sql = "
3827 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3828 FROM civicrm_contribution con
3829 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3830 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3831 WHERE con.id = {$contributionId}
3832 ";
3833
3834 // conditioned WHERE clause
3835 if ($isBalance) {
3836 // if balance trxn exists don't include details of it in transaction info
3837 $sql .= " AND ft.id != {$baseTrxnId} ";
3838 }
3839 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3840
3841 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3842 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
3843 while ($resultDAO->fetch()) {
3844 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3845 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3846 $val = array(
3847 'total_amount' => $resultDAO->total_amount,
3848 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
3849 'payment_instrument' => $paidByLabel,
3850 'receive_date' => $resultDAO->trxn_date,
3851 'trxn_id' => $resultDAO->trxn_id,
3852 'status' => $statuses[$resultDAO->status_id],
3853 );
3854 if ($paidByName == 'Check') {
3855 $val['check_number'] = $resultDAO->check_number;
3856 }
3857 $rows[] = $val;
3858 }
3859 $info['transaction'] = $rows;
3860 }
3861 return $info;
3862 }
3863
3864 /**
3865 * Get financial account id has 'Sales Tax Account is'
3866 * account relationship with financial type
3867 *
3868 * @param int $financialTypeId
3869 *
3870 * @return FinancialAccountId
3871 */
3872 public static function getFinancialAccountId($financialTypeId) {
3873 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3874 $searchParams = array(
3875 'entity_table' => 'civicrm_financial_type',
3876 'entity_id' => $financialTypeId,
3877 'account_relationship' => $accountRel,
3878 );
3879 $result = array();
3880 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
3881
3882 return CRM_Utils_Array::value('financial_account_id', $result);
3883 }
3884
3885 /**
3886 * Check tax amount.
3887 *
3888 * @param array $params
3889 * @param bool $isLineItem
3890 *
3891 * @return mixed
3892 */
3893 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3894 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
3895
3896 // Update contribution.
3897 if (!empty($params['id'])) {
3898 $id = $params['id'];
3899 $values = $ids = array();
3900 $contrbutionParams = array('id' => $id);
3901 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
3902
3903 // To assign pervious finantial type on update of contribution
3904 if (!isset($params['financial_type_id'])) {
3905 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
3906 }
3907 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3908 // Assisn tax Amount on update of contrbution
3909 if (!empty($prevContributionValue->tax_amount)) {
3910 $params['tax_amount'] = 'null';
3911 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3912 foreach ($params['line_item'] as $setID => $priceField) {
3913 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3914 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3915 }
3916 }
3917 }
3918 }
3919 }
3920
3921 // New Contrbution and update of contribution with tax rate financial type
3922 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3923 empty($params['skipLineItem']) && !$isLineItem
3924 ) {
3925 $taxRateParams = $taxRates[$params['financial_type_id']];
3926 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
3927 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3928
3929 // Get Line Item on update of contribution
3930 if (isset($params['id'])) {
3931 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3932 }
3933 else {
3934 CRM_Price_BAO_LineItem::getLineItemArray($params);
3935 }
3936 foreach ($params['line_item'] as $setID => $priceField) {
3937 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3938 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3939 }
3940 }
3941 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3942 }
3943 elseif (isset($params['api.line_item.create'])) {
3944 // Update total amount of contribution using lineItem
3945 $taxAmountArray = array();
3946 foreach ($params['api.line_item.create'] as $key => $value) {
3947 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3948 $taxRate = $taxRates[$value['financial_type_id']];
3949 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
3950 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3951 }
3952 }
3953 $params['tax_amount'] = array_sum($taxAmountArray);
3954 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3955 }
3956 else {
3957 // update line item of contrbution
3958 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3959 $taxRate = $taxRates[$params['financial_type_id']];
3960 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
3961 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3962 }
3963 }
3964 return $params;
3965 }
3966
3967 /**
3968 * Check financial type validation on update of a contribution.
3969 *
3970 * @param Integer $financialTypeId
3971 * Value of latest Financial Type.
3972 *
3973 * @param Integer $contributionId
3974 * Contribution Id.
3975 *
3976 * @param array $errors
3977 * List of errors.
3978 *
3979 * @return bool
3980 */
3981 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3982 if (!empty($financialTypeId)) {
3983 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3984 if ($oldFinancialTypeId == $financialTypeId) {
3985 return FALSE;
3986 }
3987 }
3988 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3989 $params = array(
3990 '1' => array($contributionId, 'Integer'),
3991 );
3992 $result = CRM_Core_DAO::executeQuery($sql, $params);
3993 if ($result->N > 1) {
3994 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
3995 }
3996 }
3997
3998 /**
3999 * Update related pledge payment payments.
4000 *
4001 * This function has been refactored out of the back office contribution form and may
4002 * still overlap with other functions.
4003 *
4004 * @param string $action
4005 * @param int $pledgePaymentID
4006 * @param int $contributionID
4007 * @param bool $adjustTotalAmount
4008 * @param float $total_amount
4009 * @param float $original_total_amount
4010 * @param int $contribution_status_id
4011 * @param int $original_contribution_status_id
4012 */
4013 public static function updateRelatedPledge(
4014 $action,
4015 $pledgePaymentID,
4016 $contributionID,
4017 $adjustTotalAmount,
4018 $total_amount,
4019 $original_total_amount,
4020 $contribution_status_id,
4021 $original_contribution_status_id
4022 ) {
4023 if (!$pledgePaymentID || $action & CRM_Core_Action::ADD && !$contributionID) {
4024 return;
4025 }
4026
4027 if ($pledgePaymentID) {
4028 //store contribution id in payment record.
4029 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4030 }
4031 else {
4032 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4033 $contributionID,
4034 'id',
4035 'contribution_id'
4036 );
4037 }
4038 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4039 $contributionID,
4040 'pledge_id',
4041 'contribution_id'
4042 );
4043
4044 $updatePledgePaymentStatus = FALSE;
4045
4046 // If either the status or the amount has changed we update the pledge status.
4047 if ($action & CRM_Core_Action::ADD) {
4048 $updatePledgePaymentStatus = TRUE;
4049 }
4050 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4051 ($original_total_amount != $total_amount))
4052 ) {
4053 $updatePledgePaymentStatus = TRUE;
4054 }
4055
4056 if ($updatePledgePaymentStatus) {
4057 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
4058 array($pledgePaymentID),
4059 $contribution_status_id,
4060 NULL,
4061 $total_amount,
4062 $adjustTotalAmount
4063 );
4064 }
4065 }
4066
4067 /**
4068 * Compute the stats values
4069 *
4070 * @param $stat either 'mode' or 'median'
4071 * @param $sql
4072 * @param $alias of civicrm_contribution
4073 */
4074 public static function computeStats($stat, $sql, $alias = NULL) {
4075 $mode = $median = array();
4076 switch ($stat) {
4077 case 'mode':
4078 $modeDAO = CRM_Core_DAO::executeQuery($sql);
4079 while ($modeDAO->fetch()) {
4080 if ($modeDAO->civicrm_contribution_total_amount_count > 1) {
4081 $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency);
4082 }
4083 else {
4084 $mode[] = 'N/A';
4085 }
4086 }
4087 return $mode;
4088
4089 case 'median':
4090 $currencies = CRM_Core_OptionGroup::values('currencies_enabled');
4091 foreach ($currencies as $currency => $val) {
4092 $midValue = 0;
4093 $where = "AND {$alias}.currency = '{$currency}'";
4094 $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4095
4096 $even = FALSE;
4097 $offset = 1;
4098 $medianRow = floor($rowCount / 2);
4099 if ($rowCount % 2 == 0 && !empty($medianRow)) {
4100 $even = TRUE;
4101 $offset++;
4102 $medianRow--;
4103 }
4104
4105 $medianValue = "SELECT {$alias}.total_amount as median
4106 {$sql} {$where}
4107 ORDER BY median LIMIT {$medianRow},{$offset}";
4108 $medianValDAO = CRM_Core_DAO::executeQuery($medianValue);
4109 while ($medianValDAO->fetch()) {
4110 if ($even) {
4111 $midValue = $midValue + $medianValDAO->median;
4112 }
4113 else {
4114 $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency);
4115 }
4116 }
4117 if ($even) {
4118 $midValue = $midValue / 2;
4119 $median[] = CRM_Utils_Money::format($midValue, $currency);
4120 }
4121 }
4122 return $median;
4123
4124 default:
4125 return;
4126 }
4127 }
4128
4129 /**
4130 * Complete an order.
4131 *
4132 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4133 *
4134 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4135 *
4136 * Moving it out of the BaseIPN class is just the first step.
4137 *
4138 * @param array $input
4139 * @param array $ids
4140 * @param array $objects
4141 * @param CRM_Core_Transaction $transaction
4142 * @param int $recur
4143 * @param CRM_Contribute_BAO_Contribution $contribution
4144 * @param bool $isRecurring
4145 * Duplication of param needs review. Only used by AuthorizeNetIPN
4146 * @param int $isFirstOrLastRecurringPayment
4147 * Deprecated param only used by AuthorizeNetIPN.
4148 */
4149 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4150 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
4151 // The previous details are used when calculating line items so keep it before any code that 'does something'
4152 if (!empty($contribution->id)) {
4153 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id),
4154 CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
4155 }
4156 $inputContributionWhiteList = array(
4157 'fee_amount',
4158 'net_amount',
4159 'trxn_id',
4160 'check_number',
4161 'payment_instrument_id',
4162 'is_test',
4163 'campaign_id',
4164 'receive_date',
4165 );
4166
4167 $contributionParams = array_merge(array(
4168 'contribution_status_id' => 'Completed',
4169 'financial_type_id' => $contribution->financial_type_id,
4170 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4171 ));
4172
4173 $participant = CRM_Utils_Array::value('participant', $objects);
4174 $memberships = CRM_Utils_Array::value('membership', $objects);
4175 $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
4176 if (!empty($recurContrib->id)) {
4177 $contributionParams['contribution_recur_id'] = $recurContrib->id;
4178 }
4179 self::repeatTransaction($contribution, $input, $contributionParams);
4180
4181 if (is_numeric($memberships)) {
4182 $memberships = array($objects['membership']);
4183 }
4184
4185 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4186
4187 $values = array();
4188 if (isset($input['is_email_receipt'])) {
4189 $values['is_email_receipt'] = $input['is_email_receipt'];
4190 }
4191
4192 if ($input['component'] == 'contribute') {
4193 if ($contribution->contribution_page_id) {
4194 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
4195 $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
4196 }
4197 elseif ($recurContrib && $recurContrib->id) {
4198 $contributionParams['contribution_page_id'] = NULL;
4199 $values['amount'] = $recurContrib->amount;
4200 $values['financial_type_id'] = $objects['contributionType']->id;
4201 $values['title'] = $source = ts('Offline Recurring Contribution');
4202 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
4203 $values['receipt_from_name'] = $domainValues[0];
4204 $values['receipt_from_email'] = $domainValues[1];
4205 }
4206
4207 if (empty($contributionParams['receive_date']) && $changeDate) {
4208 $contributionParams['receive_date'] = $changeDate;
4209 }
4210
4211 if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
4212 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4213 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4214 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
4215 }
4216
4217 if (!empty($values['is_email_receipt'])) {
4218 $contributionParams['receipt_date'] = $changeDate;
4219 }
4220
4221 if (!empty($memberships)) {
4222 foreach ($memberships as $membershipTypeIdKey => $membership) {
4223 if ($membership) {
4224 $membershipParams = array(
4225 'id' => $membership->id,
4226 'contact_id' => $membership->contact_id,
4227 'is_test' => $membership->is_test,
4228 'membership_type_id' => $membership->membership_type_id,
4229 );
4230
4231 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
4232 $membershipParams['membership_type_id'],
4233 $membershipParams['is_test'],
4234 $membershipParams['id']
4235 );
4236
4237 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4238 // this picks up membership type changes during renewals
4239 $sql = "
4240 SELECT membership_type_id
4241 FROM civicrm_membership_log
4242 WHERE membership_id={$membershipParams['id']}
4243 ORDER BY id DESC
4244 LIMIT 1;";
4245 $dao = CRM_Core_DAO::executeQuery($sql);
4246 if ($dao->fetch()) {
4247 if (!empty($dao->membership_type_id)) {
4248 $membershipParams['membership_type_id'] = $dao->membership_type_id;
4249 }
4250 }
4251 $dao->free();
4252
4253 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4254 $membershipParams['membership_type_id'],
4255 $primaryContributionID
4256 );
4257 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4258 if ($currentMembership) {
4259 /*
4260 * Fixed FOR CRM-4433
4261 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4262 * when Contribution mode is notify and membership is for renewal )
4263 */
4264 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4265
4266 // @todo - we should pass membership_type_id instead of null here but not
4267 // adding as not sure of testing
4268 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
4269 $changeDate, NULL, $membershipParams['num_terms']
4270 );
4271
4272 $dates['join_date'] = $currentMembership['join_date'];
4273 }
4274
4275 //get the status for membership.
4276 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
4277 $dates['end_date'],
4278 $dates['join_date'],
4279 'today',
4280 TRUE,
4281 $membershipParams['membership_type_id'],
4282 $membershipParams
4283 );
4284
4285 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
4286 //we might be renewing membership,
4287 //so make status override false.
4288 $membershipParams['is_override'] = FALSE;
4289 civicrm_api3('Membership', 'create', $membershipParams);
4290
4291 //update related Memberships.
4292 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
4293 }
4294 }
4295 }
4296 }
4297 else {
4298 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4299 $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id));
4300 $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
4301 if ($eventDetail['is_email_confirm']) {
4302 // @todo this should be set by the function that sends the mail after sending.
4303 $contributionParams['receipt_date'] = $changeDate;
4304 }
4305 $participantParams['id'] = $participant->id;
4306 $participantParams['status_id'] = 'Registered';
4307 civicrm_api3('Participant', 'create', $participantParams);
4308 }
4309 }
4310
4311 $contributionParams['id'] = $contribution->id;
4312
4313 civicrm_api3('Contribution', 'create', $contributionParams);
4314
4315 // Add new soft credit against current $contribution.
4316 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
4317 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
4318 }
4319
4320 $paymentProcessorId = '';
4321 if (isset($objects['paymentProcessor'])) {
4322 if (is_array($objects['paymentProcessor'])) {
4323 $paymentProcessorId = $objects['paymentProcessor']['id'];
4324 }
4325 else {
4326 $paymentProcessorId = $objects['paymentProcessor']->id;
4327 }
4328 }
4329
4330 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4331 'labelColumn' => 'name',
4332 'flip' => 1,
4333 ));
4334 if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
4335 $input['payment_processor'] = $paymentProcessorId;
4336 }
4337 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4338 $input['total_amount'] = $input['amount'];
4339 $input['contribution'] = $contribution;
4340 $input['financial_type_id'] = $contribution->financial_type_id;
4341
4342 if (!empty($contribution->_relatedObjects['participant'])) {
4343 $input['contribution_mode'] = 'participant';
4344 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
4345 $input['skipLineItem'] = 1;
4346 }
4347 elseif (!empty($contribution->_relatedObjects['membership'])) {
4348 $input['skipLineItem'] = TRUE;
4349 $input['contribution_mode'] = 'membership';
4350 }
4351 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4352 // and subsequent payments. In this case the line items are created at
4353 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4354 // and since the contribution is saved prior to this line there is always a contribution-id,
4355 // however there is never a prevContribution (which appears to mean original contribution not previous
4356 // contribution - or preUpdateContributionObject most accurately)
4357 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4358 // to mean "are we updating an exisitng pending contribution"
4359 //I was able to make the unit test complete as fataling here doesn't prevent
4360 // the contribution being created - but activities would not be created or emails sent
4361
4362 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
4363
4364 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
4365 $transaction->commit();
4366
4367 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
4368
4369 // create an activity record
4370 if ($input['component'] == 'contribute') {
4371 //CRM-4027
4372 $targetContactID = NULL;
4373 if (!empty($ids['related_contact'])) {
4374 $targetContactID = $contribution->contact_id;
4375 $contribution->contact_id = $ids['related_contact'];
4376 }
4377 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
4378 // event
4379 }
4380 else {
4381 CRM_Activity_BAO_Activity::addActivity($participant);
4382 }
4383
4384 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4385 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4386 if (!array_key_exists('is_email_receipt', $values) ||
4387 $values['is_email_receipt'] == 1
4388 ) {
4389 self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4390 CRM_Core_Error::debug_log_message("Receipt sent");
4391 }
4392
4393 CRM_Core_Error::debug_log_message("Success: Database updated");
4394 if ($isRecurring) {
4395 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
4396 $isFirstOrLastRecurringPayment);
4397 }
4398 }
4399
4400 /**
4401 * Send receipt from contribution.
4402 *
4403 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4404 *
4405 * Note that the compose message part has been moved to contribution
4406 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4407 *
4408 * @param array $input
4409 * Incoming data from Payment processor.
4410 * @param array $ids
4411 * Related object IDs.
4412 * @param CRM_Contribute_BAO_Contribution $contribution
4413 * @param array $values
4414 * Values related to objects that have already been loaded.
4415 * @param bool $recur
4416 * Is it part of a recurring contribution.
4417 * @param bool $returnMessageText
4418 * Should text be returned instead of sent. This.
4419 * is because the function is also used to generate pdfs
4420 *
4421 * @return array
4422 */
4423 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4424 $input['is_recur'] = $recur;
4425 // set receipt from e-mail and name in value
4426 if (!$returnMessageText) {
4427 $session = CRM_Core_Session::singleton();
4428 $userID = $session->get('userID');
4429 if (!empty($userID)) {
4430 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
4431 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail);
4432 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName);
4433 }
4434 }
4435 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4436 }
4437
4438 /**
4439 * Generate credit note id with next avaible number
4440 *
4441 * @return string
4442 * Credit Note Id.
4443 */
4444 public static function createCreditNoteId() {
4445 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
4446
4447 $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4448 $creditNoteId = NULL;
4449
4450 do {
4451 $creditNoteNum++;
4452 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4453 $result = civicrm_api3('Contribution', 'getcount', array(
4454 'sequential' => 1,
4455 'creditnote_id' => $creditNoteId,
4456 ));
4457 } while ($result > 0);
4458
4459 return $creditNoteId;
4460 }
4461
4462 }