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