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