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