Merge pull request #2687 from giant-rabbit/event_info_custom_validation
[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 * @return array array of importable Fields
495 * @access public
496 * @static
497 */
498 static function &importableFields($contactType = 'Individual', $status = TRUE) {
499 if (!self::$_importableFields) {
500 if (!self::$_importableFields) {
501 self::$_importableFields = array();
502 }
503
504 if (!$status) {
505 $fields = array('' => array('title' => ts('- do not import -')));
506 }
507 else {
508 $fields = array('' => array('title' => ts('- Contribution Fields -')));
509 }
510
511 $note = CRM_Core_DAO_Note::import();
512 $tmpFields = CRM_Contribute_DAO_Contribution::import();
513 unset($tmpFields['option_value']);
514 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
515 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
516
517 // Using new Dedupe rule.
518 $ruleParams = array(
519 'contact_type' => $contactType,
520 'used' => 'Unsupervised',
521 );
522 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
523 $tmpContactField = array();
524 if (is_array($fieldsArray)) {
525 foreach ($fieldsArray as $value) {
526 //skip if there is no dupe rule
527 if ($value == 'none') {
528 continue;
529 }
530 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
531 $value,
532 'id',
533 'column_name'
534 );
535 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
536 $tmpContactField[trim($value)] = $contactFields[trim($value)];
537 if (!$status) {
538 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
539 }
540 else {
541 $title = $tmpContactField[trim($value)]['title'];
542 }
543 $tmpContactField[trim($value)]['title'] = $title;
544 }
545 }
546
547 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
548 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
549 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
550 $fields = array_merge($fields, $tmpContactField);
551 $fields = array_merge($fields, $tmpFields);
552 $fields = array_merge($fields, $note);
553 $fields = array_merge($fields, $optionFields);
554 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
555 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
556 self::$_importableFields = $fields;
557 }
558 return self::$_importableFields;
559 }
560
561 static function &exportableFields() {
562 if (!self::$_exportableFields) {
563 if (!self::$_exportableFields) {
564 self::$_exportableFields = array();
565 }
566
567 $impFields = CRM_Contribute_DAO_Contribution::export();
568 $expFieldProduct = CRM_Contribute_DAO_Product::export();
569 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
570 $typeField = CRM_Financial_DAO_FinancialType::export();
571 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
572 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
573 $contributionStatus = array(
574 'contribution_status' => array(
575 'title' => ts('Contribution Status'),
576 'name' => 'contribution_status',
577 'data_type' => CRM_Utils_Type::T_STRING
578 ));
579
580 $contributionNote = array(
581 'contribution_note' =>
582 array(
583 'title' => ts('Contribution Note'),
584 'name' => 'contribution_note',
585 'data_type' => CRM_Utils_Type::T_TEXT
586 )
587 );
588
589 $contributionRecurId = array(
590 'contribution_recur_id' =>
591 array(
592 'title' => ts('Recurring Contributions ID'),
593 'name' => 'contribution_recur_id',
594 'where' => 'civicrm_contribution.contribution_recur_id',
595 'data_type' => CRM_Utils_Type::T_INT
596 ));
597
598 $extraFields = array(
599 'contribution_batch' => array(
600 'title' => ts('Batch Name')
601 )
602 );
603
604 $softCreditFields = array(
605 'contribution_soft_credit_name' => array(
606 'name' => 'contribution_soft_credit_name',
607 'title' => 'Soft Credit For',
608 'where' => 'civicrm_contact_d.display_name',
609 'data_type' => CRM_Utils_Type::T_STRING
610 ),
611 'contribution_soft_credit_amount' => array(
612 'name' => 'contribution_soft_credit_amount',
613 'title' => 'Soft Credit Amount',
614 'where' => 'civicrm_contribution_soft.amount',
615 'data_type' => CRM_Utils_Type::T_MONEY
616 ),
617 'contribution_soft_credit_type' => array(
618 'name' => 'contribution_soft_credit_type',
619 'title' => 'Soft Credit Type',
620 'where' => 'contribution_softcredit_type.label',
621 'data_type' => CRM_Utils_Type::T_STRING
622 ),
623 'contribution_soft_credit_contribution_id' => array(
624 'name' => 'contribution_soft_credit_contribution_id',
625 'title' => 'Soft Credit For Contribution ID',
626 'where' => 'civicrm_contribution_soft.contribution_id',
627 'data_type' => CRM_Utils_Type::T_INT
628 ),
629 );
630
631 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
632 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
633 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
634 );
635
636 self::$_exportableFields = $fields;
637 }
638
639 return self::$_exportableFields;
640 }
641
642 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
643 $where = array();
644 switch ($status) {
645 case 'Valid':
646 $where[] = 'contribution_status_id = 1';
647 break;
648
649 case 'Cancelled':
650 $where[] = 'contribution_status_id = 3';
651 break;
652 }
653
654 if ($startDate) {
655 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
656 }
657 if ($endDate) {
658 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
659 }
660
661 $whereCond = implode(' AND ', $where);
662
663 $query = "
664 SELECT sum( total_amount ) as total_amount,
665 count( civicrm_contribution.id ) as total_count,
666 currency
667 FROM civicrm_contribution
668 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
669 WHERE $whereCond
670 AND ( is_test = 0 OR is_test IS NULL )
671 AND contact.is_deleted = 0
672 GROUP BY currency
673 ";
674
675 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
676 $amount = array();
677 $count = 0;
678 while ($dao->fetch()) {
679 $count += $dao->total_count;
680 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
681 }
682 if ($count) {
683 return array('amount' => implode(', ', $amount),
684 'count' => $count,
685 );
686 }
687 return NULL;
688 }
689
690 /**
691 * Delete the indirect records associated with this contribution first
692 *
693 * @return $results no of deleted Contribution on success, false otherwise
694 * @access public
695 * @static
696 */
697 static function deleteContribution($id) {
698 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
699
700 $transaction = new CRM_Core_Transaction();
701
702 $results = NULL;
703 //delete activity record
704 $params = array(
705 'source_record_id' => $id,
706 // activity type id for contribution
707 'activity_type_id' => 6,
708 );
709
710 CRM_Activity_BAO_Activity::deleteActivity($params);
711
712 //delete billing address if exists for this contribution.
713 self::deleteAddress($id);
714
715 //update pledge and pledge payment, CRM-3961
716 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
717
718 // remove entry from civicrm_price_set_entity, CRM-5095
719 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
720 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
721 }
722 // cleanup line items.
723 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
724
725 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
726 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
727
728 if ($participantId) {
729 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
730 }
731 else {
732 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
733 }
734
735 //delete note.
736 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
737 $noteId = key($note);
738 if ($noteId) {
739 CRM_Core_BAO_Note::del($noteId, FALSE);
740 }
741
742 $dao = new CRM_Contribute_DAO_Contribution();
743 $dao->id = $id;
744
745 $results = $dao->delete();
746
747 $transaction->commit();
748
749 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
750
751 // delete the recently created Contribution
752 $contributionRecent = array(
753 'id' => $id,
754 'type' => 'Contribution',
755 );
756 CRM_Utils_Recent::del($contributionRecent);
757
758 return $results;
759 }
760
761 /**
762 * Check if there is a contribution with the same trxn_id or invoice_id
763 *
764 * @param array $params (reference ) an assoc array of name/value pairs
765 * @param array $duplicates (reference ) store ids of duplicate contribs
766 *
767 * @return boolean true if duplicate, false otherwise
768 * @access public
769 * static
770 */
771 static function checkDuplicate($input, &$duplicates, $id = NULL) {
772 if (!$id) {
773 $id = CRM_Utils_Array::value('id', $input);
774 }
775 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
776 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
777
778 $clause = array();
779 $input = array();
780
781 if ($trxn_id) {
782 $clause[] = "trxn_id = %1";
783 $input[1] = array($trxn_id, 'String');
784 }
785
786 if ($invoice_id) {
787 $clause[] = "invoice_id = %2";
788 $input[2] = array($invoice_id, 'String');
789 }
790
791 if (empty($clause)) {
792 return FALSE;
793 }
794
795 $clause = implode(' OR ', $clause);
796 if ($id) {
797 $clause = "( $clause ) AND id != %3";
798 $input[3] = array($id, 'Integer');
799 }
800
801 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
802 $dao = CRM_Core_DAO::executeQuery($query, $input);
803 $result = FALSE;
804 while ($dao->fetch()) {
805 $duplicates[] = $dao->id;
806 $result = TRUE;
807 }
808 return $result;
809 }
810
811 /**
812 * takes an associative array and creates a contribution_product object
813 *
814 * the function extract all the params it needs to initialize the create a
815 * contribution_product object. the params array could contain additional unused name/value
816 * pairs
817 *
818 * @param array $params (reference ) an assoc array of name/value pairs
819 *
820 * @return object CRM_Contribute_BAO_ContributionProduct object
821 * @access public
822 * @static
823 */
824 static function addPremium(&$params) {
825 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
826 $contributionProduct->copyValues($params);
827 return $contributionProduct->save();
828 }
829
830 /**
831 * Function to get list of contribution fields for profile
832 * For now we only allow custom contribution fields to be in
833 * profile
834 *
835 * @param boolean $addExtraFields true if special fields needs to be added
836 *
837 * @return return the list of contribution fields
838 * @static
839 * @access public
840 */
841 static function getContributionFields($addExtraFields = TRUE) {
842 $contributionFields = CRM_Contribute_DAO_Contribution::export();
843 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
844
845 if ($addExtraFields) {
846 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
847 }
848
849 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
850
851 foreach ($contributionFields as $key => $var) {
852 if ($key == 'contribution_contact_id') {
853 continue;
854 }
855 elseif ($key == 'contribution_campaign_id') {
856 $var['title'] = ts('Campaign');
857 }
858 $fields[$key] = $var;
859 }
860
861 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
862 return $fields;
863 }
864
865 /**
866 * Function to add extra fields specific to contribtion
867 *
868 * @static
869 */
870 static function getSpecialContributionFields() {
871 $extraFields = array(
872 'honor_contact_name' => array(
873 'name' => 'honor_contact_name',
874 'title' => 'Honor Contact Name',
875 'headerPattern' => '/^honor_contact_name$/i',
876 'where' => 'civicrm_contact_c.display_name',
877 ),
878 'honor_contact_email' => array(
879 'name' => 'honor_contact_email',
880 'title' => 'Honor Contact Email',
881 'headerPattern' => '/^honor_contact_email$/i',
882 'where' => 'honor_email.email',
883 ),
884 'contribution_soft_credit_name' => array(
885 'name' => 'contribution_soft_credit_name',
886 'title' => 'Soft Credit Name',
887 'headerPattern' => '/^soft_credit_name$/i',
888 'where' => 'civicrm_contact_d.display_name',
889 ),
890 'contribution_soft_credit_email' => array(
891 'name' => 'contribution_soft_credit_email',
892 'title' => 'Soft Credit Email',
893 'headerPattern' => '/^soft_credit_email$/i',
894 'where' => 'soft_email.email',
895 ),
896 'contribution_soft_credit_phone' => array(
897 'name' => 'contribution_soft_credit_phone',
898 'title' => 'Soft Credit Phone',
899 'headerPattern' => '/^soft_credit_phone$/i',
900 'where' => 'soft_phone.phone',
901 ),
902 'contribution_soft_credit_contact_id' => array(
903 'name' => 'contribution_soft_credit_contact_id',
904 'title' => 'Soft Credit Contact ID',
905 'headerPattern' => '/^soft_credit_contact_id$/i',
906 'where' => 'civicrm_contribution_soft.contact_id',
907 ),
908 );
909
910 return $extraFields;
911 }
912
913 static function getCurrentandGoalAmount($pageID) {
914 $query = "
915 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
916 FROM civicrm_contribution_page p,
917 civicrm_contribution c
918 WHERE p.id = c.contribution_page_id
919 AND p.id = %1
920 AND c.cancel_date is null
921 GROUP BY p.id
922 ";
923
924 $config = CRM_Core_Config::singleton();
925 $params = array(1 => array($pageID, 'Integer'));
926 $dao = CRM_Core_DAO::executeQuery($query, $params);
927
928 if ($dao->fetch()) {
929 return array($dao->goal, $dao->total);
930 }
931 else {
932 return array(NULL, NULL);
933 }
934 }
935
936 /**
937 * Function to get list of contribution In Honor of contact Ids
938 *
939 * @param int $honorId In Honor of Contact ID
940 *
941 * @return return the list of contribution fields
942 *
943 * @access public
944 * @static
945 */
946 static function getHonorContacts($honorId) {
947 $params = array();
948 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
949 $honorDAO->contact_id = $honorId;
950 $honorDAO->find();
951
952 $type = CRM_Contribute_PseudoConstant::financialType();
953
954 while ($honorDAO->fetch()) {
955 $contributionDAO = new CRM_Contribute_DAO_Contribution();
956 $contributionDAO->id = $honorDAO->contribution_id;
957
958 if ($contributionDAO->find(TRUE)) {
959 $params[$contributionDAO->id]['honor_type'] = CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value');
960 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
961 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
962 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
963 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
964 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
965 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
966 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
967 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
968 }
969 }
970
971 return $params;
972 }
973
974 /**
975 * function to get the sort name of a contact for a particular contribution
976 *
977 * @param int $id id of the contribution
978 *
979 * @return null|string sort name of the contact if found
980 * @static
981 * @access public
982 */
983 static function sortName($id) {
984 $id = CRM_Utils_Type::escape($id, 'Integer');
985
986 $query = "
987 SELECT civicrm_contact.sort_name
988 FROM civicrm_contribution, civicrm_contact
989 WHERE civicrm_contribution.contact_id = civicrm_contact.id
990 AND civicrm_contribution.id = {$id}
991 ";
992 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
993 }
994
995 static function annual($contactID) {
996 if (is_array($contactID)) {
997 $contactIDs = implode(',', $contactID);
998 }
999 else {
1000 $contactIDs = $contactID;
1001 }
1002
1003 $config = CRM_Core_Config::singleton();
1004 $startDate = $endDate = NULL;
1005
1006 $currentMonth = date('m');
1007 $currentDay = date('d');
1008 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1009 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1010 (int ) $config->fiscalYearStart['d'] > $currentDay
1011 )
1012 ) {
1013 $year = date('Y') - 1;
1014 }
1015 else {
1016 $year = date('Y');
1017 }
1018 $nextYear = $year + 1;
1019
1020 if ($config->fiscalYearStart) {
1021 if ($config->fiscalYearStart['M'] < 10) {
1022 $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M'];
1023 }
1024 if ($config->fiscalYearStart['d'] < 10) {
1025 $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d'];
1026 }
1027 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1028 }
1029 else {
1030 $monthDay = '0101';
1031 }
1032 $startDate = "$year$monthDay";
1033 $endDate = "$nextYear$monthDay";
1034
1035 $query = "
1036 SELECT count(*) as count,
1037 sum(total_amount) as amount,
1038 avg(total_amount) as average,
1039 currency
1040 FROM civicrm_contribution b
1041 WHERE b.contact_id IN ( $contactIDs )
1042 AND b.contribution_status_id = 1
1043 AND b.is_test = 0
1044 AND b.receive_date >= $startDate
1045 AND b.receive_date < $endDate
1046 GROUP BY currency
1047 ";
1048 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1049 $count = 0;
1050 $amount = $average = array();
1051 while ($dao->fetch()) {
1052 if ($dao->count > 0 && $dao->amount > 0) {
1053 $count += $dao->count;
1054 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1055 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1056 }
1057 }
1058 if ($count > 0) {
1059 return array(
1060 $count,
1061 implode(',&nbsp;', $amount),
1062 implode(',&nbsp;', $average),
1063 );
1064 }
1065 return array(0, 0, 0);
1066 }
1067
1068 /**
1069 * Check if there is a contribution with the params passed in.
1070 * Used for trxn_id,invoice_id and contribution_id
1071 *
1072 * @param array $params an assoc array of name/value pairs
1073 *
1074 * @return array contribution id if success else NULL
1075 * @access public
1076 * static
1077 */
1078 static function checkDuplicateIds($params) {
1079 $dao = new CRM_Contribute_DAO_Contribution();
1080
1081 $clause = array();
1082 $input = array();
1083 foreach ($params as $k => $v) {
1084 if ($v) {
1085 $clause[] = "$k = '$v'";
1086 }
1087 }
1088 $clause = implode(' AND ', $clause);
1089 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1090 $dao = CRM_Core_DAO::executeQuery($query, $input);
1091
1092 while ($dao->fetch()) {
1093 $result = $dao->id;
1094 return $result;
1095 }
1096 return NULL;
1097 }
1098
1099 /**
1100 * Function to get the contribution details for component export
1101 *
1102 * @param int $exportMode export mode
1103 * @param string $componentIds component ids
1104 *
1105 * @return array associated array
1106 *
1107 * @static
1108 * @access public
1109 */
1110 static function getContributionDetails($exportMode, $componentIds) {
1111 $paymentDetails = array();
1112 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1113
1114 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1115 $componentSelect = " civicrm_participant_payment.participant_id id";
1116 $additionalClause = "
1117 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1118 AND civicrm_participant_payment.participant_id {$componentClause} )
1119 ";
1120 }
1121 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1122 $componentSelect = " civicrm_membership_payment.membership_id id";
1123 $additionalClause = "
1124 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1125 AND civicrm_membership_payment.membership_id {$componentClause} )
1126 ";
1127 }
1128 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1129 $componentSelect = " civicrm_pledge_payment.id id";
1130 $additionalClause = "
1131 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1132 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1133 ";
1134 }
1135
1136 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1137 trxn_id, {$componentSelect}
1138 FROM civicrm_contribution
1139 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1140 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1141 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1142 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1143 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1144 AND option_group_contribution_status.id = contribution_status.option_group_id )
1145 {$additionalClause}
1146 ";
1147
1148 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1149
1150 while ($dao->fetch()) {
1151 $paymentDetails[$dao->id] = array(
1152 'total_amount' => $dao->total_amount,
1153 'contribution_status' => $dao->status,
1154 'receive_date' => $dao->receive_date,
1155 'pay_instru' => $dao->payment_instrument,
1156 'trxn_id' => $dao->trxn_id,
1157 );
1158 }
1159
1160 return $paymentDetails;
1161 }
1162
1163 /**
1164 * Function to create address associated with contribution record.
1165 * @param array $params an associated array
1166 * @param int $billingID $billingLocationTypeID
1167 *
1168 * @return address id
1169 * @static
1170 */
1171 static function createAddress(&$params, $billingLocationTypeID) {
1172 $billingFields = array(
1173 'street_address',
1174 'city',
1175 'state_province_id',
1176 'postal_code',
1177 'country_id',
1178 );
1179
1180 //build address array
1181 $addressParams = array();
1182 $addressParams['location_type_id'] = $billingLocationTypeID;
1183 $addressParams['is_billing'] = 1;
1184
1185 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
1186 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
1187 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
1188 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
1189
1190 foreach ($billingFields as $value) {
1191 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
1192 }
1193
1194 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1195
1196 return $address->id;
1197 }
1198
1199 /**
1200 * Delete billing address record related contribution
1201 *
1202 * @param int $contact_id contact id
1203 * @param int $contribution_id contributionId
1204 * @access public
1205 * @static
1206 */
1207 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1208 $clauses = array();
1209 $contactJoin = NULL;
1210
1211 if ($contributionId) {
1212 $clauses[] = "cc.id = {$contributionId}";
1213 }
1214
1215 if ($contactId) {
1216 $clauses[] = "cco.id = {$contactId}";
1217 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1218 }
1219
1220 if (empty($clauses)) {
1221 CRM_Core_Error::fatal();
1222 }
1223
1224 $condition = implode(' OR ', $clauses);
1225
1226 $query = "
1227 SELECT ca.id
1228 FROM civicrm_address ca
1229 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1230 $contactJoin
1231 WHERE $condition
1232 ";
1233 $dao = CRM_Core_DAO::executeQuery($query);
1234
1235 while ($dao->fetch()) {
1236 $params = array('id' => $dao->id);
1237 CRM_Core_BAO_Block::blockDelete('Address', $params);
1238 }
1239 }
1240
1241 /**
1242 * This function check online pending contribution associated w/
1243 * Online Event Registration or Online Membership signup.
1244 *
1245 * @param int $componentId participant/membership id.
1246 * @param string $componentName Event/Membership.
1247 *
1248 * @return $contributionId pending contribution id.
1249 * @static
1250 */
1251 static function checkOnlinePendingContribution($componentId, $componentName) {
1252 $contributionId = NULL;
1253 if (!$componentId ||
1254 !in_array($componentName, array('Event', 'Membership'))
1255 ) {
1256 return $contributionId;
1257 }
1258
1259 if ($componentName == 'Event') {
1260 $idName = 'participant_id';
1261 $componentTable = 'civicrm_participant';
1262 $paymentTable = 'civicrm_participant_payment';
1263 $source = ts('Online Event Registration');
1264 }
1265
1266 if ($componentName == 'Membership') {
1267 $idName = 'membership_id';
1268 $componentTable = 'civicrm_membership';
1269 $paymentTable = 'civicrm_membership_payment';
1270 $source = ts('Online Contribution');
1271 }
1272
1273 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1274
1275 $query = "
1276 SELECT component.id as {$idName},
1277 componentPayment.contribution_id as contribution_id,
1278 contribution.source source,
1279 contribution.contribution_status_id as contribution_status_id,
1280 contribution.is_pay_later as is_pay_later
1281 FROM $componentTable component
1282 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1283 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1284 WHERE component.id = {$componentId}";
1285
1286 $dao = CRM_Core_DAO::executeQuery($query);
1287
1288 while ($dao->fetch()) {
1289 if ($dao->contribution_id &&
1290 $dao->is_pay_later &&
1291 $dao->contribution_status_id == $pendingStatusId &&
1292 strpos($dao->source, $source) !== FALSE
1293 ) {
1294 $contributionId = $dao->contribution_id;
1295 $dao->free();
1296 }
1297 }
1298
1299 return $contributionId;
1300 }
1301
1302 /**
1303 * This function update contribution as well as related objects.
1304 */
1305 static function transitionComponents($params, $processContributionObject = FALSE) {
1306 // get minimum required values.
1307 $contactId = CRM_Utils_Array::value('contact_id', $params);
1308 $componentId = CRM_Utils_Array::value('component_id', $params);
1309 $componentName = CRM_Utils_Array::value('componentName', $params);
1310 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1311 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1312
1313 // if we already processed contribution object pass previous status id.
1314 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1315
1316 $updateResult = array();
1317
1318 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1319
1320 // we process only ( Completed, Cancelled, or Failed ) contributions.
1321 if (!$contributionId ||
1322 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1323 array_search('Cancelled', $contributionStatuses),
1324 array_search('Failed', $contributionStatuses),
1325 ))
1326 ) {
1327 return $updateResult;
1328 }
1329
1330 if (!$componentName || !$componentId) {
1331 // get the related component details.
1332 $componentDetails = self::getComponentDetails($contributionId);
1333 }
1334 else {
1335 $componentDetails['contact_id'] = $contactId;
1336 $componentDetails['component'] = $componentName;
1337
1338 if ($componentName == 'event') {
1339 $componentDetails['participant'] = $componentId;
1340 }
1341 else {
1342 $componentDetails['membership'] = $componentId;
1343 }
1344 }
1345
1346 if (!empty($componentDetails['contact_id'])) {
1347 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1348 $contributionId,
1349 'contact_id'
1350 );
1351 }
1352
1353 // do check for required ids.
1354 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1355 return $updateResult;
1356 }
1357
1358 //now we are ready w/ required ids, start processing.
1359
1360 $baseIPN = new CRM_Core_Payment_BaseIPN();
1361
1362 $input = $ids = $objects = array();
1363
1364 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1365 $ids['contribution'] = $contributionId;
1366 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1367 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1368 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1369 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1370 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1371 $ids['contributionRecur'] = NULL;
1372 $ids['contributionPage'] = NULL;
1373
1374 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1375 CRM_Core_Error::fatal();
1376 }
1377
1378 $memberships = &$objects['membership'];
1379 $participant = &$objects['participant'];
1380 $pledgePayment = &$objects['pledge_payment'];
1381 $contribution = &$objects['contribution'];
1382
1383 if ($pledgePayment) {
1384 $pledgePaymentIDs = array();
1385 foreach ($pledgePayment as $key => $object) {
1386 $pledgePaymentIDs[] = $object->id;
1387 }
1388 $pledgeID = $pledgePayment[0]->pledge_id;
1389 }
1390
1391 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1392
1393 if ($participant) {
1394 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1395 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1396 $participant->id,
1397 'status_id'
1398 );
1399 }
1400 // we might want to process contribution object.
1401 $processContribution = FALSE;
1402 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1403 if (is_array($memberships)) {
1404 foreach ($memberships as $membership) {
1405 if ($membership) {
1406 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1407 $membership->save();
1408
1409 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1410 if ($processContributionObject) {
1411 $processContribution = TRUE;
1412 }
1413 }
1414 }
1415 }
1416
1417 if ($participant) {
1418 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1419 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1420
1421 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1422 if ($processContributionObject) {
1423 $processContribution = TRUE;
1424 }
1425 }
1426
1427 if ($pledgePayment) {
1428 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1429
1430 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1431 if ($processContributionObject) {
1432 $processContribution = TRUE;
1433 }
1434 }
1435 }
1436 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1437 if (is_array($memberships)) {
1438 foreach ($memberships as $membership) {
1439 if ($membership) {
1440 $membership->status_id = array_search('Expired', $membershipStatuses);
1441 $membership->save();
1442
1443 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1444 if ($processContributionObject) {
1445 $processContribution = TRUE;
1446 }
1447 }
1448 }
1449 }
1450 if ($participant) {
1451 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1452 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1453
1454 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1455 if ($processContributionObject) {
1456 $processContribution = TRUE;
1457 }
1458 }
1459
1460 if ($pledgePayment) {
1461 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1462
1463 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1464 if ($processContributionObject) {
1465 $processContribution = TRUE;
1466 }
1467 }
1468 }
1469 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1470
1471 // only pending contribution related object processed.
1472 if ($previousContriStatusId &&
1473 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1474 ) {
1475 // this is case when we already processed contribution object.
1476 return $updateResult;
1477 }
1478 elseif (!$previousContriStatusId &&
1479 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1480 ) {
1481 // this is case when we are going to process contribution object later.
1482 return $updateResult;
1483 }
1484
1485 if (is_array($memberships)) {
1486 foreach ($memberships as $membership) {
1487 if ($membership) {
1488 $format = '%Y%m%d';
1489
1490 //CRM-4523
1491 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1492 $membership->membership_type_id,
1493 $membership->is_test, $membership->id
1494 );
1495
1496 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1497 // this picks up membership type changes during renewals
1498 $sql = "
1499 SELECT membership_type_id
1500 FROM civicrm_membership_log
1501 WHERE membership_id=$membership->id
1502 ORDER BY id DESC
1503 LIMIT 1;";
1504 $dao = new CRM_Core_DAO;
1505 $dao->query($sql);
1506 if ($dao->fetch()) {
1507 if (!empty($dao->membership_type_id)) {
1508 $membership->membership_type_id = $dao->membership_type_id;
1509 $membership->save();
1510 }
1511 }
1512 // else fall back to using current membership type
1513 $dao->free();
1514
1515 // Figure out number of terms
1516 $numterms = 1;
1517 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1518 foreach ($lineitems as $lineitem) {
1519 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1520 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1521
1522 // in case membership_num_terms comes through as null or zero
1523 $numterms = $numterms >= 1 ? $numterms : 1;
1524 break;
1525 }
1526 }
1527
1528 if ($currentMembership) {
1529 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1530 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1531 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1532 }
1533 else {
1534 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
1535 }
1536
1537 //get the status for membership.
1538 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1539 $dates['end_date'],
1540 $dates['join_date'],
1541 'today',
1542 TRUE,
1543 $membership->membership_type_id,
1544 (array) $membership
1545 );
1546
1547 $formattedParams = array(
1548 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1549 array_search('Current', $membershipStatuses)
1550 ),
1551 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1552 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1553 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1554 );
1555
1556 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1557
1558 $membership->copyValues($formattedParams);
1559 $membership->save();
1560
1561 //updating the membership log
1562 $membershipLog = array();
1563 $membershipLog = $formattedParams;
1564 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1565 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1566
1567 $membershipLog['start_date'] = $logStartDate;
1568 $membershipLog['membership_id'] = $membership->id;
1569 $membershipLog['modified_id'] = $membership->contact_id;
1570 $membershipLog['modified_date'] = date('Ymd');
1571 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1572
1573 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1574
1575 //update related Memberships.
1576 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1577
1578 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1579 '%B %E%f, %Y'
1580 );
1581 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1582 if ($processContributionObject) {
1583 $processContribution = TRUE;
1584 }
1585
1586 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1587 }
1588 }
1589 }
1590
1591 if ($participant) {
1592 $updatedStatusId = array_search('Registered', $participantStatuses);
1593 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1594
1595 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1596 if ($processContributionObject) {
1597 $processContribution = TRUE;
1598 }
1599 }
1600
1601 if ($pledgePayment) {
1602 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1603
1604 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1605 if ($processContributionObject) {
1606 $processContribution = TRUE;
1607 }
1608 }
1609 }
1610
1611 // process contribution object.
1612 if ($processContribution) {
1613 $contributionParams = array();
1614 $fields = array(
1615 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1616 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1617 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1618 );
1619 foreach ($fields as $field) {
1620 if (empty($params[$field])) {
1621 continue;
1622 }
1623 $contributionParams[$field] = $params[$field];
1624 }
1625
1626 $ids = array('contribution' => $contributionId);
1627 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1628 }
1629
1630 return $updateResult;
1631 }
1632
1633 /**
1634 * This function returns all contribution related object ids.
1635 */
1636 public static function getComponentDetails($contributionId) {
1637 $componentDetails = $pledgePayment = array();
1638 if (!$contributionId) {
1639 return $componentDetails;
1640 }
1641
1642 $query = "
1643 SELECT c.id as contribution_id,
1644 c.contact_id as contact_id,
1645 mp.membership_id as membership_id,
1646 m.membership_type_id as membership_type_id,
1647 pp.participant_id as participant_id,
1648 p.event_id as event_id,
1649 pgp.id as pledge_payment_id
1650 FROM civicrm_contribution c
1651 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1652 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1653 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1654 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1655 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1656 WHERE c.id = $contributionId";
1657
1658 $dao = CRM_Core_DAO::executeQuery($query);
1659 $componentDetails = array();
1660
1661 while ($dao->fetch()) {
1662 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1663 $componentDetails['contact_id'] = $dao->contact_id;
1664 if ($dao->event_id) {
1665 $componentDetails['event'] = $dao->event_id;
1666 }
1667 if ($dao->participant_id) {
1668 $componentDetails['participant'] = $dao->participant_id;
1669 }
1670 if ($dao->membership_id) {
1671 if (!isset($componentDetails['membership'])) {
1672 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1673 }
1674 $componentDetails['membership'][] = $dao->membership_id;
1675 $componentDetails['membership_type'][] = $dao->membership_type_id;
1676 }
1677 if ($dao->pledge_payment_id) {
1678 $pledgePayment[] = $dao->pledge_payment_id;
1679 }
1680 }
1681
1682 if ($pledgePayment) {
1683 $componentDetails['pledge_payment'] = $pledgePayment;
1684 }
1685
1686 return $componentDetails;
1687 }
1688
1689 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1690 if (!$contactId) {
1691 return 0;
1692 }
1693
1694 $contactContributionsSQL = "
1695 SELECT contribution.id AS id
1696 FROM civicrm_contribution contribution
1697 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1698
1699 $contactSoftCreditContributionsSQL = "
1700 SELECT contribution.id
1701 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1702 ON ( contribution.id = softContribution.contribution_id )
1703 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1704 $query = "SELECT count( x.id ) count FROM ( ";
1705 $query .= $contactContributionsSQL;
1706
1707 if ($includeSoftCredit) {
1708 $query .= " UNION ";
1709 $query .= $contactSoftCreditContributionsSQL;
1710 }
1711
1712 $query .= ") x";
1713
1714 return CRM_Core_DAO::singleValueQuery($query);
1715 }
1716
1717 /**
1718 * Function to get individual id for onbehalf contribution
1719 *
1720 * @param int $contributionId contribution id
1721 * @param int $contributorId contributor id
1722 *
1723 * @return array $ids containing organization id and individual id
1724 * @access public
1725 */
1726 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1727
1728 $ids = array();
1729
1730 if (!$contributionId) {
1731 return $ids;
1732 }
1733
1734 // fetch contributor id if null
1735 if (!$contributorId) {
1736 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1737 $contributionId, 'contact_id'
1738 );
1739 }
1740
1741 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1742 $activityTypeId = array_search('Contribution', $activityTypeIds);
1743
1744 if ($activityTypeId && $contributorId) {
1745 $activityQuery = "
1746 SELECT civicrm_activity_contact.contact_id
1747 FROM civicrm_activity_contact
1748 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1749 WHERE civicrm_activity.activity_type_id = %1
1750 AND civicrm_activity.source_record_id = %2
1751 AND civicrm_activity_contact.record_type_id = %3
1752 ";
1753
1754 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1755 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1756
1757 $params = array(
1758 1 => array($activityTypeId, 'Integer'),
1759 2 => array($contributionId, 'Integer'),
1760 3 => array($sourceID, 'Integer'),
1761 );
1762
1763 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1764
1765 // for on behalf contribution source is individual and contributor is organization
1766 if ($sourceContactId && $sourceContactId != $contributorId) {
1767 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1768 // get rel type id for employee of relation
1769 foreach ($relationshipTypeIds as $id => $typeVals) {
1770 if ($typeVals['name_a_b'] == 'Employee of') {
1771 $relationshipTypeId = $id;
1772 break;
1773 }
1774 }
1775
1776 $rel = new CRM_Contact_DAO_Relationship();
1777 $rel->relationship_type_id = $relationshipTypeId;
1778 $rel->contact_id_a = $sourceContactId;
1779 $rel->contact_id_b = $contributorId;
1780 if ($rel->find(TRUE)) {
1781 $ids['individual_id'] = $rel->contact_id_a;
1782 $ids['organization_id'] = $rel->contact_id_b;
1783 }
1784 }
1785 }
1786
1787 return $ids;
1788 }
1789
1790 /**
1791 * @return array
1792 * @static
1793 */
1794 static function getContributionDates() {
1795 $config = CRM_Core_Config::singleton();
1796 $currentMonth = date('m');
1797 $currentDay = date('d');
1798 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1799 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1800 (int ) $config->fiscalYearStart['d'] > $currentDay
1801 )
1802 ) {
1803 $year = date('Y') - 1;
1804 }
1805 else {
1806 $year = date('Y');
1807 }
1808 $year = array('Y' => $year);
1809 $yearDate = $config->fiscalYearStart;
1810 $yearDate = array_merge($year, $yearDate);
1811 $yearDate = CRM_Utils_Date::format($yearDate);
1812
1813 $monthDate = date('Ym') . '01';
1814
1815 $now = date('Ymd');
1816
1817 return array(
1818 'now' => $now,
1819 'yearDate' => $yearDate,
1820 'monthDate' => $monthDate,
1821 );
1822 }
1823
1824 /*
1825 * Load objects relations to contribution object
1826 * Objects are stored in the $_relatedObjects property
1827 * In the first instance we are just moving functionality from BASEIpn -
1828 * see http://issues.civicrm.org/jira/browse/CRM-9996
1829 *
1830 * @param array $input Input as delivered from Payment Processor
1831 * @param array $ids Ids as Loaded by Payment Processor
1832 * @param boolean $required Is Payment processor / contribution page required
1833 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1834 * Note that the unit test for the BaseIPN class tests this function
1835 */
1836 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1837 if($loadAll){
1838 $ids = array_merge($this->getComponentDetails($this->id),$ids);
1839 if(empty($ids['contact']) && isset($this->contact_id)){
1840 $ids['contact'] = $this->contact_id;
1841 }
1842 }
1843 if (empty($this->_component)) {
1844 if (! empty($ids['event'])) {
1845 $this->_component = 'event';
1846 }
1847 else {
1848 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
1849 }
1850 }
1851 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
1852 $contributionType = new CRM_Financial_BAO_FinancialType();
1853 $contributionType->id = $this->financial_type_id;
1854 if (!$contributionType->find(TRUE)) {
1855 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
1856 }
1857 if (!empty($ids['contact'])) {
1858 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
1859 $this->_relatedObjects['contact']->id = $ids['contact'];
1860 $this->_relatedObjects['contact']->find(TRUE);
1861 }
1862 $this->_relatedObjects['contributionType'] = $contributionType;
1863
1864 if ($this->_component == 'contribute') {
1865 // retrieve the other optional objects first so
1866 // stuff down the line can use this info and do things
1867 // CRM-6056
1868 //in any case get the memberships associated with the contribution
1869 //because we now support multiple memberships w/ price set
1870 // see if there are any other memberships to be considered for same contribution.
1871 $query = "
1872 SELECT membership_id
1873 FROM civicrm_membership_payment
1874 WHERE contribution_id = %1 ";
1875 $params = array(1 => array($this->id, 'Integer'));
1876
1877 $dao = CRM_Core_DAO::executeQuery($query, $params );
1878 while ($dao->fetch()) {
1879 if ($dao->membership_id) {
1880 if (!is_array($ids['membership'])) {
1881 $ids['membership'] = array();
1882 }
1883 $ids['membership'][] = $dao->membership_id;
1884 }
1885 }
1886
1887 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1888 foreach ($ids['membership'] as $id) {
1889 if (!empty($id)) {
1890 $membership = new CRM_Member_BAO_Membership();
1891 $membership->id = $id;
1892 if (!$membership->find(TRUE)) {
1893 throw new Exception("Could not find membership record: $id");
1894 }
1895 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
1896 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
1897 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
1898 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
1899 $membership->free();
1900 }
1901 }
1902 }
1903
1904 if (!empty($ids['pledge_payment'])) {
1905
1906 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1907 if (empty($paymentID)) {
1908 continue;
1909 }
1910 $payment = new CRM_Pledge_BAO_PledgePayment();
1911 $payment->id = $paymentID;
1912 if (!$payment->find(TRUE)) {
1913 throw new Exception("Could not find pledge payment record: " . $paymentID);
1914 }
1915 $this->_relatedObjects['pledge_payment'][] = $payment;
1916 }
1917 }
1918
1919 if (!empty($ids['contributionRecur'])) {
1920 $recur = new CRM_Contribute_BAO_ContributionRecur();
1921 $recur->id = $ids['contributionRecur'];
1922 if (!$recur->find(TRUE)) {
1923 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1924 }
1925 $this->_relatedObjects['contributionRecur'] = &$recur;
1926 //get payment processor id from recur object.
1927 $paymentProcessorID = $recur->payment_processor_id;
1928 }
1929 //for normal contribution get the payment processor id.
1930 if (!$paymentProcessorID) {
1931 if ($this->contribution_page_id) {
1932 // get the payment processor id from contribution page
1933 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1934 $this->contribution_page_id,
1935 'payment_processor'
1936 );
1937 }
1938 //fail to load payment processor id.
1939 elseif (empty($ids['pledge_payment'])) {
1940 $loadObjectSuccess = TRUE;
1941 if ($required) {
1942 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
1943 }
1944 return $loadObjectSuccess;
1945 }
1946 }
1947 }
1948 else {
1949 // we are in event mode
1950 // make sure event exists and is valid
1951 $event = new CRM_Event_BAO_Event();
1952 $event->id = $ids['event'];
1953 if ($ids['event'] &&
1954 !$event->find(TRUE)
1955 ) {
1956 throw new Exception("Could not find event: " . $ids['event']);
1957 }
1958
1959 $this->_relatedObjects['event'] = &$event;
1960
1961 $participant = new CRM_Event_BAO_Participant();
1962 $participant->id = $ids['participant'];
1963 if ($ids['participant'] &&
1964 !$participant->find(TRUE)
1965 ) {
1966 throw new Exception("Could not find participant: " . $ids['participant']);
1967 }
1968 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
1969
1970 $this->_relatedObjects['participant'] = &$participant;
1971
1972 if (!$paymentProcessorID) {
1973 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
1974 }
1975 }
1976
1977 $loadObjectSuccess = TRUE;
1978 if ($paymentProcessorID) {
1979 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
1980 $this->is_test ? 'test' : 'live'
1981 );
1982 $ids['paymentProcessor'] = $paymentProcessorID;
1983 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
1984 }
1985 elseif ($required) {
1986 $loadObjectSuccess = FALSE;
1987 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
1988 }
1989
1990 return $loadObjectSuccess;
1991 }
1992
1993 /*
1994 * Create array of message information - ie. return html version, txt version, to field
1995 *
1996 * @param array $input incoming information
1997 * - is_recur - should this be treated as recurring (not sure why you wouldn't
1998 * just check presence of recur object but maintaining legacy approach
1999 * to be careful)
2000 * @param array $ids IDs of related objects
2001 * @param array $values any values that may have already been compiled by calling process
2002 * This is augmented by values 'gathered' by gatherMessageValues
2003 * @param bool $returnMessageText distinguishes between whether to send message or return
2004 * message text. We are working towards this function ALWAYS returning message text & calling
2005 * function doing emails / pdfs with it
2006 * @return array $messageArray - messages
2007 */
2008 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2009 if (empty($this->_relatedObjects)) {
2010 $this->loadRelatedObjects($input, $ids);
2011 }
2012 if (empty($this->_component)) {
2013 $this->_component = CRM_Utils_Array::value('component', $input);
2014 }
2015
2016 //not really sure what params might be passed in but lets merge em into values
2017 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2018 $template = CRM_Core_Smarty::singleton();
2019 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2020 //what does recur 'mean here - to do with payment processor return functionality but
2021 // what is the importance
2022 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2023 $paymentObject = &CRM_Core_Payment::singleton(
2024 $this->is_test ? 'test' : 'live',
2025 $this->_relatedObjects['paymentProcessor']
2026 );
2027
2028 $entityID = $entity = NULL;
2029 if (isset($ids['contribution'])) {
2030 $entity = 'contribution';
2031 $entityID = $ids['contribution'];
2032 }
2033 if (isset($ids['membership']) && $ids['membership']) {
2034 $entity = 'membership';
2035 $entityID = $ids['membership'];
2036 }
2037
2038 $url = $paymentObject->subscriptionURL($entityID, $entity);
2039 $template->assign('cancelSubscriptionUrl', $url);
2040
2041 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2042 $template->assign('updateSubscriptionBillingUrl', $url);
2043
2044 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2045 $template->assign('updateSubscriptionUrl', $url);
2046
2047 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2048 //direct mode showing billing block, so use directIPN for temporary
2049 $template->assign('contributeMode', 'directIPN');
2050 }
2051 }
2052 // todo remove strtolower - check consistency
2053 if (strtolower($this->_component) == 'event') {
2054 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2055 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2056 );
2057 }
2058 else {
2059 $values['contribution_id'] = $this->id;
2060 if (!empty($ids['related_contact'])) {
2061 $values['related_contact'] = $ids['related_contact'];
2062 if (isset($ids['onbehalf_dupe_alert'])) {
2063 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2064 }
2065 $entityBlock = array(
2066 'contact_id' => $ids['contact'],
2067 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2068 'Home', 'id', 'name'
2069 ),
2070 );
2071 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2072 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2073 }
2074 $isTest = FALSE;
2075 if ($this->is_test) {
2076 $isTest = TRUE;
2077 }
2078 if (!empty($this->_relatedObjects['membership'])) {
2079 foreach ($this->_relatedObjects['membership'] as $membership) {
2080 if ($membership->id) {
2081 $values['membership_id'] = $membership->id;
2082
2083 // need to set the membership values here
2084 $template->assign('membership_assign', 1);
2085 $template->assign('membership_name',
2086 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2087 );
2088 $template->assign('mem_start_date', $membership->start_date);
2089 $template->assign('mem_join_date', $membership->join_date);
2090 $template->assign('mem_end_date', $membership->end_date);
2091 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2092 $template->assign('mem_status', $membership_status);
2093 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2094 $template->assign('is_pay_later', 1);
2095 }
2096
2097 // if separate payment there are two contributions recorded and the
2098 // admin will need to send a receipt for each of them separately.
2099 // we dont link the two in the db (but can potentially infer it if needed)
2100 $template->assign('is_separate_payment', 0);
2101
2102 if ($recur && $paymentObject) {
2103 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2104 $template->assign('cancelSubscriptionUrl', $url);
2105 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2106 $template->assign('updateSubscriptionBillingUrl', $url);
2107 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2108 $template->assign('updateSubscriptionUrl', $url);
2109 }
2110
2111 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2112
2113 return $result;
2114 // otherwise if its about sending emails, continue sending without return, as we
2115 // don't want to exit the loop.
2116 }
2117 }
2118 }
2119 else {
2120 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2121 }
2122 }
2123 }
2124
2125 /*
2126 * Gather values for contribution mail - this function has been created
2127 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2128 * Values related to the contribution in question are gathered
2129 *
2130 * @param array $input input into function (probably from payment processor)
2131 * @param array $ids the set of ids related to the inpurt
2132 *
2133 * @return array $values
2134 *
2135 * NB don't add direct calls to the function as we intend to change the signature
2136 */
2137 function _gatherMessageValues($input, &$values, $ids = array()) {
2138 // set display address of contributor
2139 if ($this->address_id) {
2140 $addressParams = array('id' => $this->address_id);
2141 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2142 $addressDetails = array_values($addressDetails);
2143 $values['address'] = $addressDetails[0]['display'];
2144 }
2145 if ($this->_component == 'contribute') {
2146 if (isset($this->contribution_page_id)) {
2147 CRM_Contribute_BAO_ContributionPage::setValues(
2148 $this->contribution_page_id,
2149 $values
2150 );
2151 if ($this->contribution_page_id) {
2152 // CRM-8254 - override default currency if applicable
2153 $config = CRM_Core_Config::singleton();
2154 $config->defaultCurrency = CRM_Utils_Array::value(
2155 'currency',
2156 $values,
2157 $config->defaultCurrency
2158 );
2159 }
2160 }
2161 // no contribution page -probably back office
2162 else {
2163 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2164 $values['is_email_receipt'] = 1;
2165 $values['title'] = 'Contribution';
2166 }
2167 // set lineItem for contribution
2168 if ($this->id) {
2169 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2170 if (!empty($lineItem)) {
2171 $itemId = key($lineItem);
2172 foreach ($lineItem as &$eachItem) {
2173 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership']) ) {
2174 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2175 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2176 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2177 }
2178 }
2179 $values['lineItem'][0] = $lineItem;
2180 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2181 }
2182 }
2183
2184 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2185 $this->id,
2186 $this->contact_id
2187 );
2188 // if this is onbehalf of contribution then set related contact
2189 if (!empty($relatedContact['individual_id'])) {
2190 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2191 }
2192 }
2193 else {
2194 // event
2195 $eventParams = array(
2196 'id' => $this->_relatedObjects['event']->id,
2197 );
2198 $values['event'] = array();
2199
2200 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2201
2202 //get location details
2203 $locationParams = array(
2204 'entity_id' => $this->_relatedObjects['event']->id,
2205 'entity_table' => 'civicrm_event',
2206 );
2207 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2208
2209 $ufJoinParams = array(
2210 'entity_table' => 'civicrm_event',
2211 'entity_id' => $ids['event'],
2212 'module' => 'CiviEvent',
2213 );
2214
2215 list($custom_pre_id,
2216 $custom_post_ids
2217 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2218
2219 $values['custom_pre_id'] = $custom_pre_id;
2220 $values['custom_post_id'] = $custom_post_ids;
2221
2222 // set lineItem for event contribution
2223 if ($this->id) {
2224 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2225 if (!empty($participantIds)) {
2226 foreach ($participantIds as $pIDs) {
2227 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2228 if (!CRM_Utils_System::isNull($lineItem)) {
2229 $values['lineItem'][] = $lineItem;
2230 }
2231 }
2232 }
2233 }
2234 }
2235
2236 return $values;
2237 }
2238
2239 /**
2240 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2241 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2242 * Note we send directly from this function in some cases because it is only partly refactored
2243 * Don't call this function directly as the signature will change
2244 */
2245 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2246 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2247 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2248 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2249 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2250 $template->assign('useForMember', true);
2251 }
2252 //assign honor infomation to receiptmessage
2253 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2254
2255 if (isset($softRecord['soft_credit'])) {
2256 //if id of contribution page is present
2257 if (!empty($values['id'])) {
2258 $values['honor'] = array(
2259 'honor_profile_values' => array(),
2260 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2261 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2262 );
2263 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2264
2265 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2266 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2267 }
2268 else {
2269 //offline contribution
2270 $softCreditTypes = $softCredits = array();
2271 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2272 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2273 $softCredits[$key] = array(
2274 'Name' => $softCredit['contact_name'],
2275 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency'])
2276 );
2277 }
2278 $template->assign('softCreditTypes', $softCreditTypes);
2279 $template->assign('softCredits', $softCredits);
2280 }
2281 }
2282
2283 $dao = new CRM_Contribute_DAO_ContributionProduct();
2284 $dao->contribution_id = $this->id;
2285 if ($dao->find(TRUE)) {
2286 $premiumId = $dao->product_id;
2287 $template->assign('option', $dao->product_option);
2288
2289 $productDAO = new CRM_Contribute_DAO_Product();
2290 $productDAO->id = $premiumId;
2291 $productDAO->find(TRUE);
2292 $template->assign('selectPremium', TRUE);
2293 $template->assign('product_name', $productDAO->name);
2294 $template->assign('price', $productDAO->price);
2295 $template->assign('sku', $productDAO->sku);
2296 }
2297 $template->assign('title', CRM_Utils_Array::value('title',$values));
2298 $amount = CRM_Utils_Array::value('total_amount', $input,(CRM_Utils_Array::value('amount', $input)),null);
2299 if(empty($amount) && isset($this->total_amount)){
2300 $amount = $this->total_amount;
2301 }
2302 $template->assign('amount', $amount);
2303 // add the new contribution values
2304 if (strtolower($this->_component) == 'contribute') {
2305 //PCP Info
2306 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2307 $softDAO->contribution_id = $this->id;
2308 if ($softDAO->find(TRUE)) {
2309 $template->assign('pcpBlock', TRUE);
2310 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2311 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2312 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2313
2314 //assign the pcp page title for email subject
2315 $pcpDAO = new CRM_PCP_DAO_PCP();
2316 $pcpDAO->id = $softDAO->pcp_id;
2317 if ($pcpDAO->find(TRUE)) {
2318 $template->assign('title', $pcpDAO->title);
2319 }
2320 }
2321 }
2322
2323 if ($this->financial_type_id) {
2324 $values['financial_type_id'] = $this->financial_type_id;
2325 }
2326
2327
2328 $template->assign('trxn_id', $this->trxn_id);
2329 $template->assign('receive_date',
2330 CRM_Utils_Date::mysqlToIso($this->receive_date)
2331 );
2332 $template->assign('contributeMode', 'notify');
2333 $template->assign('action', $this->is_test ? 1024 : 1);
2334 $template->assign('receipt_text',
2335 CRM_Utils_Array::value('receipt_text',
2336 $values
2337 )
2338 );
2339 $template->assign('is_monetary', 1);
2340 $template->assign('is_recur', (bool) $recur);
2341 $template->assign('currency', $this->currency);
2342 $template->assign('address', CRM_Utils_Address::format($input));
2343 if ($this->_component == 'event') {
2344 $template->assign('title', $values['event']['title']);
2345 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2346 $viewRoles = array();
2347 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2348 $viewRoles[] = $participantRoles[$v];
2349 }
2350 $values['event']['participant_role'] = implode(', ', $viewRoles);
2351 $template->assign('event', $values['event']);
2352 $template->assign('location', $values['location']);
2353 $template->assign('customPre', $values['custom_pre_id']);
2354 $template->assign('customPost', $values['custom_post_id']);
2355
2356 $isTest = FALSE;
2357 if ($this->_relatedObjects['participant']->is_test) {
2358 $isTest = TRUE;
2359 }
2360
2361 $values['params'] = array();
2362 //to get email of primary participant.
2363 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2364 $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount);
2365 //build an array of cId/pId of participants
2366 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2367 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2368 //send receipt to additional participant if exists
2369 if (count($additionalIDs)) {
2370 $template->assign('isPrimary', 0);
2371 $template->assign('customProfile', NULL);
2372 //set additionalParticipant true
2373 $values['params']['additionalParticipant'] = TRUE;
2374 foreach ($additionalIDs as $pId => $cId) {
2375 $amount = array();
2376 //to change the status pending to completed
2377 $additional = new CRM_Event_DAO_Participant();
2378 $additional->id = $pId;
2379 $additional->contact_id = $cId;
2380 $additional->find(TRUE);
2381 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2382 $additional->status_id = 1;
2383 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2384 //if additional participant dont have email
2385 //use display name.
2386 if (!$additionalParticipantInfo) {
2387 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2388 }
2389 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2390 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
2391 $additional->save();
2392 $additional->free();
2393 $template->assign('amount', $amount);
2394 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2395 }
2396 }
2397
2398 //build an array of custom profile and assigning it to template
2399 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2400
2401 if (count($customProfile)) {
2402 $template->assign('customProfile', $customProfile);
2403 }
2404
2405 // for primary contact
2406 $values['params']['additionalParticipant'] = FALSE;
2407 $template->assign('isPrimary', 1);
2408 $template->assign('amount', $primaryAmount);
2409 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2410 if ($this->payment_instrument_id) {
2411 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2412 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2413 }
2414 // carry paylater, since we did not created billing,
2415 // so need to pull email from primary location, CRM-4395
2416 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2417 }
2418 return $template;
2419 }
2420
2421 /**
2422 * Function to check whether payment processor supports
2423 * cancellation of contribution subscription
2424 *
2425 * @param int $contributionId contribution id
2426 *
2427 * @return boolean
2428 * @access public
2429 * @static
2430 */
2431 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2432 $cacheKeyString = "$contributionId";
2433 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2434
2435 static $supportsCancel = array();
2436
2437 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2438 $supportsCancel[$cacheKeyString] = FALSE;
2439 $isCancelled = FALSE;
2440
2441 if ($isNotCancelled) {
2442 $isCancelled = self::isSubscriptionCancelled($contributionId);
2443 }
2444
2445 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2446 if (!empty($paymentObject)) {
2447 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2448 }
2449 }
2450 return $supportsCancel[$cacheKeyString];
2451 }
2452
2453 /**
2454 * Function to check whether subscription is already cancelled
2455 *
2456 * @param int $contributionId contribution id
2457 *
2458 * @return string $status contribution status
2459 * @access public
2460 * @static
2461 */
2462 static function isSubscriptionCancelled($contributionId) {
2463 $sql = "
2464 SELECT cr.contribution_status_id
2465 FROM civicrm_contribution_recur cr
2466 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2467 WHERE con.id = %1 LIMIT 1";
2468 $params = array(1 => array($contributionId, 'Integer'));
2469 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2470 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2471 if ($status == 'Cancelled') {
2472 return TRUE;
2473 }
2474 return FALSE;
2475 }
2476
2477 /**
2478 * Function to create all financial accounts entry
2479 *
2480 * @param array $params contribution object, line item array and params for trxn
2481 *
2482 *
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 * @access public
2754 * @static
2755 */
2756 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2757 $itemAmount = $trxnID = NULL;
2758 //get all the statuses
2759 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2760 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2761 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2762 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2763 && $context == 'changePaymentInstrument') {
2764 return;
2765 }
2766 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2767 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2768 }
2769 if ($context == 'changedStatus') {
2770 //get all the statuses
2771 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2772
2773 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2774 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2775 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))) {
2776 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2777 }
2778 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2779 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) {
2780 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2781 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2782 $params['trxnParams']['to_financial_account_id'] = NULL;
2783 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2784 }
2785 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2786 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2787 $financialTypeID, $relationTypeId);
2788 }
2789 $itemAmount = $params['trxnParams']['total_amount'];
2790 }
2791 elseif ($context == 'changePaymentInstrument') {
2792 if ($params['trxnParams']['total_amount'] < 0) {
2793 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2794 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2795 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2796 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2797 }
2798 }
2799 else {
2800 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2801 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2802 }
2803 }
2804 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2805 $params['entity_id'] = $trxn->id;
2806
2807 if ($context == 'changedStatus') {
2808 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2809 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2810 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))) {
2811 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2812 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2813
2814 $entityParams = array(
2815 'entity_table' => 'civicrm_financial_item',
2816 'financial_trxn_id' => $trxn->id,
2817 );
2818 foreach ($params['line_item'] as $fieldId => $fields) {
2819 foreach ($fields as $fieldValueId => $fieldValues) {
2820 $fparams = array(
2821 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2822 2 => array($fieldValues['id'], 'Integer'),
2823 );
2824 CRM_Core_DAO::executeQuery($query, $fparams);
2825 $fparams = array(
2826 1 => array($fieldValues['id'], 'Integer'),
2827 );
2828 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
2829 while ($financialItem->fetch()) {
2830 $entityParams['entity_id'] = $financialItem->id;
2831 $entityParams['amount'] = $financialItem->amount;
2832 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
2833 }
2834 }
2835 }
2836 return;
2837 }
2838 }
2839 if ($context != 'changePaymentInstrument') {
2840 $itemParams['entity_table'] = 'civicrm_line_item';
2841 $trxnIds['id'] = $params['entity_id'];
2842 foreach ($params['line_item'] as $fieldId => $fields) {
2843 foreach ($fields as $fieldValueId => $fieldValues) {
2844 $prevParams['entity_id'] = $fieldValues['id'];
2845 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
2846
2847 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
2848 if ($params['contribution']->receive_date) {
2849 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
2850 }
2851
2852 $financialAccount = $prevfinancialItem->financial_account_id;
2853 if (!empty($params['financial_account_id'])) {
2854 $financialAccount = $params['financial_account_id'];
2855 }
2856
2857 $currency = $params['prevContribution']->currency;
2858 if ($params['contribution']->currency) {
2859 $currency = $params['contribution']->currency;
2860 }
2861 if (!empty($params['is_quick_config'])) {
2862 $amount = $itemAmount;
2863 if (!$amount) {
2864 $amount = $params['total_amount'];
2865 }
2866 }
2867 else {
2868 $diff = 1;
2869 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2870 $diff = -1;
2871 }
2872 $amount = $diff * $fieldValues['line_total'];
2873 }
2874
2875 $itemParams = array(
2876 'transaction_date' => $receiveDate,
2877 'contact_id' => $params['prevContribution']->contact_id,
2878 'currency' => $currency,
2879 'amount' => $amount,
2880 'description' => $prevfinancialItem->description,
2881 'status_id' => $prevfinancialItem->status_id,
2882 'financial_account_id' => $financialAccount,
2883 'entity_table' => 'civicrm_line_item',
2884 'entity_id' => $fieldValues['id']
2885 );
2886 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
2887 }
2888 }
2889 }
2890 }
2891
2892 /**
2893 * Function to check status validation on update of a contribution
2894 *
2895 * @param array $values previous form values before submit
2896 *
2897 * @param array $fields the input form values
2898 *
2899 * @param array $errors list of errors
2900 *
2901 * @access public
2902 * @static
2903 */
2904 static function checkStatusValidation($values, &$fields, &$errors) {
2905 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
2906 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2907 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2908 return FALSE;
2909 }
2910 }
2911 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2912 $checkStatus = array(
2913 'Cancelled' => array('Completed', 'Refunded'),
2914 'Completed' => array('Cancelled', 'Refunded'),
2915 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2916 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
2917 'Refunded' => array('Cancelled', 'Completed')
2918 );
2919
2920 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2921 $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']]));
2922 }
2923 }
2924
2925 /**
2926 * Function to delete contribution of contact
2927 *
2928 * CRM-12155
2929 *
2930 * @param integer $contactId contact id
2931 *
2932 * @access public
2933 * @static
2934 */
2935 static function deleteContactContribution($contactId) {
2936 $contribution = new CRM_Contribute_DAO_Contribution();
2937 $contribution->contact_id = $contactId;
2938 $contribution->find();
2939 while ($contribution->fetch()) {
2940 self::deleteContribution($contribution->id);
2941 }
2942 }
2943
2944 /**
2945 * Get options for a given contribution field.
2946 * @see CRM_Core_DAO::buildOptions
2947 *
2948 * @param String $fieldName
2949 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2950 * @param Array $props: whatever is known about this dao object
2951 */
2952 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2953 $className = __CLASS__;
2954 $params = array();
2955 switch ($fieldName) {
2956 // This field is not part of this object but the api supports it
2957 case 'payment_processor':
2958 $className = 'CRM_Contribute_BAO_ContributionPage';
2959 // Filter results by contribution page
2960 if (!empty($props['contribution_page_id'])) {
2961 $page = civicrm_api('contribution_page', 'getsingle', array(
2962 'version' => 3,
2963 'id' => ($props['contribution_page_id'])
2964 ));
2965 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
2966 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2967 }
2968 }
2969 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
2970 }
2971
2972 /**
2973 * Function to validate financial type
2974 *
2975 * CRM-13231
2976 *
2977 * @param integer $financialTypeId Financial Type id
2978 *
2979 * @access public
2980 * @static
2981 */
2982 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2983 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2984 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
2985
2986 if (!$financialAccount) {
2987 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
2988 }
2989 return FALSE;
2990 }
2991
2992
2993 /*
2994 * Function to record additional payment for partial and refund contributions
2995 *
2996 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
2997 * @param array $trxnData : to take user provided input of transaction details.
2998 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
2999 */
3000 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3001 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3002 $getInfoOf['id'] = $contributionId;
3003 $defaults = array();
3004 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3005
3006 if ($paymentType == 'owed') {
3007 // build params for recording financial trxn entry
3008 $params['contribution'] = $contributionDAO;
3009 $params = array_merge($defaults, $params);
3010 $params['skipLineItem'] = TRUE;
3011 $params['partial_payment_total'] = $contributionDAO->total_amount;
3012 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3013 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3014
3015 // record the entry
3016 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3017 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3018 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3019
3020 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3021 $trxnId = $trxnId['trxn_id'];
3022
3023 // update statuses
3024 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3025 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3026 FROM civicrm_financial_trxn ft
3027 LEFT JOIN civicrm_entity_financial_trxn eft
3028 ON (ft.id = eft.financial_trxn_id)
3029 WHERE eft.entity_table = 'civicrm_contribution'
3030 AND eft.entity_id = {$contributionId}
3031 AND ft.to_financial_account_id != {$toFinancialAccount}
3032 AND ft.status_id = {$statusId}
3033 ";
3034 $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
3035
3036 // update statuses
3037 if ($contributionDAO->total_amount == $sumOfPayments) {
3038 // update contribution status
3039 $contributionUpdate['id'] = $contributionId;
3040 $contributionUpdate['contribution_status_id'] = $statusId;
3041 $contributionUpdate['skipLineItem'] = TRUE;
3042 // note : not using the self::add method,
3043 // the reason because it performs 'status change' related code execution for financial records
3044 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3045 // are coded below i.e. just updating financial_item status to 'Paid'
3046 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3047
3048 if ($participantId) {
3049 // update participant status
3050 $participantUpdate['id'] = $participantId;
3051 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3052 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3053 CRM_Event_BAO_Participant::add($participantUpdate);
3054 }
3055
3056 // update financial item statuses
3057 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3058 $paidStatus = array_search('Paid', $financialItemStatus);
3059
3060 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3061 $sqlFinancialItemUpdate = "
3062 UPDATE civicrm_financial_item fi
3063 LEFT JOIN civicrm_entity_financial_trxn eft
3064 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3065 SET status_id = {$paidStatus}
3066 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3067 ";
3068 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3069 }
3070 }
3071 elseif ($paymentType == 'refund') {
3072 // build params for recording financial trxn entry
3073 $params['contribution'] = $contributionDAO;
3074 $params = array_merge($defaults, $params);
3075 $params['skipLineItem'] = TRUE;
3076 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3077 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3078
3079 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3080 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3081 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3082 // record the entry
3083 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3084
3085 // note : not using the self::add method,
3086 // the reason because it performs 'status change' related code execution for financial records
3087 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3088 // are coded below i.e. just updating financial_item status to 'Paid'
3089 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3090
3091 // add financial item entry
3092 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3093 $getLine['entity_id'] = $contributionDAO->id;
3094 $getLine['entity_table'] = 'civicrm_contribution';
3095 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
3096 $addFinancialEntry = array(
3097 'transaction_date' => $financialTrxn->trxn_date,
3098 'contact_id' => $contributionDAO->contact_id,
3099 'amount' => $financialTrxn->total_amount,
3100 'status_id' => array_search('Paid', $financialItemStatus),
3101 'entity_id' => $lineItemId->id,
3102 'entity_table' => 'civicrm_line_item'
3103 );
3104 $trxnIds['id'] = $financialTrxn->id;
3105 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3106
3107 if ($participantId) {
3108 // update participant status
3109 $participantUpdate['id'] = $participantId;
3110 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3111 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3112 CRM_Event_BAO_Participant::add($participantUpdate);
3113 }
3114 }
3115
3116 // activity creation
3117 if (!empty($financialTrxn)) {
3118 if ($participantId) {
3119 $inputParams['id'] = $participantId;
3120 $values = array();
3121 $ids = array();
3122 $component = 'event';
3123 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3124 $entityObj = $entityObj[$participantId];
3125 }
3126 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3127
3128 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3129 }
3130 return $financialTrxn;
3131 }
3132
3133 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3134 if ($component == 'event') {
3135 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3136 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3137 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3138 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3139 $targetCid = $entityObj->contact_id;
3140 // source record id would be the contribution id
3141 $srcRecId = $contributionId;
3142 }
3143
3144 // activity params
3145 $activityParams = array(
3146 'source_contact_id' => $targetCid,
3147 'source_record_id' => $srcRecId,
3148 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3149 $activityType,
3150 'name'
3151 ),
3152 'subject' => $subject,
3153 'activity_date_time' => $date,
3154 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3155 'Completed',
3156 'name'
3157 ),
3158 'skipRecentView' => TRUE,
3159 );
3160
3161 // create activity with target contacts
3162 $session = CRM_Core_Session::singleton();
3163 $id = $session->get('userID');
3164 if ($id) {
3165 $activityParams['source_contact_id'] = $id;
3166 $activityParams['target_contact_id'][] = $targetCid;
3167 }
3168 CRM_Activity_BAO_Activity::create($activityParams);
3169 }
3170
3171 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3172 if ($component == 'event') {
3173 $entity = 'participant';
3174 $entityTable = 'civicrm_participant';
3175 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3176 }
3177 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3178 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3179 $isBalance = NULL;
3180 if ($baseTrxnId) {
3181 $isBalance = TRUE;
3182 }
3183 else {
3184 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3185 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3186 $isBalance = FALSE;
3187 }
3188 if (empty($total) || $usingLineTotal) {
3189 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3190 }
3191 else {
3192 $baseTrxnId = $total['trxn_id'];
3193 $total = $total['total_amount'];
3194 }
3195
3196 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
3197 $info['total'] = $total;
3198 $info['paid'] = $total - $paymentBalance;
3199 $info['balance'] = $paymentBalance;
3200 $info['id'] = $id;
3201 $info['component'] = $component;
3202 $rows = array();
3203 if ($getTrxnInfo && $baseTrxnId) {
3204 $sql = "
3205 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3206 FROM civicrm_contribution con
3207 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3208 LEFT JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3209 WHERE con.id = {$contributionId}
3210 ";
3211
3212 // conditioned WHERE clause
3213 if ($isBalance) {
3214 // if balance trxn exists don't include details of it in transaction info
3215 $sql .= " AND ft.id != {$baseTrxnId} ";
3216 }
3217 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3218
3219 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3220 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
3221 while($resultDAO->fetch()) {
3222 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3223 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3224 $val = array(
3225 'total_amount' => $resultDAO->total_amount,
3226 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
3227 'payment_instrument' => $paidByLabel,
3228 'receive_date' => $resultDAO->trxn_date,
3229 'trxn_id' => $resultDAO->trxn_id,
3230 'status' => $statuses[$resultDAO->status_id],
3231 );
3232 if ($paidByName == 'Check') {
3233 $val['check_number'] = $resultDAO->check_number;
3234 }
3235 $rows[] = $val;
3236 }
3237 $info['transaction'] = $rows;
3238 }
3239 return $info;
3240 }
3241 }