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