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