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