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