CRM-10859 rename BAO classes that dont follow naming std (at least those for which...
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
index 6f6c4afce9dfe81b0d21b592679959cdcb11f822..04b035808c879349943c277764135ded47b3c043 100644 (file)
@@ -1,6 +1,4 @@
 <?php
-// $Id$
-
 /*
  +--------------------------------------------------------------------+
  | CiviCRM version 4.3                                                |
@@ -284,7 +282,7 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
         }
       }
       if ($retrieveRequired == 1) {
-        $contribution->find(true);
+        $contribution->find(TRUE);
       }
     }
 
@@ -299,34 +297,50 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
     if (!$activity->find()) {
       CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
+
     // Handle soft credit and / or link to personal campaign page
-    if (CRM_Utils_Array::value('deleteSoftCredit', $params, TRUE)) {
-        // first delete soft credits if any                                                                                                                                                            
-        //CRM_Contribute_BAO_ContributionSoft::del($contribution->id);
-
-      if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
-        $softParams = array();
-        $softParams['contribution_id'] = $contribution->id;
-        $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
-        $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
-          $pcp['pcp_made_through_id'], 'contact_id'
-        );
-        $softParams['currency'] = $contribution->currency;
-        $softParams['amount'] = $contribution->total_amount;
-        $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
-        $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
-        $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
-        CRM_Contribute_BAO_ContributionSoft::add($softParams);
-      }
-      elseif (CRM_Utils_Array::value('soft_credit', $params)) {
-        $softParams = $params['soft_credit'];
-        foreach ($softParams as $softParam) {
-          $softParam['contribution_id'] = $contribution->id;
-          $softParam['currency'] = $contribution->currency;
-          CRM_Contribute_BAO_ContributionSoft::add($softParam);
+    list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft::getSoftCreditType($contribution->id);
+    if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
+      if (!empty($type) && $type == 'soft') {
+        $deleteParams = array('contribution_id' => $contribution->id);
+        CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
+      }
+      $softParams = array();
+      $softParams['contribution_id'] = $contribution->id;
+      $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
+      $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
+        $pcp['pcp_made_through_id'], 'contact_id'
+      );
+      $softParams['currency'] = $contribution->currency;
+      $softParams['amount'] = $contribution->total_amount;
+      $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
+      $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
+      $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
+      CRM_Contribute_BAO_ContributionSoft::add($softParams);
+    }
+    elseif (CRM_Utils_Array::value('soft_credit', $params)) {
+      $softParams = $params['soft_credit'];
+
+      if (!empty($softIDs)) {
+        foreach ( $softIDs as $softID) {
+          if (!in_array($softID, $params['soft_credit_ids'])) {
+            $deleteParams = array('id' => $softID);
+            CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
+          }
         }
       }
+
+      foreach ($softParams as $softParam) {
+        $softParam['contribution_id'] = $contribution->id;
+        $softParam['currency'] = $contribution->currency;
+        $softParam['pcp_id'] = 'null';
+        $softParam['pcp_display_in_roll'] = 'null';
+        $softParam['pcp_roll_nickname'] = 'null';
+        $softParam['pcp_personal_note'] = 'NULL';
+        CRM_Contribute_BAO_ContributionSoft::add($softParam);
+      }
     }
+
     $transaction->commit();
 
     // do not add to recent items for import, CRM-4399
@@ -349,7 +363,7 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
         }
       }
       if($retrieveRequired == 1){
-        $contribution->find(true);
+        $contribution->find(TRUE);
       }
       $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
       $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
@@ -458,7 +472,7 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
    * @access public
    * @static
    */
-  static function &importableFields($contacType = 'Individual', $status = TRUE) {
+  static function &importableFields($contactType = 'Individual', $status = TRUE) {
     if (!self::$_importableFields) {
       if (!self::$_importableFields) {
         self::$_importableFields = array();
@@ -475,15 +489,15 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
       $tmpFields = CRM_Contribute_DAO_Contribution::import();
       unset($tmpFields['option_value']);
       $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
-      $contactFields = CRM_Contact_BAO_Contact::importableFields($contacType, NULL);
+      $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
 
       // Using new Dedupe rule.
       $ruleParams = array(
-        'contact_type' => $contacType,
+        'contact_type' => $contactType,
         'used'         => 'Unsupervised',
       );
       $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
-      $tmpConatctField = array();
+      $tmpContactField = array();
       if (is_array($fieldsArray)) {
         foreach ($fieldsArray as $value) {
           //skip if there is no dupe rule
@@ -496,21 +510,21 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
             'column_name'
           );
           $value = $customFieldId ? 'custom_' . $customFieldId : $value;
-          $tmpConatctField[trim($value)] = $contactFields[trim($value)];
+          $tmpContactField[trim($value)] = $contactFields[trim($value)];
           if (!$status) {
-            $title = $tmpConatctField[trim($value)]['title'] . ' ' . ts('(match to contact)');
+            $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
           }
           else {
-            $title = $tmpConatctField[trim($value)]['title'];
+            $title = $tmpContactField[trim($value)]['title'];
           }
-          $tmpConatctField[trim($value)]['title'] = $title;
+          $tmpContactField[trim($value)]['title'] = $title;
         }
       }
 
-      $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
-      $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
+      $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
+      $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
       $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
-      $fields = array_merge($fields, $tmpConatctField);
+      $fields = array_merge($fields, $tmpContactField);
       $fields = array_merge($fields, $tmpFields);
       $fields = array_merge($fields, $note);
       $fields = array_merge($fields, $optionFields);
@@ -657,8 +671,8 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = civicrm_contribution.conta
     CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
 
     // remove entry from civicrm_price_set_entity, CRM-5095
-    if (CRM_Price_BAO_Set::getFor('civicrm_contribution', $id)) {
-      CRM_Price_BAO_Set::removeFrom('civicrm_contribution', $id);
+    if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
+      CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
     }
     // cleanup line items.
     $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
@@ -1517,7 +1531,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
               $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
             }
             else {
-              $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, null, null, null, $numterms);
+              $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
             }
 
             //get the status for membership.
@@ -1528,7 +1542,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
               TRUE
             );
 
-            $formatedParams = array(
+            $formattedParams = array(
               'status_id' => CRM_Utils_Array::value('id', $calcStatus,
                 array_search('Current', $membershipStatuses)
               ),
@@ -1537,16 +1551,16 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
               'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
             );
 
-            CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formatedParams);
+            CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
 
-            $membership->copyValues($formatedParams);
+            $membership->copyValues($formattedParams);
             $membership->save();
 
             //updating the membership log
             $membershipLog = array();
-            $membershipLog = $formatedParams;
+            $membershipLog = $formattedParams;
             $logStartDate  = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
-            $logStartDate  = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
+            $logStartDate  = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
 
             $membershipLog['start_date'] = $logStartDate;
             $membershipLog['membership_id'] = $membership->id;
@@ -1557,7 +1571,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
             CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
 
             //update related Memberships.
-            CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
+            CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
 
             $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
               '%B %E%f, %Y'
@@ -1699,7 +1713,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
    * Function to get individual id for onbehalf contribution
    *
    * @param int $contributionId contribution id
-   * @param int $contributorId  contributer id
+   * @param int $contributorId  contributor id
    *
    * @return array $ids containing organization id and individual id
    * @access public
@@ -1732,7 +1746,7 @@ INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_ac
    AND     civicrm_activity_contact.record_type_id = %3
 ";
 
-      $activityContacts = CRM_Core_PseudoConstant::activityContacts('name');
+      $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
       $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
 
       $params = array(
@@ -2158,7 +2172,7 @@ WHERE  contribution_id = %1 ";
             }
           }
           $values['lineItem'][0] = $lineItem;
-          $values['priceSetID']  = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItem[$itemId]['price_field_id'], 'price_set_id');
+          $values['priceSetID']  = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
       }
       }
 
@@ -2241,11 +2255,11 @@ WHERE  contribution_id = %1 ";
       $honorIds['contribution'] = $this->id;
       $idParams = array('id' => $honorID, 'contact_id' => $honorID);
       CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds);
-      $honorType = CRM_Core_PseudoConstant::honor();
+      $honorType = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
 
       $template->assign('honor_block_is_active', 1);
       if (CRM_Utils_Array::value('prefix_id', $honorDefault)) {
-        $prefix = CRM_Core_PseudoConstant::individualPrefix();
+        $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
         $template->assign('honor_prefix', $prefix[$honorDefault['prefix_id']]);
       }
       $template->assign('honor_first_name', CRM_Utils_Array::value('first_name', $honorDefault));
@@ -2479,6 +2493,9 @@ WHERE  contribution_id = %1 ";
     if (!CRM_Utils_Array::value('prevContribution', $params)) {
       $entityID = NULL;
     }
+    else {
+      $update = TRUE;
+    }
     // build line item array if its not set in $params
     if (!CRM_Utils_Array::value('line_item', $params) || $additionalParticipantId) {
       CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
@@ -2498,7 +2515,9 @@ WHERE  contribution_id = %1 ";
         $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
       }
       else {
-        $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1");
+        $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
+        $queryParams = array(1 => array($relationTypeId, 'Integer'));
+        $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
       }
 
       $totalAmount = CRM_Utils_Array::value('total_amount', $params);
@@ -2516,7 +2535,7 @@ WHERE  contribution_id = %1 ";
         'currency' => $params['contribution']->currency,
         'trxn_id' => $params['contribution']->trxn_id,
         'status_id' => $params['contribution']->contribution_status_id,
-        'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params),
+        'payment_instrument_id' => $params['contribution']->payment_instrument_id,
         'check_number' => CRM_Utils_Array::value('check_number', $params),
       );
 
@@ -2594,7 +2613,6 @@ WHERE  contribution_id = %1 ";
             self::updateFinancialAccounts($params);
           }
         }
-        $update = TRUE;
       }
 
       if (!$update) {
@@ -2604,7 +2622,6 @@ WHERE  contribution_id = %1 ";
       }
     }
     // record line items and finacial items
-
     if (!CRM_Utils_Array::value('skipLineItem', $params)) {
       CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
     }
@@ -2615,7 +2632,7 @@ WHERE  contribution_id = %1 ";
         'batch_id' => $params['batch_id'],
         'entity_table' => 'civicrm_financial_trxn',
         'entity_id' => $financialTxn->id,
-                            );
+      );
       CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
     }
 
@@ -2672,8 +2689,7 @@ WHERE  contribution_id = %1 ";
           $params['trxnParams']['to_financial_account_id'] = NULL;
           $params['trxnParams']['total_amount'] = - $params['total_amount'];
         }
-        $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL,
-          " AND v.name LIKE 'Accounts Receivable Account is' "));
+        $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
           $financialTypeID, $relationTypeId);
       }
@@ -2797,6 +2813,12 @@ WHERE  contribution_id = %1 ";
    * @static
    */
   static function checkStatusValidation($values, &$fields, &$errors) {
+    if (CRM_Utils_System::isNull($values) && CRM_Utils_Array::value('id', $fields)) {
+      $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
+      if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
+        return FALSE;
+      }
+    }
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $checkStatus = array(
       'Cancelled' => array('Completed', 'Refunded'),