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