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