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