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