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