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