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