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