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