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