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