Merge pull request #6414 from eileenmcnaughton/CRM-16967
[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 * @deprecated
1485 *
1486 * Use api contribute.completetransaction
1487 * For failures use failPayment (preferably exposing by api in the process).
1488 *
1489 * @param array $params
1490 * @param bool $processContributionObject
1491 *
1492 * @return array
1493 * @throws \Exception
1494 */
1495 public static function transitionComponents($params, $processContributionObject = FALSE) {
1496 // get minimum required values.
1497 $contactId = CRM_Utils_Array::value('contact_id', $params);
1498 $componentId = CRM_Utils_Array::value('component_id', $params);
1499 $componentName = CRM_Utils_Array::value('componentName', $params);
1500 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1501 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1502
1503 // if we already processed contribution object pass previous status id.
1504 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1505
1506 $updateResult = array();
1507
1508 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1509
1510 // we process only ( Completed, Cancelled, or Failed ) contributions.
1511 if (!$contributionId ||
1512 !in_array($contributionStatusId, array(
1513 array_search('Completed', $contributionStatuses),
1514 array_search('Cancelled', $contributionStatuses),
1515 array_search('Failed', $contributionStatuses),
1516 ))
1517 ) {
1518 return $updateResult;
1519 }
1520
1521 if (!$componentName || !$componentId) {
1522 // get the related component details.
1523 $componentDetails = self::getComponentDetails($contributionId);
1524 }
1525 else {
1526 $componentDetails['contact_id'] = $contactId;
1527 $componentDetails['component'] = $componentName;
1528
1529 if ($componentName == 'event') {
1530 $componentDetails['participant'] = $componentId;
1531 }
1532 else {
1533 $componentDetails['membership'] = $componentId;
1534 }
1535 }
1536
1537 if (!empty($componentDetails['contact_id'])) {
1538 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1539 $contributionId,
1540 'contact_id'
1541 );
1542 }
1543
1544 // do check for required ids.
1545 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1546 return $updateResult;
1547 }
1548
1549 //now we are ready w/ required ids, start processing.
1550
1551 $baseIPN = new CRM_Core_Payment_BaseIPN();
1552
1553 $input = $ids = $objects = array();
1554
1555 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1556 $ids['contribution'] = $contributionId;
1557 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1558 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1559 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1560 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1561 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1562 $ids['contributionRecur'] = NULL;
1563 $ids['contributionPage'] = NULL;
1564
1565 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1566 CRM_Core_Error::fatal();
1567 }
1568
1569 $memberships = &$objects['membership'];
1570 $participant = &$objects['participant'];
1571 $pledgePayment = &$objects['pledge_payment'];
1572 $contribution = &$objects['contribution'];
1573
1574 if ($pledgePayment) {
1575 $pledgePaymentIDs = array();
1576 foreach ($pledgePayment as $key => $object) {
1577 $pledgePaymentIDs[] = $object->id;
1578 }
1579 $pledgeID = $pledgePayment[0]->pledge_id;
1580 }
1581
1582 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1583
1584 if ($participant) {
1585 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1586 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1587 $participant->id,
1588 'status_id'
1589 );
1590 }
1591 // we might want to process contribution object.
1592 $processContribution = FALSE;
1593 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1594 if (is_array($memberships)) {
1595 foreach ($memberships as $membership) {
1596 if ($membership) {
1597 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1598 $membership->save();
1599
1600 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1601 if ($processContributionObject) {
1602 $processContribution = TRUE;
1603 }
1604 }
1605 }
1606 }
1607
1608 if ($participant) {
1609 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1610 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1611
1612 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1613 if ($processContributionObject) {
1614 $processContribution = TRUE;
1615 }
1616 }
1617
1618 if ($pledgePayment) {
1619 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1620
1621 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1622 if ($processContributionObject) {
1623 $processContribution = TRUE;
1624 }
1625 }
1626 }
1627 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1628 if (is_array($memberships)) {
1629 foreach ($memberships as $membership) {
1630 if ($membership) {
1631 $membership->status_id = array_search('Expired', $membershipStatuses);
1632 $membership->save();
1633
1634 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1635 if ($processContributionObject) {
1636 $processContribution = TRUE;
1637 }
1638 }
1639 }
1640 }
1641 if ($participant) {
1642 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1643 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1644
1645 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1646 if ($processContributionObject) {
1647 $processContribution = TRUE;
1648 }
1649 }
1650
1651 if ($pledgePayment) {
1652 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1653
1654 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1655 if ($processContributionObject) {
1656 $processContribution = TRUE;
1657 }
1658 }
1659 }
1660 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1661
1662 // only pending contribution related object processed.
1663 if ($previousContriStatusId &&
1664 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1665 ) {
1666 // this is case when we already processed contribution object.
1667 return $updateResult;
1668 }
1669 elseif (!$previousContriStatusId &&
1670 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1671 ) {
1672 // this is case when we are going to process contribution object later.
1673 return $updateResult;
1674 }
1675
1676 if (is_array($memberships)) {
1677 foreach ($memberships as $membership) {
1678 if ($membership) {
1679 $format = '%Y%m%d';
1680
1681 //CRM-4523
1682 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1683 $membership->membership_type_id,
1684 $membership->is_test, $membership->id
1685 );
1686
1687 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1688 // this picks up membership type changes during renewals
1689 $sql = "
1690 SELECT membership_type_id
1691 FROM civicrm_membership_log
1692 WHERE membership_id=$membership->id
1693 ORDER BY id DESC
1694 LIMIT 1;";
1695 $dao = new CRM_Core_DAO();
1696 $dao->query($sql);
1697 if ($dao->fetch()) {
1698 if (!empty($dao->membership_type_id)) {
1699 $membership->membership_type_id = $dao->membership_type_id;
1700 $membership->save();
1701 }
1702 }
1703 // else fall back to using current membership type
1704 $dao->free();
1705
1706 // Figure out number of terms
1707 $numterms = 1;
1708 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1709 foreach ($lineitems as $lineitem) {
1710 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1711 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1712
1713 // in case membership_num_terms comes through as null or zero
1714 $numterms = $numterms >= 1 ? $numterms : 1;
1715 break;
1716 }
1717 }
1718
1719 // CRM-15735-to update the membership status as per the contribution receive date
1720 $joinDate = NULL;
1721 if (!empty($params['receive_date'])) {
1722 $joinDate = $params['receive_date'];
1723 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1724 $membership->end_date,
1725 $membership->join_date,
1726 $params['receive_date'],
1727 FALSE,
1728 $membership->membership_type_id,
1729 (array) $membership
1730 );
1731 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1732 $membership->save();
1733 }
1734
1735 if ($currentMembership) {
1736 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1737 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1738 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1739 }
1740 else {
1741 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
1742 }
1743
1744 //get the status for membership.
1745 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1746 $dates['end_date'],
1747 $dates['join_date'],
1748 'today',
1749 TRUE,
1750 $membership->membership_type_id,
1751 (array) $membership
1752 );
1753
1754 $formattedParams = array(
1755 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1756 array_search('Current', $membershipStatuses)
1757 ),
1758 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1759 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1760 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1761 );
1762
1763 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1764
1765 $membership->copyValues($formattedParams);
1766 $membership->save();
1767
1768 //updating the membership log
1769 $membershipLog = array();
1770 $membershipLog = $formattedParams;
1771 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1772 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1773
1774 $membershipLog['start_date'] = $logStartDate;
1775 $membershipLog['membership_id'] = $membership->id;
1776 $membershipLog['modified_id'] = $membership->contact_id;
1777 $membershipLog['modified_date'] = date('Ymd');
1778 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1779
1780 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1781
1782 //update related Memberships.
1783 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1784
1785 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1786 '%B %E%f, %Y'
1787 );
1788 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1789 if ($processContributionObject) {
1790 $processContribution = TRUE;
1791 }
1792
1793 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1794 }
1795 }
1796 }
1797
1798 if ($participant) {
1799 $updatedStatusId = array_search('Registered', $participantStatuses);
1800 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1801
1802 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1803 if ($processContributionObject) {
1804 $processContribution = TRUE;
1805 }
1806 }
1807
1808 if ($pledgePayment) {
1809 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1810
1811 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1812 if ($processContributionObject) {
1813 $processContribution = TRUE;
1814 }
1815 }
1816 }
1817
1818 // process contribution object.
1819 if ($processContribution) {
1820 $contributionParams = array();
1821 $fields = array(
1822 'contact_id',
1823 'total_amount',
1824 'receive_date',
1825 'is_test',
1826 'campaign_id',
1827 'payment_instrument_id',
1828 'trxn_id',
1829 'invoice_id',
1830 'financial_type_id',
1831 'contribution_status_id',
1832 'non_deductible_amount',
1833 'receipt_date',
1834 'check_number',
1835 );
1836 foreach ($fields as $field) {
1837 if (empty($params[$field])) {
1838 continue;
1839 }
1840 $contributionParams[$field] = $params[$field];
1841 }
1842
1843 $ids = array('contribution' => $contributionId);
1844 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1845 }
1846
1847 return $updateResult;
1848 }
1849
1850 /**
1851 * Returns all contribution related object ids.
1852 *
1853 * @param $contributionId
1854 *
1855 * @return array
1856 */
1857 public static function getComponentDetails($contributionId) {
1858 $componentDetails = $pledgePayment = array();
1859 if (!$contributionId) {
1860 return $componentDetails;
1861 }
1862
1863 $query = "
1864 SELECT c.id as contribution_id,
1865 c.contact_id as contact_id,
1866 c.contribution_recur_id,
1867 mp.membership_id as membership_id,
1868 m.membership_type_id as membership_type_id,
1869 pp.participant_id as participant_id,
1870 p.event_id as event_id,
1871 pgp.id as pledge_payment_id
1872 FROM civicrm_contribution c
1873 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1874 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1875 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1876 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1877 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1878 WHERE c.id = $contributionId";
1879
1880 $dao = CRM_Core_DAO::executeQuery($query);
1881 $componentDetails = array();
1882
1883 while ($dao->fetch()) {
1884 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1885 $componentDetails['contact_id'] = $dao->contact_id;
1886 if ($dao->event_id) {
1887 $componentDetails['event'] = $dao->event_id;
1888 }
1889 if ($dao->participant_id) {
1890 $componentDetails['participant'] = $dao->participant_id;
1891 }
1892 if ($dao->membership_id) {
1893 if (!isset($componentDetails['membership'])) {
1894 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1895 }
1896 $componentDetails['membership'][] = $dao->membership_id;
1897 $componentDetails['membership_type'][] = $dao->membership_type_id;
1898 }
1899 if ($dao->pledge_payment_id) {
1900 $pledgePayment[] = $dao->pledge_payment_id;
1901 }
1902 if ($dao->contribution_recur_id) {
1903 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
1904 }
1905 }
1906
1907 if ($pledgePayment) {
1908 $componentDetails['pledge_payment'] = $pledgePayment;
1909 }
1910
1911 return $componentDetails;
1912 }
1913
1914 /**
1915 * @param int $contactId
1916 * @param bool $includeSoftCredit
1917 *
1918 * @return null|string
1919 */
1920 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1921 if (!$contactId) {
1922 return 0;
1923 }
1924
1925 $contactContributionsSQL = "
1926 SELECT contribution.id AS id
1927 FROM civicrm_contribution contribution
1928 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1929
1930 $contactSoftCreditContributionsSQL = "
1931 SELECT contribution.id
1932 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1933 ON ( contribution.id = softContribution.contribution_id )
1934 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1935 $query = "SELECT count( x.id ) count FROM ( ";
1936 $query .= $contactContributionsSQL;
1937
1938 if ($includeSoftCredit) {
1939 $query .= " UNION ";
1940 $query .= $contactSoftCreditContributionsSQL;
1941 }
1942
1943 $query .= ") x";
1944
1945 return CRM_Core_DAO::singleValueQuery($query);
1946 }
1947
1948 /**
1949 * Get individual id for onbehalf contribution.
1950 *
1951 * @param int $contributionId
1952 * Contribution id.
1953 * @param int $contributorId
1954 * Contributor id.
1955 *
1956 * @return array
1957 * containing organization id and individual id
1958 */
1959 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1960
1961 $ids = array();
1962
1963 if (!$contributionId) {
1964 return $ids;
1965 }
1966
1967 // fetch contributor id if null
1968 if (!$contributorId) {
1969 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1970 $contributionId, 'contact_id'
1971 );
1972 }
1973
1974 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1975 $activityTypeId = array_search('Contribution', $activityTypeIds);
1976
1977 if ($activityTypeId && $contributorId) {
1978 $activityQuery = "
1979 SELECT civicrm_activity_contact.contact_id
1980 FROM civicrm_activity_contact
1981 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1982 WHERE civicrm_activity.activity_type_id = %1
1983 AND civicrm_activity.source_record_id = %2
1984 AND civicrm_activity_contact.record_type_id = %3
1985 ";
1986
1987 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1988 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1989
1990 $params = array(
1991 1 => array($activityTypeId, 'Integer'),
1992 2 => array($contributionId, 'Integer'),
1993 3 => array($sourceID, 'Integer'),
1994 );
1995
1996 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1997
1998 // for on behalf contribution source is individual and contributor is organization
1999 if ($sourceContactId && $sourceContactId != $contributorId) {
2000 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2001 // get rel type id for employee of relation
2002 foreach ($relationshipTypeIds as $id => $typeVals) {
2003 if ($typeVals['name_a_b'] == 'Employee of') {
2004 $relationshipTypeId = $id;
2005 break;
2006 }
2007 }
2008
2009 $rel = new CRM_Contact_DAO_Relationship();
2010 $rel->relationship_type_id = $relationshipTypeId;
2011 $rel->contact_id_a = $sourceContactId;
2012 $rel->contact_id_b = $contributorId;
2013 if ($rel->find(TRUE)) {
2014 $ids['individual_id'] = $rel->contact_id_a;
2015 $ids['organization_id'] = $rel->contact_id_b;
2016 }
2017 }
2018 }
2019
2020 return $ids;
2021 }
2022
2023 /**
2024 * @return array
2025 */
2026 public static function getContributionDates() {
2027 $config = CRM_Core_Config::singleton();
2028 $currentMonth = date('m');
2029 $currentDay = date('d');
2030 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2031 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2032 (int ) $config->fiscalYearStart['d'] > $currentDay
2033 )
2034 ) {
2035 $year = date('Y') - 1;
2036 }
2037 else {
2038 $year = date('Y');
2039 }
2040 $year = array('Y' => $year);
2041 $yearDate = $config->fiscalYearStart;
2042 $yearDate = array_merge($year, $yearDate);
2043 $yearDate = CRM_Utils_Date::format($yearDate);
2044
2045 $monthDate = date('Ym') . '01';
2046
2047 $now = date('Ymd');
2048
2049 return array(
2050 'now' => $now,
2051 'yearDate' => $yearDate,
2052 'monthDate' => $monthDate,
2053 );
2054 }
2055
2056 /**
2057 * Load objects relations to contribution object.
2058 * Objects are stored in the $_relatedObjects property
2059 * In the first instance we are just moving functionality from BASEIpn -
2060 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2061 *
2062 * Note that the unit test for the BaseIPN class tests this function
2063 *
2064 * @param array $input
2065 * Input as delivered from Payment Processor.
2066 * @param array $ids
2067 * Ids as Loaded by Payment Processor.
2068 * @param bool $loadAll
2069 * Load all related objects - even where id not passed in? (allows API to call this).
2070 *
2071 * @return bool
2072 * @throws Exception
2073 */
2074 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2075 if ($loadAll) {
2076 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2077 if (empty($ids['contact']) && isset($this->contact_id)) {
2078 $ids['contact'] = $this->contact_id;
2079 }
2080 }
2081 if (empty($this->_component)) {
2082 if (!empty($ids['event'])) {
2083 $this->_component = 'event';
2084 }
2085 else {
2086 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2087 }
2088 }
2089
2090 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2091 // refactoring than anything else, and has unit test coverage.
2092 if (empty($this->financial_type_id)) {
2093 $this->find(TRUE);
2094 }
2095
2096 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2097 'paymentProcessor',
2098 $ids
2099 ));
2100
2101 if (!$paymentProcessorID && $this->contribution_page_id) {
2102 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2103 $this->contribution_page_id,
2104 'payment_processor'
2105 );
2106 if ($paymentProcessorID) {
2107 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2108 }
2109 }
2110
2111 $ids['contributionType'] = $this->financial_type_id;
2112 $ids['financialType'] = $this->financial_type_id;
2113
2114 $entities = array(
2115 'contact' => 'CRM_Contact_BAO_Contact',
2116 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2117 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2118 'financialType' => 'CRM_Financial_BAO_FinancialType',
2119 );
2120 foreach ($entities as $entity => $bao) {
2121 if (!empty($ids[$entity])) {
2122 $this->_relatedObjects[$entity] = new $bao();
2123 $this->_relatedObjects[$entity]->id = $ids[$entity];
2124 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
2125 throw new CRM_Core_Exception($entity . ' could not be loaded');
2126 }
2127 }
2128 }
2129
2130 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2131 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
2132 }
2133
2134 if (!empty($ids['pledge_payment'])) {
2135 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2136 if (empty($paymentID)) {
2137 continue;
2138 }
2139 $payment = new CRM_Pledge_BAO_PledgePayment();
2140 $payment->id = $paymentID;
2141 if (!$payment->find(TRUE)) {
2142 throw new Exception("Could not find pledge payment record: " . $paymentID);
2143 }
2144 $this->_relatedObjects['pledge_payment'][] = $payment;
2145 }
2146 }
2147
2148 if ($this->_component == 'contribute') {
2149 // retrieve the other optional objects first so
2150 // stuff down the line can use this info and do things
2151 // CRM-6056
2152 //in any case get the memberships associated with the contribution
2153 //because we now support multiple memberships w/ price set
2154 // see if there are any other memberships to be considered for same contribution.
2155 $query = "
2156 SELECT membership_id
2157 FROM civicrm_membership_payment
2158 WHERE contribution_id = %1 ";
2159 $params = array(1 => array($this->id, 'Integer'));
2160
2161 $dao = CRM_Core_DAO::executeQuery($query, $params);
2162 while ($dao->fetch()) {
2163 if ($dao->membership_id) {
2164 if (!is_array($ids['membership'])) {
2165 $ids['membership'] = array();
2166 }
2167 $ids['membership'][] = $dao->membership_id;
2168 }
2169 }
2170
2171 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2172 foreach ($ids['membership'] as $id) {
2173 if (!empty($id)) {
2174 $membership = new CRM_Member_BAO_Membership();
2175 $membership->id = $id;
2176 if (!$membership->find(TRUE)) {
2177 throw new Exception("Could not find membership record: $id");
2178 }
2179 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2180 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2181 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2182 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2183 $membership->free();
2184 }
2185 }
2186 }
2187 }
2188 else {
2189 // we are in event mode
2190 // make sure event exists and is valid
2191 $event = new CRM_Event_BAO_Event();
2192 $event->id = $ids['event'];
2193 if ($ids['event'] &&
2194 !$event->find(TRUE)
2195 ) {
2196 throw new Exception("Could not find event: " . $ids['event']);
2197 }
2198
2199 $this->_relatedObjects['event'] = &$event;
2200
2201 $participant = new CRM_Event_BAO_Participant();
2202 $participant->id = $ids['participant'];
2203 if ($ids['participant'] &&
2204 !$participant->find(TRUE)
2205 ) {
2206 throw new Exception("Could not find participant: " . $ids['participant']);
2207 }
2208 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2209
2210 $this->_relatedObjects['participant'] = &$participant;
2211
2212 // get the payment processor id from event - this is inaccurate see CRM-16923
2213 // in future we should look at throwing an exception here rather than an dubious guess.
2214 if (!$paymentProcessorID) {
2215 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2216 if ($paymentProcessorID) {
2217 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2218 }
2219 }
2220 }
2221
2222 if ($paymentProcessorID) {
2223 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2224 $this->is_test ? 'test' : 'live'
2225 );
2226 $ids['paymentProcessor'] = $paymentProcessorID;
2227 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
2228 }
2229 return TRUE;
2230 }
2231
2232 /**
2233 * Create array of message information - ie. return html version, txt version, to field
2234 *
2235 * @param array $input
2236 * Incoming information.
2237 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2238 * just check presence of recur object but maintaining legacy approach
2239 * to be careful)
2240 * @param array $ids
2241 * IDs of related objects.
2242 * @param array $values
2243 * Any values that may have already been compiled by calling process.
2244 * This is augmented by values 'gathered' by gatherMessageValues
2245 * @param bool $recur
2246 * @param bool $returnMessageText
2247 * Distinguishes between whether to send message or return.
2248 * message text. We are working towards this function ALWAYS returning message text & calling
2249 * function doing emails / pdfs with it
2250 *
2251 * @return array
2252 * messages
2253 * @throws Exception
2254 */
2255 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2256 $this->loadRelatedObjects($input, $ids);
2257
2258 if (empty($this->_component)) {
2259 $this->_component = CRM_Utils_Array::value('component', $input);
2260 }
2261
2262 //not really sure what params might be passed in but lets merge em into values
2263 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2264 $template = CRM_Core_Smarty::singleton();
2265 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2266 //what does recur 'mean here - to do with payment processor return functionality but
2267 // what is the importance
2268 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2269 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
2270
2271 $entityID = $entity = NULL;
2272 if (isset($ids['contribution'])) {
2273 $entity = 'contribution';
2274 $entityID = $ids['contribution'];
2275 }
2276 if (!empty($ids['membership'])) {
2277 //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
2278 // 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
2279 // line having loaded an array
2280 $ids['membership'] = (array) $ids['membership'];
2281 $entity = 'membership';
2282 $entityID = $ids['membership'][0];
2283 }
2284
2285 $url = $paymentObject->subscriptionURL($entityID, $entity);
2286 $template->assign('cancelSubscriptionUrl', $url);
2287
2288 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2289 $template->assign('updateSubscriptionBillingUrl', $url);
2290
2291 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2292 $template->assign('updateSubscriptionUrl', $url);
2293
2294 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2295 //direct mode showing billing block, so use directIPN for temporary
2296 $template->assign('contributeMode', 'directIPN');
2297 }
2298 }
2299 // todo remove strtolower - check consistency
2300 if (strtolower($this->_component) == 'event') {
2301 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2302 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2303 );
2304 }
2305 else {
2306 $values['contribution_id'] = $this->id;
2307 if (!empty($ids['related_contact'])) {
2308 $values['related_contact'] = $ids['related_contact'];
2309 if (isset($ids['onbehalf_dupe_alert'])) {
2310 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2311 }
2312 $entityBlock = array(
2313 'contact_id' => $ids['contact'],
2314 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2315 'Home', 'id', 'name'
2316 ),
2317 );
2318 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2319 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2320 }
2321 $isTest = FALSE;
2322 if ($this->is_test) {
2323 $isTest = TRUE;
2324 }
2325 if (!empty($this->_relatedObjects['membership'])) {
2326 foreach ($this->_relatedObjects['membership'] as $membership) {
2327 if ($membership->id) {
2328 $values['isMembership'] = TRUE;
2329
2330 // need to set the membership values here
2331 $template->assign('membership_assign', 1);
2332 $template->assign('membership_name',
2333 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2334 );
2335 $template->assign('mem_start_date', $membership->start_date);
2336 $template->assign('mem_join_date', $membership->join_date);
2337 $template->assign('mem_end_date', $membership->end_date);
2338 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2339 $template->assign('mem_status', $membership_status);
2340 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2341 $template->assign('is_pay_later', 1);
2342 }
2343
2344 // if separate payment there are two contributions recorded and the
2345 // admin will need to send a receipt for each of them separately.
2346 // we dont link the two in the db (but can potentially infer it if needed)
2347 $template->assign('is_separate_payment', 0);
2348
2349 if ($recur && $paymentObject) {
2350 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2351 $template->assign('cancelSubscriptionUrl', $url);
2352 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2353 $template->assign('updateSubscriptionBillingUrl', $url);
2354 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2355 $template->assign('updateSubscriptionUrl', $url);
2356 }
2357
2358 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2359
2360 return $result;
2361 // otherwise if its about sending emails, continue sending without return, as we
2362 // don't want to exit the loop.
2363 }
2364 }
2365 }
2366 else {
2367 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2368 }
2369 }
2370 }
2371
2372 /**
2373 * Gather values for contribution mail - this function has been created
2374 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2375 * Values related to the contribution in question are gathered
2376 *
2377 * @param array $input
2378 * Input into function (probably from payment processor).
2379 * @param array $values
2380 * @param array $ids
2381 * The set of ids related to the input.
2382 *
2383 * @return array
2384 */
2385 public function _gatherMessageValues($input, &$values, $ids = array()) {
2386 // set display address of contributor
2387 if ($this->address_id) {
2388 $addressParams = array('id' => $this->address_id);
2389 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2390 $addressDetails = array_values($addressDetails);
2391 $values['address'] = $addressDetails[0]['display'];
2392 }
2393 if ($this->_component == 'contribute') {
2394 if (isset($this->contribution_page_id)) {
2395 CRM_Contribute_BAO_ContributionPage::setValues(
2396 $this->contribution_page_id,
2397 $values
2398 );
2399 if ($this->contribution_page_id) {
2400 // CRM-8254 - override default currency if applicable
2401 $config = CRM_Core_Config::singleton();
2402 $config->defaultCurrency = CRM_Utils_Array::value(
2403 'currency',
2404 $values,
2405 $config->defaultCurrency
2406 );
2407 }
2408 }
2409 // no contribution page -probably back office
2410 else {
2411 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2412 $values['is_email_receipt'] = 1;
2413 $values['title'] = 'Contribution';
2414 }
2415 // set lineItem for contribution
2416 if ($this->id) {
2417 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2418 if (!empty($lineItem)) {
2419 $itemId = key($lineItem);
2420 foreach ($lineItem as &$eachItem) {
2421 if (is_array($this->_relatedObjects['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2422 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2423 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2424 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2425 }
2426 }
2427 $values['lineItem'][0] = $lineItem;
2428 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2429 }
2430 }
2431
2432 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2433 $this->id,
2434 $this->contact_id
2435 );
2436 // if this is onbehalf of contribution then set related contact
2437 if (!empty($relatedContact['individual_id'])) {
2438 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2439 }
2440 }
2441 else {
2442 // event
2443 $eventParams = array(
2444 'id' => $this->_relatedObjects['event']->id,
2445 );
2446 $values['event'] = array();
2447
2448 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2449
2450 //get location details
2451 $locationParams = array(
2452 'entity_id' => $this->_relatedObjects['event']->id,
2453 'entity_table' => 'civicrm_event',
2454 );
2455 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2456
2457 $ufJoinParams = array(
2458 'entity_table' => 'civicrm_event',
2459 'entity_id' => $ids['event'],
2460 'module' => 'CiviEvent',
2461 );
2462
2463 list($custom_pre_id,
2464 $custom_post_ids
2465 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2466
2467 $values['custom_pre_id'] = $custom_pre_id;
2468 $values['custom_post_id'] = $custom_post_ids;
2469
2470 // set lineItem for event contribution
2471 if ($this->id) {
2472 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2473 if (!empty($participantIds)) {
2474 foreach ($participantIds as $pIDs) {
2475 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2476 if (!CRM_Utils_System::isNull($lineItem)) {
2477 $values['lineItem'][] = $lineItem;
2478 }
2479 }
2480 }
2481 }
2482 }
2483
2484 return $values;
2485 }
2486
2487 /**
2488 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2489 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2490 * Note we send directly from this function in some cases because it is only partly refactored
2491 * Don't call this function directly as the signature will change
2492 *
2493 * @param $values
2494 * @param $input
2495 * @param CRM_Core_SMARTY $template
2496 * @param bool $recur
2497 * @param bool $returnMessageText
2498 *
2499 * @return mixed
2500 */
2501 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2502 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2503 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2504 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2505 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2506 $template->assign('useForMember', TRUE);
2507 }
2508 //assign honor information to receipt message
2509 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2510
2511 if (isset($softRecord['soft_credit'])) {
2512 //if id of contribution page is present
2513 if (!empty($values['id'])) {
2514 $values['honor'] = array(
2515 'honor_profile_values' => array(),
2516 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2517 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2518 );
2519 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2520
2521 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2522 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2523 }
2524 else {
2525 //offline contribution
2526 $softCreditTypes = $softCredits = array();
2527 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2528 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2529 $softCredits[$key] = array(
2530 'Name' => $softCredit['contact_name'],
2531 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2532 );
2533 }
2534 $template->assign('softCreditTypes', $softCreditTypes);
2535 $template->assign('softCredits', $softCredits);
2536 }
2537 }
2538
2539 $dao = new CRM_Contribute_DAO_ContributionProduct();
2540 $dao->contribution_id = $this->id;
2541 if ($dao->find(TRUE)) {
2542 $premiumId = $dao->product_id;
2543 $template->assign('option', $dao->product_option);
2544
2545 $productDAO = new CRM_Contribute_DAO_Product();
2546 $productDAO->id = $premiumId;
2547 $productDAO->find(TRUE);
2548 $template->assign('selectPremium', TRUE);
2549 $template->assign('product_name', $productDAO->name);
2550 $template->assign('price', $productDAO->price);
2551 $template->assign('sku', $productDAO->sku);
2552 }
2553 $template->assign('title', CRM_Utils_Array::value('title', $values));
2554 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2555 if (empty($amount) && isset($this->total_amount)) {
2556 $amount = $this->total_amount;
2557 }
2558 $template->assign('amount', $amount);
2559 // add the new contribution values
2560 if (strtolower($this->_component) == 'contribute') {
2561 //PCP Info
2562 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2563 $softDAO->contribution_id = $this->id;
2564 if ($softDAO->find(TRUE)) {
2565 $template->assign('pcpBlock', TRUE);
2566 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2567 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2568 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2569
2570 //assign the pcp page title for email subject
2571 $pcpDAO = new CRM_PCP_DAO_PCP();
2572 $pcpDAO->id = $softDAO->pcp_id;
2573 if ($pcpDAO->find(TRUE)) {
2574 $template->assign('title', $pcpDAO->title);
2575 }
2576 }
2577 }
2578
2579 if ($this->financial_type_id) {
2580 $values['financial_type_id'] = $this->financial_type_id;
2581 }
2582
2583 $template->assign('trxn_id', $this->trxn_id);
2584 $template->assign('receive_date',
2585 CRM_Utils_Date::mysqlToIso($this->receive_date)
2586 );
2587 $template->assign('contributeMode', 'notify');
2588 $template->assign('action', $this->is_test ? 1024 : 1);
2589 $template->assign('receipt_text',
2590 CRM_Utils_Array::value('receipt_text',
2591 $values
2592 )
2593 );
2594 $template->assign('is_monetary', 1);
2595 $template->assign('is_recur', (bool) $recur);
2596 $template->assign('currency', $this->currency);
2597 $template->assign('address', CRM_Utils_Address::format($input));
2598 if ($this->_component == 'event') {
2599 $template->assign('title', $values['event']['title']);
2600 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2601 $viewRoles = array();
2602 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2603 $viewRoles[] = $participantRoles[$v];
2604 }
2605 $values['event']['participant_role'] = implode(', ', $viewRoles);
2606 $template->assign('event', $values['event']);
2607 $template->assign('location', $values['location']);
2608 $template->assign('customPre', $values['custom_pre_id']);
2609 $template->assign('customPost', $values['custom_post_id']);
2610
2611 $isTest = FALSE;
2612 if ($this->_relatedObjects['participant']->is_test) {
2613 $isTest = TRUE;
2614 }
2615
2616 $values['params'] = array();
2617 //to get email of primary participant.
2618 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2619 $primaryAmount[] = array(
2620 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2621 'amount' => $this->_relatedObjects['participant']->fee_amount,
2622 );
2623 //build an array of cId/pId of participants
2624 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2625 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2626 //send receipt to additional participant if exists
2627 if (count($additionalIDs)) {
2628 $template->assign('isPrimary', 0);
2629 $template->assign('customProfile', NULL);
2630 //set additionalParticipant true
2631 $values['params']['additionalParticipant'] = TRUE;
2632 foreach ($additionalIDs as $pId => $cId) {
2633 $amount = array();
2634 //to change the status pending to completed
2635 $additional = new CRM_Event_DAO_Participant();
2636 $additional->id = $pId;
2637 $additional->contact_id = $cId;
2638 $additional->find(TRUE);
2639 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2640 $additional->status_id = 1;
2641 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2642 //if additional participant dont have email
2643 //use display name.
2644 if (!$additionalParticipantInfo) {
2645 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2646 }
2647 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2648 $primaryAmount[] = array(
2649 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2650 'amount' => $additional->fee_amount,
2651 );
2652 $additional->save();
2653 $additional->free();
2654 $template->assign('amount', $amount);
2655 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2656 }
2657 }
2658
2659 //build an array of custom profile and assigning it to template
2660 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2661
2662 if (count($customProfile)) {
2663 $template->assign('customProfile', $customProfile);
2664 }
2665
2666 // for primary contact
2667 $values['params']['additionalParticipant'] = FALSE;
2668 $template->assign('isPrimary', 1);
2669 $template->assign('amount', $primaryAmount);
2670 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2671 if ($this->payment_instrument_id) {
2672 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2673 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2674 }
2675 // carry paylater, since we did not created billing,
2676 // so need to pull email from primary location, CRM-4395
2677 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2678 }
2679 return $template;
2680 }
2681
2682 /**
2683 * Check whether payment processor supports
2684 * cancellation of contribution subscription
2685 *
2686 * @param int $contributionId
2687 * Contribution id.
2688 *
2689 * @param bool $isNotCancelled
2690 *
2691 * @return bool
2692 */
2693 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2694 $cacheKeyString = "$contributionId";
2695 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2696
2697 static $supportsCancel = array();
2698
2699 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2700 $supportsCancel[$cacheKeyString] = FALSE;
2701 $isCancelled = FALSE;
2702
2703 if ($isNotCancelled) {
2704 $isCancelled = self::isSubscriptionCancelled($contributionId);
2705 }
2706
2707 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2708 if (!empty($paymentObject)) {
2709 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2710 }
2711 }
2712 return $supportsCancel[$cacheKeyString];
2713 }
2714
2715 /**
2716 * Check whether subscription is already cancelled.
2717 *
2718 * @param int $contributionId
2719 * Contribution id.
2720 *
2721 * @return string
2722 * contribution status
2723 */
2724 public static function isSubscriptionCancelled($contributionId) {
2725 $sql = "
2726 SELECT cr.contribution_status_id
2727 FROM civicrm_contribution_recur cr
2728 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2729 WHERE con.id = %1 LIMIT 1";
2730 $params = array(1 => array($contributionId, 'Integer'));
2731 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2732 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2733 if ($status == 'Cancelled') {
2734 return TRUE;
2735 }
2736 return FALSE;
2737 }
2738
2739 /**
2740 * Create all financial accounts entry.
2741 *
2742 * @param array $params
2743 * Contribution object, line item array and params for trxn.
2744 *
2745 *
2746 * @param array $financialTrxnValues
2747 *
2748 * @return null|object
2749 */
2750 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2751 $skipRecords = $update = $return = $isRelatedId = FALSE;
2752
2753 $additionalParticipantId = array();
2754 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2755
2756 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2757 $entityId = $params['participant_id'];
2758 $entityTable = 'civicrm_participant';
2759 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2760 }
2761 elseif (!empty($params['membership_id'])) {
2762 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2763 // are created off one contribution should be handled elsewhere
2764 $entityId = $params['membership_id'];
2765 $entityTable = 'civicrm_membership';
2766 }
2767 else {
2768 $entityId = $params['contribution']->id;
2769 $entityTable = 'civicrm_contribution';
2770 }
2771
2772 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2773 $isRelatedId = TRUE;
2774 }
2775
2776 $entityID[] = $entityId;
2777 if (!empty($additionalParticipantId)) {
2778 $entityID += $additionalParticipantId;
2779 }
2780 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2781 if (empty($params['prevContribution'])) {
2782 $entityID = NULL;
2783 }
2784 else {
2785 $update = TRUE;
2786 }
2787
2788 $statusId = $params['contribution']->contribution_status_id;
2789 // CRM-13964 partial payment
2790 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2791 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2792 ) {
2793 $partialAmtPay = $params['partial_amount_pay'];
2794 $partialAmtTotal = $params['partial_payment_total'];
2795
2796 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2797 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2798 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
2799 $params['total_amount'] = $partialAmtPay;
2800
2801 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
2802 if (empty($balanceTrxnInfo['trxn_id'])) {
2803 // create new balance transaction record
2804 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2805 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2806
2807 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2808 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2809 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2810 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis');
2811 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2812 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2813 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2814 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2815 $balanceTrxnParams['status_id'] = $statusId;
2816 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2817 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
2818 if (!empty($params['payment_processor'])) {
2819 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2820 }
2821 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
2822 }
2823 }
2824
2825 // build line item array if its not set in $params
2826 if (empty($params['line_item']) || $additionalParticipantId) {
2827 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2828 }
2829
2830 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2831 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
2832 ) {
2833 $skipRecords = TRUE;
2834 $pendingStatus = array(
2835 array_search('Pending', $contributionStatuses),
2836 array_search('In Progress', $contributionStatuses),
2837 );
2838 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
2839 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2840 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2841 }
2842 elseif (!empty($params['payment_processor'])) {
2843 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2844 }
2845 elseif (!empty($params['payment_instrument_id'])) {
2846 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2847 }
2848 else {
2849 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2850 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2851 $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);
2852 }
2853
2854 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2855 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2856 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2857 }
2858
2859 //build financial transaction params
2860 $trxnParams = array(
2861 'contribution_id' => $params['contribution']->id,
2862 'to_financial_account_id' => $params['to_financial_account_id'],
2863 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
2864 'total_amount' => $totalAmount,
2865 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2866 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
2867 'currency' => $params['contribution']->currency,
2868 'trxn_id' => $params['contribution']->trxn_id,
2869 'status_id' => $statusId,
2870 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
2871 'check_number' => CRM_Utils_Array::value('check_number', $params),
2872 );
2873
2874 if (!empty($params['payment_processor'])) {
2875 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2876 }
2877
2878 if (isset($fromFinancialAccountId)) {
2879 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2880 }
2881
2882 // consider external values passed for recording transaction entry
2883 if (!empty($financialTrxnValues)) {
2884 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2885 }
2886
2887 $params['trxnParams'] = $trxnParams;
2888
2889 if (!empty($params['prevContribution'])) {
2890 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2891 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2892 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2893 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2894 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
2895
2896 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
2897 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
2898 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
2899 ) {
2900 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2901 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2902 }
2903
2904 //if financial type is changed
2905 if (!empty($params['financial_type_id']) &&
2906 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
2907 ) {
2908 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2909 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2910 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2911 if ($oldFinancialAccount != $newFinancialAccount) {
2912 $params['total_amount'] = 0;
2913 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
2914 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2915 $params['prevContribution']->financial_type_id, $relationTypeId);
2916 }
2917 else {
2918 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2919 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2920 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2921 }
2922 }
2923 self::updateFinancialAccounts($params, 'changeFinancialType');
2924 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2925 $params['financial_account_id'] = $newFinancialAccount;
2926 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2927 self::updateFinancialAccounts($params);
2928 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2929 }
2930 }
2931
2932 //Update contribution status
2933 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
2934 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2935 if (!empty($params['contribution_status_id']) &&
2936 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2937 ) {
2938 //Update Financial Records
2939 self::updateFinancialAccounts($params, 'changedStatus');
2940 }
2941
2942 // change Payment Instrument for a Completed contribution
2943 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2944 // instrument is null and now new payment instrument is added along with the payment
2945 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2946 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
2947 if (array_key_exists('payment_instrument_id', $params)) {
2948 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2949 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2950 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
2951 ) {
2952 //check if status is changed from Pending to Completed
2953 // do not update payment instrument changes for Pending to Completed
2954 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2955 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
2956 ) {
2957 // for all other statuses create new financial records
2958 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2959 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2960 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2961 }
2962 }
2963 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2964 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2965 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
2966 ) {
2967 // for any other payment instrument changes create new financial records
2968 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2969 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2970 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2971 }
2972 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2973 $params['contribution']->check_number != $params['prevContribution']->check_number
2974 ) {
2975 // another special case when check number is changed, create new financial records
2976 // create financial trxn with negative amount
2977 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2978 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2979 // create financial trxn with positive amount
2980 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2981 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2982 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2983 }
2984 }
2985
2986 //if Change contribution amount
2987 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2988 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2989 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2990 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2991 if (isset($totalAmount) &&
2992 $totalAmount != $params['prevContribution']->total_amount
2993 ) {
2994 //Update Financial Records
2995 $params['trxnParams']['from_financial_account_id'] = NULL;
2996 self::updateFinancialAccounts($params, 'changedAmount');
2997 }
2998 }
2999
3000 if (!$update) {
3001 // records finanical trxn and entity financial trxn
3002 // also make it available as return value
3003 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3004 $params['entity_id'] = $financialTxn->id;
3005 }
3006 }
3007 // record line items and financial items
3008 if (empty($params['skipLineItem'])) {
3009 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
3010 }
3011
3012 // create batch entry if batch_id is passed and
3013 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3014 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3015 $entityParams = array(
3016 'batch_id' => $params['batch_id'],
3017 'entity_table' => 'civicrm_financial_trxn',
3018 'entity_id' => $financialTxn->id,
3019 );
3020 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
3021 }
3022
3023 // when a fee is charged
3024 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
3025 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3026 }
3027
3028 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3029 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3030 ) {
3031 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3032 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3033 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3034 }
3035 unset($params['line_item']);
3036
3037 return $return;
3038 }
3039
3040 /**
3041 * Update all financial accounts entry.
3042 *
3043 * @param array $params
3044 * Contribution object, line item array and params for trxn.
3045 *
3046 * @param string $context
3047 * Update scenarios.
3048 *
3049 * @param null $skipTrxn
3050 *
3051 */
3052 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3053 $itemAmount = $trxnID = NULL;
3054 //get all the statuses
3055 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3056 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3057 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
3058 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3059 && $context == 'changePaymentInstrument'
3060 ) {
3061 return;
3062 }
3063 if (($params['prevContribution']->contribution_status_id == array_search('Partially paid', $contributionStatus))
3064 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3065 && $context == 'changedStatus'
3066 ) {
3067 return;
3068 }
3069 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3070 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
3071 }
3072 if ($context == 'changedStatus') {
3073 //get all the statuses
3074 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3075
3076 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
3077 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3078 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
3079 ) {
3080 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3081 }
3082 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3083 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
3084 ) {
3085 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
3086 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
3087 $params['trxnParams']['to_financial_account_id'] = NULL;
3088 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3089 }
3090 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3091 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
3092 $financialTypeID, $relationTypeId);
3093 }
3094 $itemAmount = $params['trxnParams']['total_amount'];
3095 }
3096 elseif ($context == 'changePaymentInstrument') {
3097 if ($params['trxnParams']['total_amount'] < 0) {
3098 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3099 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3100 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3101 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3102 }
3103 }
3104 else {
3105 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3106 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3107 }
3108 }
3109 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3110 $params['entity_id'] = $trxn->id;
3111
3112 if ($context == 'changedStatus') {
3113 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3114 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
3115 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3116 ) {
3117 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3118 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3119
3120 $entityParams = array(
3121 'entity_table' => 'civicrm_financial_item',
3122 'financial_trxn_id' => $trxn->id,
3123 );
3124 if (empty($params['line_item'])) {
3125 //CRM-15296
3126 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3127 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3128 // & this can be removed
3129 return;
3130 }
3131 foreach ($params['line_item'] as $fieldId => $fields) {
3132 foreach ($fields as $fieldValueId => $fieldValues) {
3133 $fparams = array(
3134 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3135 2 => array($fieldValues['id'], 'Integer'),
3136 );
3137 CRM_Core_DAO::executeQuery($query, $fparams);
3138 $fparams = array(
3139 1 => array($fieldValues['id'], 'Integer'),
3140 );
3141 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3142 while ($financialItem->fetch()) {
3143 $entityParams['entity_id'] = $financialItem->id;
3144 $entityParams['amount'] = $financialItem->amount;
3145 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3146 }
3147 }
3148 }
3149 return;
3150 }
3151 }
3152 if ($context != 'changePaymentInstrument') {
3153 $itemParams['entity_table'] = 'civicrm_line_item';
3154 $trxnIds['id'] = $params['entity_id'];
3155 foreach ($params['line_item'] as $fieldId => $fields) {
3156 foreach ($fields as $fieldValueId => $fieldValues) {
3157 $prevParams['entity_id'] = $fieldValues['id'];
3158 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3159
3160 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3161 if ($params['contribution']->receive_date) {
3162 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3163 }
3164
3165 $financialAccount = $prevfinancialItem->financial_account_id;
3166 if (!empty($params['financial_account_id'])) {
3167 $financialAccount = $params['financial_account_id'];
3168 }
3169
3170 $currency = $params['prevContribution']->currency;
3171 if ($params['contribution']->currency) {
3172 $currency = $params['contribution']->currency;
3173 }
3174 $diff = 1;
3175 if (!empty($params['is_quick_config'])) {
3176 $amount = $itemAmount;
3177 if (!$amount) {
3178 $amount = $params['total_amount'];
3179 }
3180 }
3181 else {
3182 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
3183 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3184 ) {
3185 $diff = -1;
3186 }
3187 $amount = $diff * $fieldValues['line_total'];
3188 }
3189
3190 $itemParams = array(
3191 'transaction_date' => $receiveDate,
3192 'contact_id' => $params['prevContribution']->contact_id,
3193 'currency' => $currency,
3194 'amount' => $amount,
3195 'description' => $prevfinancialItem->description,
3196 'status_id' => $prevfinancialItem->status_id,
3197 'financial_account_id' => $financialAccount,
3198 'entity_table' => 'civicrm_line_item',
3199 'entity_id' => $fieldValues['id'],
3200 );
3201 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3202
3203 if ($fieldValues['tax_amount']) {
3204 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3205 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3206 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3207 $itemParams['description'] = $taxTerm;
3208 if ($fieldValues['financial_type_id']) {
3209 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3210 }
3211 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3212 }
3213 }
3214 }
3215 }
3216 if ($context == 'changeFinancialType') {
3217 $params['skipLineItem'] = FALSE;
3218 foreach ($params['line_item'] as &$lineItems) {
3219 foreach ($lineItems as &$line) {
3220 $line['financial_type_id'] = $params['financial_type_id'];
3221 }
3222 }
3223 }
3224 }
3225
3226 /**
3227 * Check status validation on update of a contribution.
3228 *
3229 * @param array $values
3230 * Previous form values before submit.
3231 *
3232 * @param array $fields
3233 * The input form values.
3234 *
3235 * @param array $errors
3236 * List of errors.
3237 *
3238 * @return bool
3239 */
3240 public static function checkStatusValidation($values, &$fields, &$errors) {
3241 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3242 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3243 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3244 return FALSE;
3245 }
3246 }
3247 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3248 $checkStatus = array(
3249 'Cancelled' => array('Completed', 'Refunded'),
3250 'Completed' => array('Cancelled', 'Refunded'),
3251 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3252 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3253 'Refunded' => array('Cancelled', 'Completed'),
3254 'Partially paid' => array('Completed'),
3255 );
3256
3257 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3258 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3259 1 => $contributionStatuses[$values['contribution_status_id']],
3260 2 => $contributionStatuses[$fields['contribution_status_id']],
3261 ));
3262 }
3263 }
3264
3265 /**
3266 * Delete contribution of contact.
3267 *
3268 * CRM-12155
3269 *
3270 * @param int $contactId
3271 * Contact id.
3272 *
3273 */
3274 public static function deleteContactContribution($contactId) {
3275 $contribution = new CRM_Contribute_DAO_Contribution();
3276 $contribution->contact_id = $contactId;
3277 $contribution->find();
3278 while ($contribution->fetch()) {
3279 self::deleteContribution($contribution->id);
3280 }
3281 }
3282
3283 /**
3284 * Get options for a given contribution field.
3285 * @see CRM_Core_DAO::buildOptions
3286 *
3287 * @param string $fieldName
3288 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3289 * @param array $props whatever is known about this dao object.
3290 *
3291 * @return array|bool
3292 */
3293 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3294 $className = __CLASS__;
3295 $params = array();
3296 switch ($fieldName) {
3297 // This field is not part of this object but the api supports it
3298 case 'payment_processor':
3299 $className = 'CRM_Contribute_BAO_ContributionPage';
3300 // Filter results by contribution page
3301 if (!empty($props['contribution_page_id'])) {
3302 $page = civicrm_api('contribution_page', 'getsingle', array(
3303 'version' => 3,
3304 'id' => ($props['contribution_page_id']),
3305 ));
3306 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3307 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3308 }
3309 break;
3310
3311 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3312 case 'honor_type_id':
3313 $className = 'CRM_Contribute_BAO_ContributionSoft';
3314 $fieldName = 'soft_credit_type_id';
3315 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3316 break;
3317 }
3318 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3319 }
3320
3321 /**
3322 * Validate financial type.
3323 *
3324 * CRM-13231
3325 *
3326 * @param int $financialTypeId
3327 * Financial Type id.
3328 *
3329 * @param string $relationName
3330 *
3331 * @return array|bool
3332 */
3333 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3334 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3335 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3336
3337 if (!$financialAccount) {
3338 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3339 }
3340 return FALSE;
3341 }
3342
3343
3344 /**
3345 * Function to record additional payment for partial and refund contributions.
3346 *
3347 * @param int $contributionId
3348 * is the invoice contribution id (got created after processing participant payment).
3349 * @param array $trxnsData
3350 * to take user provided input of transaction details.
3351 * @param string $paymentType
3352 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3353 * @param int $participantId
3354 *
3355 * @return null|object
3356 */
3357 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3358 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3359 $getInfoOf['id'] = $contributionId;
3360 $defaults = array();
3361 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3362
3363 if ($paymentType == 'owed') {
3364 // build params for recording financial trxn entry
3365 $params['contribution'] = $contributionDAO;
3366 $params = array_merge($defaults, $params);
3367 $params['skipLineItem'] = TRUE;
3368 $params['partial_payment_total'] = $contributionDAO->total_amount;
3369 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3370 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3371 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3372
3373 // record the entry
3374 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3375 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3376 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3377
3378 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3379 if (!empty($trxnId)) {
3380 $trxnId = $trxnId['trxn_id'];
3381 }
3382 elseif (!empty($contributionDAO->payment_instrument_id)) {
3383 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3384 }
3385 else {
3386 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3387 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3388 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3389 }
3390
3391 // update statuses
3392 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3393 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3394 FROM civicrm_financial_trxn ft
3395 LEFT JOIN civicrm_entity_financial_trxn eft
3396 ON (ft.id = eft.financial_trxn_id)
3397 WHERE eft.entity_table = 'civicrm_contribution'
3398 AND eft.entity_id = {$contributionId}
3399 AND ft.to_financial_account_id != {$toFinancialAccount}
3400 AND ft.status_id = {$statusId}
3401 ";
3402 $query = CRM_Core_DAO::executeQuery($sql);
3403 $query->fetch();
3404 $sumOfPayments = $query->sum_of_payments;
3405
3406 // update statuses
3407 if ($contributionDAO->total_amount == $sumOfPayments) {
3408 // update contribution status and
3409 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3410 $contributionDAO->contribution_status_id = $statusId;
3411 $contributionDAO->cancel_date = 'null';
3412 $contributionDAO->cancel_reason = NULL;
3413 $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
3414 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
3415 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
3416 $contributionDAO->save();
3417
3418 //Change status of financial record too
3419 $financialTrxn->status_id = $statusId;
3420 $financialTrxn->save();
3421
3422 // note : not using the self::add method,
3423 // the reason because it performs 'status change' related code execution for financial records
3424 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3425 // are coded below i.e. just updating financial_item status to 'Paid'
3426
3427 if ($participantId) {
3428 // update participant status
3429 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3430 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3431 foreach ($ids as $val) {
3432 $participantUpdate['id'] = $val;
3433 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3434 CRM_Event_BAO_Participant::add($participantUpdate);
3435 }
3436 }
3437
3438 // update financial item statuses
3439 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3440 $paidStatus = array_search('Paid', $financialItemStatus);
3441
3442 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3443 $sqlFinancialItemUpdate = "
3444 UPDATE civicrm_financial_item fi
3445 LEFT JOIN civicrm_entity_financial_trxn eft
3446 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3447 SET status_id = {$paidStatus}
3448 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3449 ";
3450 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3451 }
3452 }
3453 elseif ($paymentType == 'refund') {
3454 // build params for recording financial trxn entry
3455 $params['contribution'] = $contributionDAO;
3456 $params = array_merge($defaults, $params);
3457 $params['skipLineItem'] = TRUE;
3458 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3459 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3460
3461 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3462 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3463 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3464 // record the entry
3465 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3466
3467 // note : not using the self::add method,
3468 // the reason because it performs 'status change' related code execution for financial records
3469 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3470 // are coded below i.e. just updating financial_item status to 'Paid'
3471 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3472
3473 // add financial item entry
3474 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3475 $getLine['entity_id'] = $contributionDAO->id;
3476 $getLine['entity_table'] = 'civicrm_contribution';
3477 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
3478 if (!empty($lineItemId->id)) {
3479 $addFinancialEntry = array(
3480 'transaction_date' => $financialTrxn->trxn_date,
3481 'contact_id' => $contributionDAO->contact_id,
3482 'amount' => $financialTrxn->total_amount,
3483 'status_id' => array_search('Paid', $financialItemStatus),
3484 'entity_id' => $lineItemId->id,
3485 'entity_table' => 'civicrm_line_item',
3486 );
3487 $trxnIds['id'] = $financialTrxn->id;
3488 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3489 }
3490 if ($participantId) {
3491 // update participant status
3492 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3493 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3494 foreach ($ids as $val) {
3495 $participantUpdate['id'] = $val;
3496 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3497 CRM_Event_BAO_Participant::add($participantUpdate);
3498 }
3499 }
3500 }
3501
3502 // activity creation
3503 if (!empty($financialTrxn)) {
3504 if ($participantId) {
3505 $inputParams['id'] = $participantId;
3506 $values = array();
3507 $ids = array();
3508 $component = 'event';
3509 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3510 $entityObj = $entityObj[$participantId];
3511 }
3512 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3513
3514 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3515 }
3516 return $financialTrxn;
3517 }
3518
3519 /**
3520 * @param $entityObj
3521 * @param $trxnObj
3522 * @param $activityType
3523 * @param $component
3524 * @param int $contributionId
3525 *
3526 * @throws CRM_Core_Exception
3527 */
3528 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3529 if ($component == 'event') {
3530 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3531 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3532 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3533 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3534 $targetCid = $entityObj->contact_id;
3535 // source record id would be the contribution id
3536 $srcRecId = $contributionId;
3537 }
3538
3539 // activity params
3540 $activityParams = array(
3541 'source_contact_id' => $targetCid,
3542 'source_record_id' => $srcRecId,
3543 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3544 $activityType,
3545 'name'
3546 ),
3547 'subject' => $subject,
3548 'activity_date_time' => $date,
3549 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3550 'Completed',
3551 'name'
3552 ),
3553 'skipRecentView' => TRUE,
3554 );
3555
3556 // create activity with target contacts
3557 $session = CRM_Core_Session::singleton();
3558 $id = $session->get('userID');
3559 if ($id) {
3560 $activityParams['source_contact_id'] = $id;
3561 $activityParams['target_contact_id'][] = $targetCid;
3562 }
3563 CRM_Activity_BAO_Activity::create($activityParams);
3564 }
3565
3566 /**
3567 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3568 *
3569 * @param int $id
3570 * @param $component
3571 * @param bool $getTrxnInfo
3572 * @param bool $usingLineTotal
3573 *
3574 * @return mixed
3575 */
3576 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3577 if ($component == 'event') {
3578 $entity = 'participant';
3579 $entityTable = 'civicrm_participant';
3580 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3581
3582 if (!$contributionId) {
3583 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3584 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3585 $id = $primaryParticipantId;
3586 }
3587 if (!$contributionId) {
3588 return;
3589 }
3590 }
3591 }
3592 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3593 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3594 $isBalance = NULL;
3595 if ($baseTrxnId) {
3596 $isBalance = TRUE;
3597 }
3598 else {
3599 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3600 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3601 $isBalance = FALSE;
3602 }
3603 if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
3604 // for additional participants
3605 if ($entityTable == 'civicrm_participant') {
3606 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3607 $total = 0;
3608 foreach ($ids as $val) {
3609 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3610 }
3611 }
3612 else {
3613 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3614 }
3615 }
3616 else {
3617 $baseTrxnId = $total['trxn_id'];
3618 $total = $total['total_amount'];
3619 }
3620
3621 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
3622 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3623
3624 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3625 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3626 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
3627
3628 if ($paymentBalance == 0 && $contributionIsPayLater) {
3629 $paymentBalance = $total;
3630 }
3631
3632 $info['total'] = $total;
3633 $info['paid'] = $total - $paymentBalance;
3634 $info['balance'] = $paymentBalance;
3635 $info['id'] = $id;
3636 $info['component'] = $component;
3637 $info['payLater'] = $contributionIsPayLater;
3638 $rows = array();
3639 if ($getTrxnInfo && $baseTrxnId) {
3640 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3641 $sql = "
3642 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3643 FROM civicrm_contribution con
3644 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3645 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3646 WHERE con.id = {$contributionId}
3647 ";
3648
3649 // conditioned WHERE clause
3650 if ($isBalance) {
3651 // if balance trxn exists don't include details of it in transaction info
3652 $sql .= " AND ft.id != {$baseTrxnId} ";
3653 }
3654 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3655
3656 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3657 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
3658 while ($resultDAO->fetch()) {
3659 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3660 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3661 $val = array(
3662 'total_amount' => $resultDAO->total_amount,
3663 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
3664 'payment_instrument' => $paidByLabel,
3665 'receive_date' => $resultDAO->trxn_date,
3666 'trxn_id' => $resultDAO->trxn_id,
3667 'status' => $statuses[$resultDAO->status_id],
3668 );
3669 if ($paidByName == 'Check') {
3670 $val['check_number'] = $resultDAO->check_number;
3671 }
3672 $rows[] = $val;
3673 }
3674 $info['transaction'] = $rows;
3675 }
3676 return $info;
3677 }
3678
3679 /**
3680 * Get financial account id has 'Sales Tax Account is'
3681 * account relationship with financial type
3682 *
3683 * @param int $financialTypeId
3684 *
3685 * @return FinancialAccountId
3686 */
3687 public static function getFinancialAccountId($financialTypeId) {
3688 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3689 $searchParams = array(
3690 'entity_table' => 'civicrm_financial_type',
3691 'entity_id' => $financialTypeId,
3692 'account_relationship' => $accountRel,
3693 );
3694 $result = array();
3695 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
3696
3697 return CRM_Utils_Array::value('financial_account_id', $result);
3698 }
3699
3700 /**
3701 * Check tax amount.
3702 *
3703 * @param array $params
3704 * @param bool $isLineItem
3705 *
3706 * @return mixed
3707 */
3708 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3709 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
3710
3711 // Update contribution.
3712 if (!empty($params['id'])) {
3713 $id = $params['id'];
3714 $values = $ids = array();
3715 $contrbutionParams = array('id' => $id);
3716 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
3717
3718 // To assign pervious finantial type on update of contribution
3719 if (!isset($params['financial_type_id'])) {
3720 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
3721 }
3722 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3723 // Assisn tax Amount on update of contrbution
3724 if (!empty($prevContributionValue->tax_amount)) {
3725 $params['tax_amount'] = 'null';
3726 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3727 foreach ($params['line_item'] as $setID => $priceField) {
3728 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3729 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3730 }
3731 }
3732 }
3733 }
3734 }
3735
3736 // New Contrbution and update of contribution with tax rate financial type
3737 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3738 empty($params['skipLineItem']) && !$isLineItem
3739 ) {
3740 $taxRateParams = $taxRates[$params['financial_type_id']];
3741 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
3742 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3743
3744 // Get Line Item on update of contribution
3745 if (isset($params['id'])) {
3746 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3747 }
3748 else {
3749 CRM_Price_BAO_LineItem::getLineItemArray($params);
3750 }
3751 foreach ($params['line_item'] as $setID => $priceField) {
3752 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3753 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3754 }
3755 }
3756 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3757 }
3758 elseif (isset($params['api.line_item.create'])) {
3759 // Update total amount of contribution using lineItem
3760 $taxAmountArray = array();
3761 foreach ($params['api.line_item.create'] as $key => $value) {
3762 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3763 $taxRate = $taxRates[$value['financial_type_id']];
3764 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
3765 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3766 }
3767 }
3768 $params['tax_amount'] = array_sum($taxAmountArray);
3769 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3770 }
3771 else {
3772 // update line item of contrbution
3773 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3774 $taxRate = $taxRates[$params['financial_type_id']];
3775 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
3776 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3777 }
3778 }
3779 return $params;
3780 }
3781
3782 /**
3783 * Check financial type validation on update of a contribution.
3784 *
3785 * @param Integer $financialTypeId
3786 * Value of latest Financial Type.
3787 *
3788 * @param Integer $contributionId
3789 * Contribution Id.
3790 *
3791 * @param array $errors
3792 * List of errors.
3793 *
3794 * @return bool
3795 */
3796 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3797 if (!empty($financialTypeId)) {
3798 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3799 if ($oldFinancialTypeId == $financialTypeId) {
3800 return FALSE;
3801 }
3802 }
3803 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3804 $params = array(
3805 '1' => array($contributionId, 'Integer'),
3806 );
3807 $result = CRM_Core_DAO::executeQuery($sql, $params);
3808 if ($result->N > 1) {
3809 $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.');
3810 }
3811 }
3812
3813 /**
3814 * Update related pledge payment payments.
3815 *
3816 * This function has been refactored out of the back office contribution form and may
3817 * still overlap with other functions.
3818 *
3819 * @param string $action
3820 * @param int $pledgePaymentID
3821 * @param int $contributionID
3822 * @param bool $adjustTotalAmount
3823 * @param float $total_amount
3824 * @param float $original_total_amount
3825 * @param int $contribution_status_id
3826 * @param int $original_contribution_status_id
3827 */
3828 public static function updateRelatedPledge(
3829 $action,
3830 $pledgePaymentID,
3831 $contributionID,
3832 $adjustTotalAmount,
3833 $total_amount,
3834 $original_total_amount,
3835 $contribution_status_id,
3836 $original_contribution_status_id
3837 ) {
3838 if (!$pledgePaymentID || $action & CRM_Core_Action::ADD && !$contributionID) {
3839 return;
3840 }
3841
3842 if ($pledgePaymentID) {
3843 //store contribution id in payment record.
3844 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3845 }
3846 else {
3847 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3848 $contributionID,
3849 'id',
3850 'contribution_id'
3851 );
3852 }
3853 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3854 $contributionID,
3855 'pledge_id',
3856 'contribution_id'
3857 );
3858
3859 $updatePledgePaymentStatus = FALSE;
3860
3861 // If either the status or the amount has changed we update the pledge status.
3862 if ($action & CRM_Core_Action::ADD) {
3863 $updatePledgePaymentStatus = TRUE;
3864 }
3865 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
3866 ($original_total_amount != $total_amount))
3867 ) {
3868 $updatePledgePaymentStatus = TRUE;
3869 }
3870
3871 if ($updatePledgePaymentStatus) {
3872 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
3873 array($pledgePaymentID),
3874 $contribution_status_id,
3875 NULL,
3876 $total_amount,
3877 $adjustTotalAmount
3878 );
3879 }
3880 }
3881
3882 /**
3883 * Compute the stats values
3884 *
3885 * @param $stat either 'mode' or 'median'
3886 * @param $sql
3887 * @param $alias of civicrm_contribution
3888 */
3889 public static function computeStats($stat, $sql, $alias = NULL) {
3890 $mode = $median = array();
3891 switch ($stat) {
3892 case 'mode':
3893 $modeDAO = CRM_Core_DAO::executeQuery($sql);
3894 while ($modeDAO->fetch()) {
3895 if ($modeDAO->civicrm_contribution_total_amount_count > 1) {
3896 $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency);
3897 }
3898 else {
3899 $mode[] = 'N/A';
3900 }
3901 }
3902 return $mode;
3903
3904 case 'median':
3905 $currencies = CRM_Core_OptionGroup::values('currencies_enabled');
3906 foreach ($currencies as $currency => $val) {
3907 $midValue = 0;
3908 $where = "AND {$alias}.currency = '{$currency}'";
3909 $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
3910
3911 $even = FALSE;
3912 $offset = 1;
3913 $medianRow = floor($rowCount / 2);
3914 if ($rowCount % 2 == 0 && !empty($medianRow)) {
3915 $even = TRUE;
3916 $offset++;
3917 $medianRow--;
3918 }
3919
3920 $medianValue = "SELECT {$alias}.total_amount as median
3921 {$sql} {$where}
3922 ORDER BY median LIMIT {$medianRow},{$offset}";
3923 $medianValDAO = CRM_Core_DAO::executeQuery($medianValue);
3924 while ($medianValDAO->fetch()) {
3925 if ($even) {
3926 $midValue = $midValue + $medianValDAO->median;
3927 }
3928 else {
3929 $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency);
3930 }
3931 }
3932 if ($even) {
3933 $midValue = $midValue / 2;
3934 $median[] = CRM_Utils_Money::format($midValue, $currency);
3935 }
3936 }
3937 return $median;
3938
3939 default:
3940 return;
3941 }
3942 }
3943
3944 /**
3945 * Complete an order.
3946 *
3947 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
3948 *
3949 * Currently overloaded to complete a transaction & repeat a transaction - fix!
3950 *
3951 * Moving it out of the BaseIPN class is just the first step.
3952 *
3953 * @param array $input
3954 * @param array $ids
3955 * @param array $objects
3956 * @param CRM_Core_Transaction $transaction
3957 * @param int $recur
3958 * @param CRM_Contribute_BAO_Contribution $contribution
3959 * @param bool $isRecurring
3960 * Duplication of param needs review. Only used by AuthorizeNetIPN
3961 * @param int $isFirstOrLastRecurringPayment
3962 * Deprecated param only used by AuthorizeNetIPN.
3963 */
3964 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring,
3965 $isFirstOrLastRecurringPayment) {
3966 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
3967
3968 $participant = CRM_Utils_Array::value('participant', $objects);
3969 $memberships = CRM_Utils_Array::value('membership', $objects);
3970 $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
3971
3972 if (is_numeric($memberships)) {
3973 $memberships = array($objects['membership']);
3974 }
3975
3976 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
3977
3978 $values = array();
3979 if (isset($input['is_email_receipt'])) {
3980 $values['is_email_receipt'] = $input['is_email_receipt'];
3981 }
3982 $source = NULL;
3983 if ($input['component'] == 'contribute') {
3984 if ($contribution->contribution_page_id) {
3985 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
3986 $source = ts('Online Contribution') . ': ' . $values['title'];
3987 }
3988 elseif ($recurContrib && $recurContrib->id) {
3989 $contribution->contribution_page_id = NULL;
3990 $values['amount'] = $recurContrib->amount;
3991 $values['financial_type_id'] = $objects['contributionType']->id;
3992 $values['title'] = $source = ts('Offline Recurring Contribution');
3993 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
3994 $values['receipt_from_name'] = $domainValues[0];
3995 $values['receipt_from_email'] = $domainValues[1];
3996 }
3997
3998 if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
3999 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4000 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4001 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
4002 }
4003
4004 $contribution->source = $source;
4005 if (!empty($values['is_email_receipt'])) {
4006 $contribution->receipt_date = $changeDate;
4007 }
4008
4009 if (!empty($memberships)) {
4010 foreach ($memberships as $membershipTypeIdKey => $membership) {
4011 if ($membership) {
4012 $membershipParams = array(
4013 'id' => $membership->id,
4014 'contact_id' => $membership->contact_id,
4015 'is_test' => $membership->is_test,
4016 'membership_type_id' => $membership->membership_type_id,
4017 );
4018
4019 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
4020 $membershipParams['membership_type_id'],
4021 $membershipParams['is_test'],
4022 $membershipParams['id']
4023 );
4024
4025 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4026 // this picks up membership type changes during renewals
4027 $sql = "
4028 SELECT membership_type_id
4029 FROM civicrm_membership_log
4030 WHERE membership_id={$membershipParams['id']}
4031 ORDER BY id DESC
4032 LIMIT 1;";
4033 $dao = CRM_Core_DAO::executeQuery($sql);
4034 if ($dao->fetch()) {
4035 if (!empty($dao->membership_type_id)) {
4036 $membershipParams['membership_type_id'] = $dao->membership_type_id;
4037 }
4038 }
4039 $dao->free();
4040
4041 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4042 $membershipParams['membership_type_id'],
4043 $primaryContributionID
4044 );
4045 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4046 if ($currentMembership) {
4047 /*
4048 * Fixed FOR CRM-4433
4049 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4050 * when Contribution mode is notify and membership is for renewal )
4051 */
4052 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4053
4054 // @todo - we should pass membership_type_id instead of null here but not
4055 // adding as not sure of testing
4056 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
4057 $changeDate, NULL, $membershipParams['num_terms']
4058 );
4059
4060 $dates['join_date'] = $currentMembership['join_date'];
4061 }
4062
4063 //get the status for membership.
4064 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
4065 $dates['end_date'],
4066 $dates['join_date'],
4067 'today',
4068 TRUE,
4069 $membershipParams['membership_type_id'],
4070 $membershipParams
4071 );
4072
4073 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
4074 //we might be renewing membership,
4075 //so make status override false.
4076 $membershipParams['is_override'] = FALSE;
4077 civicrm_api3('Membership', 'create', $membershipParams);
4078
4079 //update related Memberships.
4080 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
4081 }
4082 }
4083 }
4084 }
4085 else {
4086 // event
4087 $eventParams = array('id' => $objects['event']->id);
4088 $values['event'] = array();
4089
4090 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
4091
4092 //get location details
4093 $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
4094 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
4095
4096 $ufJoinParams = array(
4097 'entity_table' => 'civicrm_event',
4098 'entity_id' => $ids['event'],
4099 'module' => 'CiviEvent',
4100 );
4101
4102 list($custom_pre_id,
4103 $custom_post_ids
4104 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
4105
4106 $values['custom_pre_id'] = $custom_pre_id;
4107 $values['custom_post_id'] = $custom_post_ids;
4108 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
4109 //and cases involving status updation through ipn
4110 $values['totalAmount'] = $input['amount'];
4111
4112 $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
4113
4114 if ($values['event']['is_email_confirm']) {
4115 $contribution->receipt_date = $changeDate;
4116 $values['is_email_receipt'] = 1;
4117 }
4118 if (empty($input['skipComponentSync'])) {
4119 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
4120 'labelColumn' => 'name',
4121 'flip' => 1,
4122 ));
4123 $participant->status_id = $participantStatuses['Registered'];
4124 }
4125 $participant->save();
4126 }
4127
4128 if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 &&
4129 CRM_Utils_Array::value('fee_amount', $input, 0) != 0
4130 ) {
4131 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
4132 }
4133 // This complete transaction function is being overloaded to create new contributions too.
4134 // here we record if it is a new contribution.
4135 // @todo separate the 2 more appropriately.
4136 $isNewContribution = FALSE;
4137 if (empty($contribution->id)) {
4138 $isNewContribution = TRUE;
4139 if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
4140 $contribution->total_amount = $input['amount'];
4141 // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
4142 // so we have to handle net_amount in this (naughty) code.
4143 if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
4144 $contribution->fee_amount = $input['fee_amount'];
4145 }
4146 $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
4147 }
4148 if (!empty($input['campaign_id'])) {
4149 $contribution->campaign_id = $input['campaign_id'];
4150 }
4151 }
4152
4153 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4154 'labelColumn' => 'name',
4155 'flip' => 1,
4156 ));
4157
4158 // @todo this section should call the api in order to have hooks called &
4159 // because all this 'messiness' setting variables could be avoided
4160 // by letting the api resolve pseudoconstants & copy set values and format dates.
4161 $contribution->contribution_status_id = $contributionStatuses['Completed'];
4162 $contribution->is_test = $input['is_test'];
4163
4164 // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
4165 if (isset($input['net_amount'])) {
4166 $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
4167 }
4168 if (isset($input['net_amount'])) {
4169 $contribution->net_amount = $input['net_amount'];
4170 }
4171
4172 $contribution->trxn_id = $input['trxn_id'];
4173 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
4174 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
4175 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
4176 $contribution->cancel_date = 'null';
4177
4178 if (!empty($input['check_number'])) {
4179 $contribution->check_number = $input['check_number'];
4180 }
4181
4182 if (!empty($input['payment_instrument_id'])) {
4183 $contribution->payment_instrument_id = $input['payment_instrument_id'];
4184 }
4185
4186 if (!empty($contribution->id)) {
4187 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id),
4188 CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
4189 }
4190
4191 $contribution->save();
4192
4193 // Add new soft credit against current $contribution.
4194 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
4195 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
4196 }
4197
4198 //add line items for recurring payments
4199 if (!empty($contribution->contribution_recur_id)) {
4200 if ($isNewContribution) {
4201 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($contribution->contribution_recur_id, $contribution);
4202 }
4203 else {
4204 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
4205 $input['line_item'] = array();
4206 }
4207 }
4208
4209 //copy initial contribution custom fields for recurring contributions
4210 if ($recurContrib && $recurContrib->id) {
4211 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($recurContrib->id, $contribution->id);
4212 }
4213
4214 $paymentProcessorId = '';
4215 if (isset($objects['paymentProcessor'])) {
4216 if (is_array($objects['paymentProcessor'])) {
4217 $paymentProcessorId = $objects['paymentProcessor']['id'];
4218 }
4219 else {
4220 $paymentProcessorId = $objects['paymentProcessor']->id;
4221 }
4222 }
4223
4224 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4225 'labelColumn' => 'name',
4226 'flip' => 1,
4227 ));
4228 if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
4229 $input['payment_processor'] = $paymentProcessorId;
4230 }
4231 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4232 $input['total_amount'] = $input['amount'];
4233 $input['contribution'] = $contribution;
4234 $input['financial_type_id'] = $contribution->financial_type_id;
4235
4236 if (!empty($contribution->_relatedObjects['participant'])) {
4237 $input['contribution_mode'] = 'participant';
4238 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
4239 $input['skipLineItem'] = 1;
4240 }
4241 elseif (!empty($contribution->_relatedObjects['membership'])) {
4242 $input['skipLineItem'] = TRUE;
4243 $input['contribution_mode'] = 'membership';
4244 }
4245 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4246 // and subsequent payments. In this case the line items are created at
4247 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4248 // and since the contribution is saved prior to this line there is always a contribution-id,
4249 // however there is never a prevContribution (which appears to mean original contribution not previous
4250 // contribution - or preUpdateContributionObject most accurately)
4251 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4252 // to mean "are we updating an exisitng pending contribution"
4253 //I was able to make the unit test complete as fataling here doesn't prevent
4254 // the contribution being created - but activities would not be created or emails sent
4255
4256 CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
4257
4258 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
4259 $transaction->commit();
4260
4261 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
4262
4263 // create an activity record
4264 if ($input['component'] == 'contribute') {
4265 //CRM-4027
4266 $targetContactID = NULL;
4267 if (!empty($ids['related_contact'])) {
4268 $targetContactID = $contribution->contact_id;
4269 $contribution->contact_id = $ids['related_contact'];
4270 }
4271 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
4272 // event
4273 }
4274 else {
4275 CRM_Activity_BAO_Activity::addActivity($participant);
4276 }
4277
4278 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4279 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4280 if (!array_key_exists('is_email_receipt', $values) ||
4281 $values['is_email_receipt'] == 1
4282 ) {
4283 self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
4284 CRM_Core_Error::debug_log_message("Receipt sent");
4285 }
4286
4287 CRM_Core_Error::debug_log_message("Success: Database updated");
4288 if ($isRecurring) {
4289 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
4290 $isFirstOrLastRecurringPayment);
4291 }
4292 }
4293
4294 /**
4295 * Send receipt from contribution.
4296 *
4297 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4298 *
4299 * Note that the compose message part has been moved to contribution
4300 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4301 *
4302 * @param array $input
4303 * Incoming data from Payment processor.
4304 * @param array $ids
4305 * Related object IDs.
4306 * @param $objects
4307 * @param array $values
4308 * Values related to objects that have already been loaded.
4309 * @param bool $recur
4310 * Is it part of a recurring contribution.
4311 * @param bool $returnMessageText
4312 * Should text be returned instead of sent. This.
4313 * is because the function is also used to generate pdfs
4314 *
4315 * @return array
4316 */
4317 public static function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4318 $contribution = $objects['contribution'];
4319 $input['is_recur'] = $recur;
4320 // set receipt from e-mail and name in value
4321 if (!$returnMessageText) {
4322 $session = CRM_Core_Session::singleton();
4323 $userID = $session->get('userID');
4324 if (!empty($userID)) {
4325 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
4326 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail);
4327 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName);
4328 }
4329 }
4330 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4331 }
4332
4333 }