Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-05-01-14-11-47
[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 contributions for contribution record.
1293 * @param array $params an associated array
1294 * @param boolean $all include PCP data
1295 *
1296 * @return array of soft contribution ids, amounts, and associated contact ids
1297 * @static
1298 */
1299 static function getSoftContribution($params, $all = FALSE) {
1300 $cs = new CRM_Contribute_DAO_ContributionSoft();
1301 $cs->copyValues($params);
1302 $softContribution = array();
1303 $cs->find();
1304 if ($cs->N > 0) {
1305 while ($cs->fetch()) {
1306
1307 if ($all) {
1308 foreach (array(
1309 'pcp_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $key => $val) {
1310 $softContribution[$val] = $cs->$val;
1311 }
1312 }
1313 $softContribution[$cs->id]['soft_credit_to'] = $cs->contact_id;
1314 $softContribution[$cs->id]['soft_credit_id'] = $cs->id;
1315 $softContribution[$cs->id]['soft_credit_amount'] = $cs->amount;
1316 }
1317 }
1318 return $softContribution;
1319 }
1320
1321 /**
1322 * Function to retrieve the list of soft contributons for given contact.
1323 * @param int $contact_id contact id
1324 *
1325 * @return array
1326 * @static
1327 */
1328 static function getSoftContributionList($contact_id, $isTest = 0) {
1329 $query = "
1330 SELECT ccs.id, ccs.amount as amount,
1331 ccs.contribution_id,
1332 ccs.pcp_id,
1333 ccs.pcp_display_in_roll,
1334 ccs.pcp_roll_nickname,
1335 ccs.pcp_personal_note,
1336 cc.receive_date,
1337 cc.contact_id as contributor_id,
1338 cc.contribution_status_id as contribution_status_id,
1339 cp.title as pcp_title,
1340 cc.currency,
1341 contact.display_name,
1342 cct.name as contributionType
1343 FROM civicrm_contribution_soft ccs
1344 LEFT JOIN civicrm_contribution cc
1345 ON ccs.contribution_id = cc.id
1346 LEFT JOIN civicrm_pcp cp
1347 ON ccs.pcp_id = cp.id
1348 LEFT JOIN civicrm_contact contact
1349 ON ccs.contribution_id = cc.id AND
1350 cc.contact_id = contact.id
1351 LEFT JOIN civicrm_financial_type cct
1352 ON cc.financial_type_id = cct.id
1353 WHERE cc.is_test = %2 AND ccs.contact_id = %1
1354 ORDER BY cc.receive_date DESC";
1355
1356 $params = array(1 => array($contact_id, 'Integer'),
1357 2 => array($isTest, 'Integer'));
1358 $cs = CRM_Core_DAO::executeQuery($query, $params);
1359 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
1360 $result = array();
1361 while ($cs->fetch()) {
1362 $result[$cs->id]['amount'] = $cs->amount;
1363 $result[$cs->id]['currency'] = $cs->currency;
1364 $result[$cs->id]['contributor_id'] = $cs->contributor_id;
1365 $result[$cs->id]['contribution_id'] = $cs->contribution_id;
1366 $result[$cs->id]['contributor_name'] = $cs->display_name;
1367 $result[$cs->id]['financial_type'] = $cs->contributionType;
1368 $result[$cs->id]['receive_date'] = $cs->receive_date;
1369 $result[$cs->id]['pcp_id'] = $cs->pcp_id;
1370 $result[$cs->id]['pcp_title'] = $cs->pcp_title;
1371 $result[$cs->id]['pcp_display_in_roll'] = $cs->pcp_display_in_roll;
1372 $result[$cs->id]['pcp_roll_nickname'] = $cs->pcp_roll_nickname;
1373 $result[$cs->id]['pcp_personal_note'] = $cs->pcp_personal_note;
1374 $result[$cs->id]['contribution_status'] = CRM_Utils_Array::value($cs->contribution_status_id, $contributionStatus);
1375
1376 if ($isTest) {
1377 $result[$cs->id]['contribution_status'] = $result[$cs->id]['contribution_status'] . '<br /> (test)';
1378 }
1379 }
1380 return $result;
1381 }
1382
1383 static function getSoftContributionTotals($contact_id, $isTest = 0) {
1384 $query = "
1385 SELECT SUM(amount) as amount,
1386 AVG(total_amount) as average,
1387 cc.currency
1388 FROM civicrm_contribution_soft ccs
1389 LEFT JOIN civicrm_contribution cc
1390 ON ccs.contribution_id = cc.id
1391 WHERE cc.is_test = %2 AND
1392 ccs.contact_id = %1
1393 GROUP BY currency ";
1394
1395 $params = array(1 => array($contact_id, 'Integer'),
1396 2 => array($isTest, 'Integer'));
1397
1398 $cs = CRM_Core_DAO::executeQuery($query, $params);
1399
1400 $count = 0;
1401 $amount = $average = array();
1402
1403 while ($cs->fetch()) {
1404 if ($cs->amount > 0) {
1405 $count++;
1406 $amount[] = $cs->amount;
1407 $average[] = $cs->average;
1408 $currency[] = $cs->currency;
1409 }
1410 }
1411
1412 if ($count > 0) {
1413 return array(implode(',&nbsp;', $amount),
1414 implode(',&nbsp;', $average),
1415 implode(',&nbsp;', $currency),
1416 );
1417 }
1418 return array(0, 0);
1419 }
1420
1421 /**
1422 * Delete billing address record related contribution
1423 *
1424 * @param int $contact_id contact id
1425 * @param int $contribution_id contributionId
1426 * @access public
1427 * @static
1428 */
1429 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1430 $clauses = array();
1431 $contactJoin = NULL;
1432
1433 if ($contributionId) {
1434 $clauses[] = "cc.id = {$contributionId}";
1435 }
1436
1437 if ($contactId) {
1438 $clauses[] = "cco.id = {$contactId}";
1439 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1440 }
1441
1442 if (empty($clauses)) {
1443 CRM_Core_Error::fatal();
1444 }
1445
1446 $condition = implode(' OR ', $clauses);
1447
1448 $query = "
1449 SELECT ca.id
1450 FROM civicrm_address ca
1451 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1452 $contactJoin
1453 WHERE $condition
1454 ";
1455 $dao = CRM_Core_DAO::executeQuery($query);
1456
1457 while ($dao->fetch()) {
1458 $params = array('id' => $dao->id);
1459 CRM_Core_BAO_Block::blockDelete('Address', $params);
1460 }
1461 }
1462
1463 /**
1464 * This function check online pending contribution associated w/
1465 * Online Event Registration or Online Membership signup.
1466 *
1467 * @param int $componentId participant/membership id.
1468 * @param string $componentName Event/Membership.
1469 *
1470 * @return $contributionId pending contribution id.
1471 * @static
1472 */
1473 static function checkOnlinePendingContribution($componentId, $componentName) {
1474 $contributionId = NULL;
1475 if (!$componentId ||
1476 !in_array($componentName, array('Event', 'Membership'))
1477 ) {
1478 return $contributionId;
1479 }
1480
1481 if ($componentName == 'Event') {
1482 $idName = 'participant_id';
1483 $componentTable = 'civicrm_participant';
1484 $paymentTable = 'civicrm_participant_payment';
1485 $source = ts('Online Event Registration');
1486 }
1487
1488 if ($componentName == 'Membership') {
1489 $idName = 'membership_id';
1490 $componentTable = 'civicrm_membership';
1491 $paymentTable = 'civicrm_membership_payment';
1492 $source = ts('Online Contribution');
1493 }
1494
1495 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1496
1497 $query = "
1498 SELECT component.id as {$idName},
1499 componentPayment.contribution_id as contribution_id,
1500 contribution.source source,
1501 contribution.contribution_status_id as contribution_status_id,
1502 contribution.is_pay_later as is_pay_later
1503 FROM $componentTable component
1504 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1505 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1506 WHERE component.id = {$componentId}";
1507
1508 $dao = CRM_Core_DAO::executeQuery($query);
1509
1510 while ($dao->fetch()) {
1511 if ($dao->contribution_id &&
1512 $dao->is_pay_later &&
1513 $dao->contribution_status_id == $pendingStatusId &&
1514 strpos($dao->source, $source) !== FALSE
1515 ) {
1516 $contributionId = $dao->contribution_id;
1517 $dao->free();
1518 }
1519 }
1520
1521 return $contributionId;
1522 }
1523
1524 /**
1525 * This function update contribution as well as related objects.
1526 */
1527 function transitionComponents($params, $processContributionObject = FALSE) {
1528 // get minimum required values.
1529 $contactId = CRM_Utils_Array::value('contact_id', $params);
1530 $componentId = CRM_Utils_Array::value('component_id', $params);
1531 $componentName = CRM_Utils_Array::value('componentName', $params);
1532 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1533 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1534
1535 // if we already processed contribution object pass previous status id.
1536 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1537
1538 $updateResult = array();
1539
1540 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1541
1542 // we process only ( Completed, Cancelled, or Failed ) contributions.
1543 if (!$contributionId ||
1544 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1545 array_search('Cancelled', $contributionStatuses),
1546 array_search('Failed', $contributionStatuses),
1547 ))
1548 ) {
1549 return $updateResult;
1550 }
1551
1552 if (!$componentName || !$componentId) {
1553 // get the related component details.
1554 $componentDetails = self::getComponentDetails($contributionId);
1555 }
1556 else {
1557 $componentDetails['contact_id'] = $contactId;
1558 $componentDetails['component'] = $componentName;
1559
1560 if ($componentName == 'event') {
1561 $componentDetails['participant'] = $componentId;
1562 }
1563 else {
1564 $componentDetails['membership'] = $componentId;
1565 }
1566 }
1567
1568 if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
1569 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1570 $contributionId,
1571 'contact_id'
1572 );
1573 }
1574
1575 // do check for required ids.
1576 if (!CRM_Utils_Array::value('membership', $componentDetails) &&
1577 !CRM_Utils_Array::value('participant', $componentDetails) &&
1578 !CRM_Utils_Array::value('pledge_payment', $componentDetails) ||
1579 !CRM_Utils_Array::value('contact_id', $componentDetails)
1580 ) {
1581 return $updateResult;
1582 }
1583
1584 //now we are ready w/ required ids, start processing.
1585
1586 $baseIPN = new CRM_Core_Payment_BaseIPN();
1587
1588 $input = $ids = $objects = array();
1589
1590 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1591 $ids['contribution'] = $contributionId;
1592 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1593 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1594 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1595 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1596 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1597 $ids['contributionRecur'] = NULL;
1598 $ids['contributionPage'] = NULL;
1599
1600 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1601 CRM_Core_Error::fatal();
1602 }
1603
1604 $memberships = &$objects['membership'];
1605 $participant = &$objects['participant'];
1606 $pledgePayment = &$objects['pledge_payment'];
1607 $contribution = &$objects['contribution'];
1608
1609 if ($pledgePayment) {
1610 $pledgePaymentIDs = array();
1611 foreach ($pledgePayment as $key => $object) {
1612 $pledgePaymentIDs[] = $object->id;
1613 }
1614 $pledgeID = $pledgePayment[0]->pledge_id;
1615 }
1616
1617
1618 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1619
1620 if ($participant) {
1621 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1622 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1623 $participant->id,
1624 'status_id'
1625 );
1626 }
1627 // we might want to process contribution object.
1628 $processContribution = FALSE;
1629 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1630 if (is_array($memberships)) {
1631 foreach ($memberships as $membership) {
1632 if ($membership) {
1633 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1634 $membership->save();
1635
1636 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1637 if ($processContributionObject) {
1638 $processContribution = TRUE;
1639 }
1640 }
1641 }
1642 }
1643
1644 if ($participant) {
1645 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1646 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1647
1648 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1649 if ($processContributionObject) {
1650 $processContribution = TRUE;
1651 }
1652 }
1653
1654 if ($pledgePayment) {
1655 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1656
1657 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1658 if ($processContributionObject) {
1659 $processContribution = TRUE;
1660 }
1661 }
1662 }
1663 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1664 if (is_array($memberships)) {
1665 foreach ($memberships as $membership) {
1666 if ($membership) {
1667 $membership->status_id = array_search('Expired', $membershipStatuses);
1668 $membership->save();
1669
1670 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1671 if ($processContributionObject) {
1672 $processContribution = TRUE;
1673 }
1674 }
1675 }
1676 }
1677 if ($participant) {
1678 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1679 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1680
1681 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1682 if ($processContributionObject) {
1683 $processContribution = TRUE;
1684 }
1685 }
1686
1687 if ($pledgePayment) {
1688 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1689
1690 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1691 if ($processContributionObject) {
1692 $processContribution = TRUE;
1693 }
1694 }
1695 }
1696 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1697
1698 // only pending contribution related object processed.
1699 if ($previousContriStatusId &&
1700 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1701 ) {
1702 // this is case when we already processed contribution object.
1703 return $updateResult;
1704 }
1705 elseif (!$previousContriStatusId &&
1706 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1707 ) {
1708 // this is case when we are going to process contribution object later.
1709 return $updateResult;
1710 }
1711
1712 if (is_array($memberships)) {
1713 foreach ($memberships as $membership) {
1714 if ($membership) {
1715 $format = '%Y%m%d';
1716
1717 //CRM-4523
1718 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1719 $membership->membership_type_id,
1720 $membership->is_test, $membership->id
1721 );
1722
1723 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1724 // this picks up membership type changes during renewals
1725 $sql = "
1726 SELECT membership_type_id
1727 FROM civicrm_membership_log
1728 WHERE membership_id=$membership->id
1729 ORDER BY id DESC
1730 LIMIT 1;";
1731 $dao = new CRM_Core_DAO;
1732 $dao->query($sql);
1733 if ($dao->fetch()) {
1734 if (!empty($dao->membership_type_id)) {
1735 $membership->membership_type_id = $dao->membership_type_id;
1736 $membership->save();
1737 }
1738 }
1739 // else fall back to using current membership type
1740 $dao->free();
1741
1742 // Figure out number of terms
1743 $numterms = 1;
1744 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1745 foreach ($lineitems as $lineitem) {
1746 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1747 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1748
1749 // in case membership_num_terms comes through as null or zero
1750 $numterms = $numterms >= 1 ? $numterms : 1;
1751 break;
1752 }
1753 }
1754
1755 if ($currentMembership) {
1756 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1757 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1758 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1759 }
1760 else {
1761 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, null, null, null, $numterms);
1762 }
1763
1764 //get the status for membership.
1765 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1766 $dates['end_date'],
1767 $dates['join_date'],
1768 'today',
1769 TRUE
1770 );
1771
1772 $formatedParams = array(
1773 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1774 array_search('Current', $membershipStatuses)
1775 ),
1776 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1777 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1778 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1779 );
1780
1781 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formatedParams);
1782
1783 $membership->copyValues($formatedParams);
1784 $membership->save();
1785
1786 //updating the membership log
1787 $membershipLog = array();
1788 $membershipLog = $formatedParams;
1789 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1790 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
1791
1792 $membershipLog['start_date'] = $logStartDate;
1793 $membershipLog['membership_id'] = $membership->id;
1794 $membershipLog['modified_id'] = $membership->contact_id;
1795 $membershipLog['modified_date'] = date('Ymd');
1796 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1797
1798 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1799
1800 //update related Memberships.
1801 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
1802
1803 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1804 '%B %E%f, %Y'
1805 );
1806 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1807 if ($processContributionObject) {
1808 $processContribution = TRUE;
1809 }
1810
1811 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1812 }
1813 }
1814 }
1815
1816 if ($participant) {
1817 $updatedStatusId = array_search('Registered', $participantStatuses);
1818 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1819
1820 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1821 if ($processContributionObject) {
1822 $processContribution = TRUE;
1823 }
1824 }
1825
1826 if ($pledgePayment) {
1827 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1828
1829 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1830 if ($processContributionObject) {
1831 $processContribution = TRUE;
1832 }
1833 }
1834 }
1835
1836 // process contribution object.
1837 if ($processContribution) {
1838 $contributionParams = array();
1839 $fields = array(
1840 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1841 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1842 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1843 );
1844 foreach ($fields as $field) {
1845 if (!CRM_Utils_Array::value($field, $params)) {
1846 continue;
1847 }
1848 $contributionParams[$field] = $params[$field];
1849 }
1850
1851 $ids = array('contribution' => $contributionId);
1852 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1853 }
1854
1855 return $updateResult;
1856 }
1857
1858 /**
1859 * This function returns all contribution related object ids.
1860 */
1861 function getComponentDetails($contributionId) {
1862 $componentDetails = $pledgePayment = array();
1863 if (!$contributionId) {
1864 return $componentDetails;
1865 }
1866
1867 $query = "
1868 SELECT c.id as contribution_id,
1869 c.contact_id as contact_id,
1870 mp.membership_id as membership_id,
1871 m.membership_type_id as membership_type_id,
1872 pp.participant_id as participant_id,
1873 p.event_id as event_id,
1874 pgp.id as pledge_payment_id
1875 FROM civicrm_contribution c
1876 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1877 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1878 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1879 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1880 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1881 WHERE c.id = $contributionId";
1882
1883 $dao = CRM_Core_DAO::executeQuery($query);
1884 $componentDetails = array();
1885
1886 while ($dao->fetch()) {
1887 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1888 $componentDetails['contact_id'] = $dao->contact_id;
1889 if ($dao->event_id) {
1890 $componentDetails['event'] = $dao->event_id;
1891 }
1892 if ($dao->participant_id) {
1893 $componentDetails['participant'] = $dao->participant_id;
1894 }
1895 if ($dao->membership_id) {
1896 if (!isset($componentDetails['membership'])) {
1897 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1898 }
1899 $componentDetails['membership'][] = $dao->membership_id;
1900 $componentDetails['membership_type'][] = $dao->membership_type_id;
1901 }
1902 if ($dao->pledge_payment_id) {
1903 $pledgePayment[] = $dao->pledge_payment_id;
1904 }
1905 }
1906
1907 if ($pledgePayment) {
1908 $componentDetails['pledge_payment'] = $pledgePayment;
1909 }
1910
1911 return $componentDetails;
1912 }
1913
1914 static function contributionCount($contactId, $includeSoftCredit = TRUE, $includeHonoree = TRUE) {
1915 if (!$contactId) {
1916 return 0;
1917 }
1918
1919 $fromClause = "civicrm_contribution contribution";
1920 $whereConditions = array("contribution.contact_id = {$contactId}");
1921 if ($includeSoftCredit) {
1922 $fromClause .= " LEFT JOIN civicrm_contribution_soft softContribution
1923 ON ( contribution.id = softContribution.contribution_id )";
1924 $whereConditions[] = " softContribution.contact_id = {$contactId}";
1925 }
1926 if ($includeHonoree) {
1927 $whereConditions[] = " contribution.honor_contact_id = {$contactId}";
1928 }
1929 $whereClause = " contribution.is_test = 0 AND ( " . implode(' OR ', $whereConditions) . " )";
1930
1931 $query = "
1932 SELECT count( contribution.id ) count
1933 FROM {$fromClause}
1934 WHERE {$whereClause}";
1935
1936 return CRM_Core_DAO::singleValueQuery($query);
1937 }
1938
1939 /**
1940 * Function to get individual id for onbehalf contribution
1941 *
1942 * @param int $contributionId contribution id
1943 * @param int $contributorId contributer id
1944 *
1945 * @return array $ids containing organization id and individual id
1946 * @access public
1947 */
1948 function getOnbehalfIds($contributionId, $contributorId = NULL) {
1949
1950 $ids = array();
1951
1952 if (!$contributionId) {
1953 return $ids;
1954 }
1955
1956 // fetch contributor id if null
1957 if (!$contributorId) {
1958 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1959 $contributionId, 'contact_id'
1960 );
1961 }
1962
1963 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1964 $activityTypeId = array_search('Contribution', $activityTypeIds);
1965
1966 if ($activityTypeId && $contributorId) {
1967 $activityQuery = "
1968 SELECT civicrm_activity_contact.contact_id
1969 FROM civicrm_activity_contact
1970 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1971 WHERE civicrm_activity.activity_type_id = %1
1972 AND civicrm_activity.source_record_id = %2
1973 AND civicrm_activity_contact.record_type_id = %3
1974 ";
1975
1976 $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
1977 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1978
1979 $params = array(
1980 1 => array($activityTypeId, 'Integer'),
1981 2 => array($contributionId, 'Integer'),
1982 3 => array($sourceID, 'Integer'),
1983 );
1984
1985 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1986
1987 // for on behalf contribution source is individual and contributor is organization
1988 if ($sourceContactId && $sourceContactId != $contributorId) {
1989 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1990 // get rel type id for employee of relation
1991 foreach ($relationshipTypeIds as $id => $typeVals) {
1992 if ($typeVals['name_a_b'] == 'Employee of') {
1993 $relationshipTypeId = $id;
1994 break;
1995 }
1996 }
1997
1998 $rel = new CRM_Contact_DAO_Relationship();
1999 $rel->relationship_type_id = $relationshipTypeId;
2000 $rel->contact_id_a = $sourceContactId;
2001 $rel->contact_id_b = $contributorId;
2002 if ($rel->find(TRUE)) {
2003 $ids['individual_id'] = $rel->contact_id_a;
2004 $ids['organization_id'] = $rel->contact_id_b;
2005 }
2006 }
2007 }
2008
2009 return $ids;
2010 }
2011
2012 /**
2013 * @return array
2014 * @static
2015 */
2016 static function getContributionDates() {
2017 $config = CRM_Core_Config::singleton();
2018 $currentMonth = date('m');
2019 $currentDay = date('d');
2020 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2021 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2022 (int ) $config->fiscalYearStart['d'] > $currentDay
2023 )
2024 ) {
2025 $year = date('Y') - 1;
2026 }
2027 else {
2028 $year = date('Y');
2029 }
2030 $year = array('Y' => $year);
2031 $yearDate = $config->fiscalYearStart;
2032 $yearDate = array_merge($year, $yearDate);
2033 $yearDate = CRM_Utils_Date::format($yearDate);
2034
2035 $monthDate = date('Ym') . '01';
2036
2037 $now = date('Ymd');
2038
2039 return array(
2040 'now' => $now,
2041 'yearDate' => $yearDate,
2042 'monthDate' => $monthDate,
2043 );
2044 }
2045
2046 /*
2047 * Load objects relations to contribution object
2048 * Objects are stored in the $_relatedObjects property
2049 * In the first instance we are just moving functionality from BASEIpn -
2050 * see http://issues.civicrm.org/jira/browse/CRM-9996
2051 *
2052 * @param array $input Input as delivered from Payment Processor
2053 * @param array $ids Ids as Loaded by Payment Processor
2054 * @param boolean $required Is Payment processor / contribution page required
2055 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
2056 * Note that the unit test for the BaseIPN class tests this function
2057 */
2058 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
2059 if($loadAll){
2060 $ids = array_merge($this->getComponentDetails($this->id),$ids);
2061 if(empty($ids['contact']) && isset($this->contact_id)){
2062 $ids['contact'] = $this->contact_id;
2063 }
2064 }
2065 if (empty($this->_component)) {
2066 if (! empty($ids['event'])) {
2067 $this->_component = 'event';
2068 }
2069 else {
2070 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2071 }
2072 }
2073 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
2074 $contributionType = new CRM_Financial_BAO_FinancialType();
2075 $contributionType->id = $this->financial_type_id;
2076 if (!$contributionType->find(TRUE)) {
2077 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
2078 }
2079 if (!empty($ids['contact'])) {
2080 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
2081 $this->_relatedObjects['contact']->id = $ids['contact'];
2082 $this->_relatedObjects['contact']->find(TRUE);
2083 }
2084 $this->_relatedObjects['contributionType'] = $contributionType;
2085
2086 if ($this->_component == 'contribute') {
2087 // retrieve the other optional objects first so
2088 // stuff down the line can use this info and do things
2089 // CRM-6056
2090 //in any case get the memberships associated with the contribution
2091 //because we now support multiple memberships w/ price set
2092 // see if there are any other memberships to be considered for same contribution.
2093 $query = "
2094 SELECT membership_id
2095 FROM civicrm_membership_payment
2096 WHERE contribution_id = %1 ";
2097 $params = array(1 => array($this->id, 'Integer'));
2098
2099 $dao = CRM_Core_DAO::executeQuery($query, $params );
2100 while ($dao->fetch()) {
2101 if ($dao->membership_id) {
2102 if (!is_array($ids['membership'])) {
2103 $ids['membership'] = array();
2104 }
2105 $ids['membership'][] = $dao->membership_id;
2106 }
2107 }
2108
2109 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2110 foreach ($ids['membership'] as $id) {
2111 if (!empty($id)) {
2112 $membership = new CRM_Member_BAO_Membership();
2113 $membership->id = $id;
2114 if (!$membership->find(TRUE)) {
2115 throw new Exception("Could not find membership record: $id");
2116 }
2117 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2118 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2119 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2120 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2121 $membership->free();
2122 }
2123 }
2124 }
2125
2126 if (!empty($ids['pledge_payment'])) {
2127
2128 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2129 if (empty($paymentID)) {
2130 continue;
2131 }
2132 $payment = new CRM_Pledge_BAO_PledgePayment();
2133 $payment->id = $paymentID;
2134 if (!$payment->find(TRUE)) {
2135 throw new Exception("Could not find pledge payment record: " . $paymentID);
2136 }
2137 $this->_relatedObjects['pledge_payment'][] = $payment;
2138 }
2139 }
2140
2141 if (!empty($ids['contributionRecur'])) {
2142 $recur = new CRM_Contribute_BAO_ContributionRecur();
2143 $recur->id = $ids['contributionRecur'];
2144 if (!$recur->find(TRUE)) {
2145 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2146 }
2147 $this->_relatedObjects['contributionRecur'] = &$recur;
2148 //get payment processor id from recur object.
2149 $paymentProcessorID = $recur->payment_processor_id;
2150 }
2151 //for normal contribution get the payment processor id.
2152 if (!$paymentProcessorID) {
2153 if ($this->contribution_page_id) {
2154 // get the payment processor id from contribution page
2155 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2156 $this->contribution_page_id,
2157 'payment_processor'
2158 );
2159 }
2160 //fail to load payment processor id.
2161 elseif (!CRM_Utils_Array::value('pledge_payment', $ids)) {
2162 $loadObjectSuccess = TRUE;
2163 if ($required) {
2164 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
2165 }
2166 return $loadObjectSuccess;
2167 }
2168 }
2169 }
2170 else {
2171 // we are in event mode
2172 // make sure event exists and is valid
2173 $event = new CRM_Event_BAO_Event();
2174 $event->id = $ids['event'];
2175 if ($ids['event'] &&
2176 !$event->find(TRUE)
2177 ) {
2178 throw new Exception("Could not find event: " . $ids['event']);
2179 }
2180
2181 $this->_relatedObjects['event'] = &$event;
2182
2183 $participant = new CRM_Event_BAO_Participant();
2184 $participant->id = $ids['participant'];
2185 if ($ids['participant'] &&
2186 !$participant->find(TRUE)
2187 ) {
2188 throw new Exception("Could not find participant: " . $ids['participant']);
2189 }
2190 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2191
2192 $this->_relatedObjects['participant'] = &$participant;
2193
2194 if (!$paymentProcessorID) {
2195 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2196 }
2197 }
2198
2199 $loadObjectSuccess = TRUE;
2200 if ($paymentProcessorID) {
2201 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2202 $this->is_test ? 'test' : 'live'
2203 );
2204 $ids['paymentProcessor'] = $paymentProcessorID;
2205 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2206 }
2207 elseif ($required) {
2208 $loadObjectSuccess = FALSE;
2209 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2210 }
2211
2212 return $loadObjectSuccess;
2213 }
2214
2215 /*
2216 * Create array of message information - ie. return html version, txt version, to field
2217 *
2218 * @param array $input incoming information
2219 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2220 * just check presence of recur object but maintaining legacy approach
2221 * to be careful)
2222 * @param array $ids IDs of related objects
2223 * @param array $values any values that may have already been compiled by calling process
2224 * This is augmented by values 'gathered' by gatherMessageValues
2225 * @param bool $returnMessageText distinguishes between whether to send message or return
2226 * message text. We are working towards this function ALWAYS returning message text & calling
2227 * function doing emails / pdfs with it
2228 * @return array $messageArray - messages
2229 */
2230 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2231 if (empty($this->_relatedObjects)) {
2232 $this->loadRelatedObjects($input, $ids);
2233 }
2234 if (empty($this->_component)) {
2235 $this->_component = CRM_Utils_Array::value('component', $input);
2236 }
2237
2238 //not really sure what params might be passed in but lets merge em into values
2239 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2240 $template = CRM_Core_Smarty::singleton();
2241 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2242 //what does recur 'mean here - to do with payment processor return functionality but
2243 // what is the importance
2244 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2245 $paymentObject = &CRM_Core_Payment::singleton(
2246 $this->is_test ? 'test' : 'live',
2247 $this->_relatedObjects['paymentProcessor']
2248 );
2249
2250 $entityID = $entity = NULL;
2251 if (isset($ids['contribution'])) {
2252 $entity = 'contribution';
2253 $entityID = $ids['contribution'];
2254 }
2255 if (isset($ids['membership']) && $ids['membership']) {
2256 $entity = 'membership';
2257 $entityID = $ids['membership'];
2258 }
2259
2260 $url = $paymentObject->subscriptionURL($entityID, $entity);
2261 $template->assign('cancelSubscriptionUrl', $url);
2262
2263 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2264 $template->assign('updateSubscriptionBillingUrl', $url);
2265
2266 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2267 $template->assign('updateSubscriptionUrl', $url);
2268
2269 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2270 //direct mode showing billing block, so use directIPN for temporary
2271 $template->assign('contributeMode', 'directIPN');
2272 }
2273 }
2274 // todo remove strtolower - check consistency
2275 if (strtolower($this->_component) == 'event') {
2276 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2277 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2278 );
2279 }
2280 else {
2281 $values['contribution_id'] = $this->id;
2282 if (CRM_Utils_Array::value('related_contact', $ids)) {
2283 $values['related_contact'] = $ids['related_contact'];
2284 if (isset($ids['onbehalf_dupe_alert'])) {
2285 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2286 }
2287 $entityBlock = array(
2288 'contact_id' => $ids['contact'],
2289 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2290 'Home', 'id', 'name'
2291 ),
2292 );
2293 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2294 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2295 }
2296 $isTest = FALSE;
2297 if ($this->is_test) {
2298 $isTest = TRUE;
2299 }
2300 if (!empty($this->_relatedObjects['membership'])) {
2301 foreach ($this->_relatedObjects['membership'] as $membership) {
2302 if ($membership->id) {
2303 $values['membership_id'] = $membership->id;
2304
2305 // need to set the membership values here
2306 $template->assign('membership_assign', 1);
2307 $template->assign('membership_name',
2308 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2309 );
2310 $template->assign('mem_start_date', $membership->start_date);
2311 $template->assign('mem_join_date', $membership->join_date);
2312 $template->assign('mem_end_date', $membership->end_date);
2313 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2314 $template->assign('mem_status', $membership_status);
2315 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2316 $template->assign('is_pay_later', 1);
2317 }
2318
2319 // if separate payment there are two contributions recorded and the
2320 // admin will need to send a receipt for each of them separately.
2321 // we dont link the two in the db (but can potentially infer it if needed)
2322 $template->assign('is_separate_payment', 0);
2323
2324 if ($recur && $paymentObject) {
2325 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2326 $template->assign('cancelSubscriptionUrl', $url);
2327 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2328 $template->assign('updateSubscriptionBillingUrl', $url);
2329 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2330 $template->assign('updateSubscriptionUrl', $url);
2331 }
2332
2333 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2334
2335 return $result;
2336 // otherwise if its about sending emails, continue sending without return, as we
2337 // don't want to exit the loop.
2338 }
2339 }
2340 }
2341 else {
2342 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2343 }
2344 }
2345 }
2346
2347 /*
2348 * Gather values for contribution mail - this function has been created
2349 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2350 * Values related to the contribution in question are gathered
2351 *
2352 * @param array $input input into function (probably from payment processor)
2353 * @param array $ids the set of ids related to the inpurt
2354 *
2355 * @return array $values
2356 *
2357 * NB don't add direct calls to the function as we intend to change the signature
2358 */
2359 function _gatherMessageValues($input, &$values, $ids = array()) {
2360 // set display address of contributor
2361 if ($this->address_id) {
2362 $addressParams = array('id' => $this->address_id);
2363 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2364 $addressDetails = array_values($addressDetails);
2365 $values['address'] = $addressDetails[0]['display'];
2366 }
2367 if ($this->_component == 'contribute') {
2368 if (isset($this->contribution_page_id)) {
2369 CRM_Contribute_BAO_ContributionPage::setValues(
2370 $this->contribution_page_id,
2371 $values
2372 );
2373 if ($this->contribution_page_id) {
2374 // CRM-8254 - override default currency if applicable
2375 $config = CRM_Core_Config::singleton();
2376 $config->defaultCurrency = CRM_Utils_Array::value(
2377 'currency',
2378 $values,
2379 $config->defaultCurrency
2380 );
2381 }
2382 }
2383 // no contribution page -probably back office
2384 else {
2385 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2386 $values['is_email_receipt'] = 1;
2387 $values['title'] = 'Contribution';
2388 }
2389 // set lineItem for contribution
2390 if ($this->id) {
2391 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2392 if (!empty($lineItem)) {
2393 $itemId = key($lineItem);
2394 foreach ($lineItem as &$eachItem) {
2395 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership']) ) {
2396 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2397 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2398 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2399 }
2400 }
2401 $values['lineItem'][0] = $lineItem;
2402 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2403 }
2404 }
2405
2406 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2407 $this->id,
2408 $this->contact_id
2409 );
2410 // if this is onbehalf of contribution then set related contact
2411 if (CRM_Utils_Array::value('individual_id', $relatedContact)) {
2412 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2413 }
2414 }
2415 else {
2416 // event
2417 $eventParams = array(
2418 'id' => $this->_relatedObjects['event']->id,
2419 );
2420 $values['event'] = array();
2421
2422 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2423
2424 //get location details
2425 $locationParams = array(
2426 'entity_id' => $this->_relatedObjects['event']->id,
2427 'entity_table' => 'civicrm_event',
2428 );
2429 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2430
2431 $ufJoinParams = array(
2432 'entity_table' => 'civicrm_event',
2433 'entity_id' => $ids['event'],
2434 'module' => 'CiviEvent',
2435 );
2436
2437 list($custom_pre_id,
2438 $custom_post_ids
2439 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2440
2441 $values['custom_pre_id'] = $custom_pre_id;
2442 $values['custom_post_id'] = $custom_post_ids;
2443
2444 // set lineItem for event contribution
2445 if ($this->id) {
2446 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2447 if (!empty($participantIds)) {
2448 foreach ($participantIds as $pIDs) {
2449 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2450 if (!CRM_Utils_System::isNull($lineItem)) {
2451 $values['lineItem'][] = $lineItem;
2452 }
2453 }
2454 }
2455 }
2456 }
2457
2458 return $values;
2459 }
2460
2461 /**
2462 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2463 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2464 * Note we send directly from this function in some cases because it is only partly refactored
2465 * Don't call this function directly as the signature will change
2466 */
2467 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2468 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2469 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2470 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2471 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2472 $template->assign('useForMember', true);
2473 }
2474 //assign honor infomation to receiptmessage
2475 $honorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2476 $this->id,
2477 'honor_contact_id'
2478 );
2479 if (!empty($honorID)) {
2480
2481 $honorDefault = $honorIds = array();
2482 $honorIds['contribution'] = $this->id;
2483 $idParams = array('id' => $honorID, 'contact_id' => $honorID);
2484 CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds);
2485 $honorType = CRM_Core_PseudoConstant::honor();
2486
2487 $template->assign('honor_block_is_active', 1);
2488 if (CRM_Utils_Array::value('prefix_id', $honorDefault)) {
2489 $prefix = CRM_Core_PseudoConstant::individualPrefix();
2490 $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
2491 }
2492 $template->assign('honor_first_name', CRM_Utils_Array::value('first_name', $honorDefault));
2493 $template->assign('honor_last_name', CRM_Utils_Array::value('last_name', $honorDefault));
2494 $template->assign('honor_email', CRM_Utils_Array::value('email', $honorDefault['email'][1]));
2495 $template->assign('honor_type', $honorType[$this->honor_type_id]);
2496 }
2497
2498 $dao = new CRM_Contribute_DAO_ContributionProduct();
2499 $dao->contribution_id = $this->id;
2500 if ($dao->find(TRUE)) {
2501 $premiumId = $dao->product_id;
2502 $template->assign('option', $dao->product_option);
2503
2504 $productDAO = new CRM_Contribute_DAO_Product();
2505 $productDAO->id = $premiumId;
2506 $productDAO->find(TRUE);
2507 $template->assign('selectPremium', TRUE);
2508 $template->assign('product_name', $productDAO->name);
2509 $template->assign('price', $productDAO->price);
2510 $template->assign('sku', $productDAO->sku);
2511 }
2512 $template->assign('title', CRM_Utils_Array::value('title',$values));
2513 $amount = CRM_Utils_Array::value('total_amount', $input,(CRM_Utils_Array::value('amount', $input)),null);
2514 if(empty($amount) && isset($this->total_amount)){
2515 $amount = $this->total_amount;
2516 }
2517 $template->assign('amount', $amount);
2518 // add the new contribution values
2519 if (strtolower($this->_component) == 'contribute') {
2520 //PCP Info
2521 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2522 $softDAO->contribution_id = $this->id;
2523 if ($softDAO->find(TRUE)) {
2524 $template->assign('pcpBlock', TRUE);
2525 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2526 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2527 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2528
2529 //assign the pcp page title for email subject
2530 $pcpDAO = new CRM_PCP_DAO_PCP();
2531 $pcpDAO->id = $softDAO->pcp_id;
2532 if ($pcpDAO->find(TRUE)) {
2533 $template->assign('title', $pcpDAO->title);
2534 }
2535 }
2536 }
2537
2538 if ($this->financial_type_id) {
2539 $values['financial_type_id'] = $this->financial_type_id;
2540 }
2541
2542
2543 $template->assign('trxn_id', $this->trxn_id);
2544 $template->assign('receive_date',
2545 CRM_Utils_Date::mysqlToIso($this->receive_date)
2546 );
2547 $template->assign('contributeMode', 'notify');
2548 $template->assign('action', $this->is_test ? 1024 : 1);
2549 $template->assign('receipt_text',
2550 CRM_Utils_Array::value('receipt_text',
2551 $values
2552 )
2553 );
2554 $template->assign('is_monetary', 1);
2555 $template->assign('is_recur', (bool) $recur);
2556 $template->assign('currency', $this->currency);
2557 $template->assign('address', CRM_Utils_Address::format($input));
2558 if ($this->_component == 'event') {
2559 $template->assign('title', $values['event']['title']);
2560 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2561 $viewRoles = array();
2562 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2563 $viewRoles[] = $participantRoles[$v];
2564 }
2565 $values['event']['participant_role'] = implode(', ', $viewRoles);
2566 $template->assign('event', $values['event']);
2567 $template->assign('location', $values['location']);
2568 $template->assign('customPre', $values['custom_pre_id']);
2569 $template->assign('customPost', $values['custom_post_id']);
2570
2571 $isTest = FALSE;
2572 if ($this->_relatedObjects['participant']->is_test) {
2573 $isTest = TRUE;
2574 }
2575
2576 $values['params'] = array();
2577 //to get email of primary participant.
2578 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2579 $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount);
2580 //build an array of cId/pId of participants
2581 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2582 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2583 //send receipt to additional participant if exists
2584 if (count($additionalIDs)) {
2585 $template->assign('isPrimary', 0);
2586 $template->assign('customProfile', NULL);
2587 //set additionalParticipant true
2588 $values['params']['additionalParticipant'] = TRUE;
2589 foreach ($additionalIDs as $pId => $cId) {
2590 $amount = array();
2591 //to change the status pending to completed
2592 $additional = new CRM_Event_DAO_Participant();
2593 $additional->id = $pId;
2594 $additional->contact_id = $cId;
2595 $additional->find(TRUE);
2596 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2597 $additional->status_id = 1;
2598 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2599 //if additional participant dont have email
2600 //use display name.
2601 if (!$additionalParticipantInfo) {
2602 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2603 }
2604 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2605 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
2606 $additional->save();
2607 $additional->free();
2608 $template->assign('amount', $amount);
2609 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2610 }
2611 }
2612
2613 //build an array of custom profile and assigning it to template
2614 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2615
2616 if (count($customProfile)) {
2617 $template->assign('customProfile', $customProfile);
2618 }
2619
2620 // for primary contact
2621 $values['params']['additionalParticipant'] = FALSE;
2622 $template->assign('isPrimary', 1);
2623 $template->assign('amount', $primaryAmount);
2624 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2625 if ($this->payment_instrument_id) {
2626 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2627 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2628 }
2629 // carry paylater, since we did not created billing,
2630 // so need to pull email from primary location, CRM-4395
2631 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2632 }
2633 return $template;
2634 }
2635
2636 /**
2637 * Function to check whether payment processor supports
2638 * cancellation of contribution subscription
2639 *
2640 * @param int $contributionId contribution id
2641 *
2642 * @return boolean
2643 * @access public
2644 * @static
2645 */
2646 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2647 $cacheKeyString = "$contributionId";
2648 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2649
2650 static $supportsCancel = array();
2651
2652 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2653 $supportsCancel[$cacheKeyString] = FALSE;
2654 $isCancelled = FALSE;
2655
2656 if ($isNotCancelled) {
2657 $isCancelled = self::isSubscriptionCancelled($contributionId);
2658 }
2659
2660 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2661 if (!empty($paymentObject)) {
2662 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2663 }
2664 }
2665 return $supportsCancel[$cacheKeyString];
2666 }
2667
2668 /**
2669 * Function to check whether subscription is already cancelled
2670 *
2671 * @param int $contributionId contribution id
2672 *
2673 * @return string $status contribution status
2674 * @access public
2675 * @static
2676 */
2677 static function isSubscriptionCancelled($contributionId) {
2678 $sql = "
2679 SELECT cr.contribution_status_id
2680 FROM civicrm_contribution_recur cr
2681 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2682 WHERE con.id = %1 LIMIT 1";
2683 $params = array(1 => array($contributionId, 'Integer'));
2684 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2685 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2686 if ($status == 'Cancelled') {
2687 return TRUE;
2688 }
2689 return FALSE;
2690 }
2691
2692 /**
2693 * Function to create all financial accounts entry
2694 *
2695 * @param array $params contribution object, line item array and params for trxn
2696 *
2697 * @param array $ids of contribution id
2698 *
2699 * @access public
2700 * @static
2701 */
2702 static function recordFinancialAccounts(&$params, $ids) {
2703 $skipRecords = $update = FALSE;
2704 $additionalPaticipantId = array();
2705 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2706
2707 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2708 $entityId = $params['participant_id'];
2709 $entityTable = 'civicrm_participant';
2710 $additionalPaticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2711 }
2712 else {
2713 $entityId = $params['contribution']->id;
2714 $entityTable = 'civicrm_contribution';
2715 }
2716 $entityID[] = $entityId;
2717 if (!empty($additionalPaticipantId)) {
2718 $entityID += $additionalPaticipantId;
2719 }
2720 if (!CRM_Utils_Array::value('prevContribution', $params)) {
2721 $entityID = NULL;
2722 }
2723 // build line item array if its not set in $params
2724 if (!CRM_Utils_Array::value('line_item', $params) || $additionalPaticipantId) {
2725 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2726 }
2727
2728 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2729 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)) {
2730 $skipRecords = TRUE;
2731 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses)) {
2732 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2733 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2734 }
2735 elseif (CRM_Utils_Array::value('payment_processor', $params)) {
2736 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2737 }
2738 elseif (CRM_Utils_Array::value('payment_instrument_id', $params)) {
2739 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2740 }
2741 else {
2742 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2743 }
2744
2745 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2746 if (!isset($totalAmount) && CRM_Utils_Array::value('prevContribution', $params)) {
2747 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2748 }
2749 //build financial transaction params
2750 $trxnParams = array(
2751 'contribution_id' => $params['contribution']->id,
2752 'to_financial_account_id' => $params['to_financial_account_id'],
2753 'trxn_date' => date('YmdHis'),
2754 'total_amount' => $totalAmount,
2755 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2756 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2757 'currency' => $params['contribution']->currency,
2758 'trxn_id' => $params['contribution']->trxn_id,
2759 'status_id' => $params['contribution']->contribution_status_id,
2760 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params),
2761 'check_number' => CRM_Utils_Array::value('check_number', $params),
2762 );
2763
2764 if (CRM_Utils_Array::value('payment_processor', $params)) {
2765 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2766 }
2767 $params['trxnParams'] = $trxnParams;
2768
2769 if (CRM_Utils_Array::value('prevContribution', $params)) {
2770
2771 //if Change contribution amount
2772 if (array_key_exists('total_amount', $params) && isset($params['total_amount']) &&
2773 $params['total_amount'] != $params['prevContribution']->total_amount) {
2774 //Update Financial Records
2775 self::updateFinancialAccounts($params, 'changedAmount');
2776 }
2777
2778 //Update contribution status
2779 if (CRM_Utils_Array::value('contribution_status_id', $params) &&
2780 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) {
2781 //Update Financial Records
2782 self::updateFinancialAccounts($params, 'changedStatus');
2783 }
2784
2785 // change Payment Instrument for a Completed contribution
2786 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2787 // instrument is null and now new payment instrument is added along with the payment
2788 if (array_key_exists('payment_instrument_id', $params)) {
2789 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2790 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)) {
2791 //check if status is changed from Pending to Completed
2792 // do not update payment instrument changes for Pending to Completed
2793 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2794 $params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses))) {
2795 // for all other statuses create new financial records
2796 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2797 }
2798 }
2799 else if ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2800 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2801 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id) {
2802 // for any other payment instrument changes create new financial records
2803 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2804 }
2805 else if (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2806 $params['contribution']->check_number != $params['prevContribution']->check_number) {
2807 // another special case when check number is changed, create new financial records
2808 // create financial trxn with negative amount
2809 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2810 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2811 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2812 // create financial trxn with positive amount
2813 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2814 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2815 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2816 }
2817 }
2818
2819 //if financial type is changed
2820 if (CRM_Utils_Array::value('financial_type_id', $params) &&
2821 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id) {
2822 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2823 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2824 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2825 if ($oldFinancialAccount != $newFinancialAccount) {
2826 $params['total_amount'] = 0;
2827 if ($params['contribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
2828 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2829 $params['prevContribution']->financial_type_id, $relationTypeId);
2830 }
2831 self::updateFinancialAccounts($params, 'changeFinancialType');
2832 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2833 $params['financial_account_id'] = $newFinancialAccount;
2834 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2835 self::updateFinancialAccounts($params);
2836 }
2837 }
2838 $update = TRUE;
2839 }
2840
2841 if (!$update) {
2842 //records finanical trxn and entity financial trxn
2843 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
2844 $params['entity_id'] = $financialTxn->id;
2845 }
2846 }
2847 // record line items and finacial items
2848
2849 if (!CRM_Utils_Array::value('skipLineItem', $params)) {
2850 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
2851 }
2852
2853 // create batch entry if batch_id is passed
2854 if (CRM_Utils_Array::value('batch_id', $params)) {
2855 $entityParams = array(
2856 'batch_id' => $params['batch_id'],
2857 'entity_table' => 'civicrm_financial_trxn',
2858 'entity_id' => $financialTxn->id,
2859 );
2860 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2861 }
2862
2863 // when a fee is charged
2864 if (CRM_Utils_Array::value('fee_amount', $params) && (!CRM_Utils_Array::value('prevContribution', $params)
2865 || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
2866 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2867 }
2868
2869 if (CRM_Utils_Array::value('prevContribution', $params) && $entityTable == 'civicrm_participant'
2870 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) {
2871 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2872 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2873 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2874 }
2875 unset($params['line_item']);
2876 }
2877
2878 /**
2879 * Function to update all financial accounts entry
2880 *
2881 * @param array $params contribution object, line item array and params for trxn
2882 *
2883 * @param string $context update scenarios
2884 *
2885 * @access public
2886 * @static
2887 */
2888 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2889 $itemAmount = $trxnID = NULL;
2890 //get all the statuses
2891 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2892 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) &&
2893 $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2894 && $context == 'changePaymentInstrument') {
2895 return;
2896 }
2897 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2898 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2899 }
2900 if ($context == 'changedStatus') {
2901 //get all the statuses
2902 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2903
2904 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2905 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2906 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))) {
2907
2908 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2909 }
2910 elseif ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
2911 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2912 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2913 $params['trxnParams']['to_financial_account_id'] = NULL;
2914 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2915 }
2916 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL,
2917 " AND v.name LIKE 'Accounts Receivable Account is' "));
2918 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2919 $financialTypeID, $relationTypeId);
2920 }
2921 $itemAmount = $params['trxnParams']['total_amount'];
2922 }
2923 elseif ($context == 'changePaymentInstrument') {
2924 if ($params['prevContribution']->payment_instrument_id != null
2925 && $params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2926 && $params['contribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
2927 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2928 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2929 }
2930 elseif ($params['prevContribution']->payment_instrument_id != null) {
2931 $params['trxnParams']['from_financial_account_id'] =
2932 CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount(
2933 $params['prevContribution']->payment_instrument_id);
2934 }
2935 else {
2936 $params['trxnParams']['from_financial_account_id'] = CRM_Core_DAO::singleValueQuery(
2937 "SELECT id FROM civicrm_financial_account WHERE is_default = 1");
2938 }
2939 }
2940
2941 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2942 $params['entity_id'] = $trxn->id;
2943
2944 if ($context == 'changedStatus') {
2945 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) &&
2946 ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))) {
2947 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2948 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2949
2950 $entityParams = array(
2951 'entity_table' => 'civicrm_financial_item',
2952 'financial_trxn_id' => $trxn->id,
2953 );
2954 foreach ($params['line_item'] as $fieldId => $fields) {
2955 foreach ($fields as $fieldValueId => $fieldValues) {
2956 $fparams = array(
2957 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2958 2 => array($fieldValues['id'], 'Integer'),
2959 );
2960 CRM_Core_DAO::executeQuery($query, $fparams);
2961 $fparams = array(
2962 1 => array($fieldValues['id'], 'Integer'),
2963 );
2964 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
2965 while ($financialItem->fetch()) {
2966 $entityParams['entity_id'] = $financialItem->id;
2967 $entityParams['amount'] = $financialItem->amount;
2968 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
2969 }
2970 }
2971 }
2972 return;
2973 }
2974 }
2975 if ($context != 'changePaymentInstrument') {
2976 $itemParams['entity_table'] = 'civicrm_line_item';
2977 $trxnIds['id'] = $params['entity_id'];
2978 foreach ($params['line_item'] as $fieldId => $fields) {
2979 foreach ($fields as $fieldValueId => $fieldValues) {
2980 $prevParams['entity_id'] = $fieldValues['id'];
2981 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
2982
2983 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
2984 if ($params['contribution']->receive_date) {
2985 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
2986 }
2987
2988 $financialAccount = $prevfinancialItem->financial_account_id;
2989 if (CRM_Utils_Array::value('financial_account_id', $params)) {
2990 $financialAccount = $params['financial_account_id'];
2991 }
2992
2993 $currency = $params['prevContribution']->currency;
2994 if ($params['contribution']->currency) {
2995 $currency = $params['contribution']->currency;
2996 }
2997 if (CRM_Utils_Array::value('is_quick_config', $params)) {
2998 $amount = $itemAmount;
2999 if (!$amount) {
3000 $amount = $params['total_amount'];
3001 }
3002 }
3003 else {
3004 $diff = 1;
3005 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
3006 $diff = -1;
3007 }
3008 $amount = $diff * $fieldValues['line_total'];
3009 }
3010
3011 $itemParams = array(
3012 'transaction_date' => $receiveDate,
3013 'contact_id' => $params['prevContribution']->contact_id,
3014 'currency' => $currency,
3015 'amount' => $amount,
3016 'description' => $prevfinancialItem->description,
3017 'status_id' => $prevfinancialItem->status_id,
3018 'financial_account_id' => $financialAccount,
3019 'entity_table' => 'civicrm_line_item',
3020 'entity_id' => $fieldValues['id']
3021 );
3022 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3023 }
3024 }
3025 }
3026 }
3027
3028 /**
3029 * Function to check status validation on update of a contribution
3030 *
3031 * @param array $values previous form values before submit
3032 *
3033 * @param array $fields the input form values
3034 *
3035 * @param array $errors list of errors
3036 *
3037 * @access public
3038 * @static
3039 */
3040 static function checkStatusValidation($values, &$fields, &$errors) {
3041 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3042 $checkStatus = array(
3043 'Cancelled' => array('Completed', 'Refunded'),
3044 'Completed' => array('Cancelled', 'Refunded'),
3045 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3046 'Refunded' => array('Cancelled', 'Completed')
3047 );
3048
3049 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3050 $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']]));
3051 }
3052 }
3053
3054 /**
3055 * Function to delete contribution of contact
3056 *
3057 * CRM-12155
3058 *
3059 * @param integer $contactId contact id
3060 *
3061 * @access public
3062 * @static
3063 */
3064 static function deleteContactContribution($contactId) {
3065 $contribution = new CRM_Contribute_DAO_Contribution();
3066 $contribution->contact_id = $contactId;
3067 $contribution->find();
3068 while ($contribution->fetch()) {
3069 self::deleteContribution($contribution->id);
3070 }
3071 }
3072 }