Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-02-02-18-36-16
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
index 6aa92b45f14753a0350726bfda3972b21c02b729..f461bf693b3f130c2a03486eb61c80b4a45f999e 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.5                                                |
+ | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
  | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
@@ -23,7 +23,7 @@
  | GNU Affero General Public License or the licensing of CiviCRM,     |
  | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
  +--------------------------------------------------------------------+
-*/
+ */
 
 /**
  *
@@ -43,10 +43,14 @@ class CRM_Core_Payment_BaseIPN {
    */
   protected $_inputParameters = array();
 
+  protected $_isRecurring = FALSE;
+
+  protected $_isFirstOrLastRecurringPayment = FALSE;
+
   /**
    * Constructor
    */
-  function __construct() {
+  public function __construct() {
     self::$_now = date('YmdHis');
   }
 
@@ -57,12 +61,13 @@ class CRM_Core_Payment_BaseIPN {
    *
    * @throws CRM_Core_Exception
    */
-  function setInputParameters($parameters) {
-    if(!is_array($parameters)) {
+  public function setInputParameters($parameters) {
+    if (!is_array($parameters)) {
       throw new CRM_Core_Exception('Invalid input parameters');
     }
     $this->_inputParameters = $parameters;
   }
+
   /**
    * Validate incoming data. This function is intended to ensure that incoming data matches
    * It provides a form of pseudo-authentication - by checking the calling fn already knows
@@ -71,20 +76,25 @@ class CRM_Core_Payment_BaseIPN {
    * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
    * and didn't update your IPN URL.
    *
-   * @param array $input interpreted values from the values returned through the IPN
-   * @param array $ids more interpreted values (ids) from the values returned through the IPN
-   * @param array $objects an empty array that will be populated with loaded object
-   * @param boolean $required boolean Return FALSE if the relevant objects don't exist
-   * @param integer $paymentProcessorID Id of the payment processor ID in use
-   * @return boolean
+   * @param array $input
+   *   Interpreted values from the values returned through the IPN.
+   * @param array $ids
+   *   More interpreted values (ids) from the values returned through the IPN.
+   * @param array $objects
+   *   An empty array that will be populated with loaded object.
+   * @param bool $required
+   *   Boolean Return FALSE if the relevant objects don't exist.
+   * @param int $paymentProcessorID
+   *   Id of the payment processor ID in use.
+   * @return bool
    */
-  function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
+  public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
 
     // make sure contact exists and is valid
     $contact = new CRM_Contact_BAO_Contact();
     $contact->id = $ids['contact'];
     if (!$contact->find(TRUE)) {
-      CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
+      CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
       echo "Failure: Could not find contact record: {$ids['contact']}<p>";
       return FALSE;
     }
@@ -93,7 +103,7 @@ class CRM_Core_Payment_BaseIPN {
     $contribution = new CRM_Contribute_BAO_Contribution();
     $contribution->id = $ids['contribution'];
     if (!$contribution->find(TRUE)) {
-      CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
+      CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
       echo "Failure: Could not find contribution record for {$contribution->id}<p>";
       return FALSE;
     }
@@ -121,13 +131,13 @@ class CRM_Core_Payment_BaseIPN {
    * @param $input
    * @param array $ids
    * @param array $objects
-   * @param boolean $required
-   * @param integer $paymentProcessorID
+   * @param bool $required
+   * @param int $paymentProcessorID
    * @param array $error_handling
    *
-   * @return multitype:number NULL |boolean
+   * @return bool
    */
-  function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
+  public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
     if (empty($error_handling)) {
       // default options are that we log an error & echo it out
       // note that we should refactor this error handling into error code @ some point
@@ -151,13 +161,13 @@ class CRM_Core_Payment_BaseIPN {
     try {
       $success = $contribution->loadRelatedObjects($input, $ids, $required);
     }
-    catch(Exception $e) {
+    catch (Exception $e) {
       $success = FALSE;
       if (!empty($error_handling['log_error'])) {
         CRM_Core_Error::debug_log_message($e->getMessage());
       }
       if (!empty($error_handling['echo_error'])) {
-        echo ($e->getMessage());
+        echo $e->getMessage();
       }
       if (!empty($error_handling['return_error'])) {
         return array(
@@ -175,9 +185,9 @@ class CRM_Core_Payment_BaseIPN {
    * @param array $objects
    * @param object $transaction
    * @param array $input
-   * @return boolean
+   * @return bool
    */
-  function failed(&$objects, &$transaction, $input = array()) {
+  public function failed(&$objects, &$transaction, $input = array()) {
     $contribution = &$objects['contribution'];
     $memberships = array();
     if (!empty($objects['membership'])) {
@@ -193,16 +203,20 @@ class CRM_Core_Payment_BaseIPN {
     }
     $participant = &$objects['participant'];
 
-    $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+    //CRM-15546
+    $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+        'labelColumn' => 'name',
+        'flip' => 1,
+      ));
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
-    $contribution->contribution_status_id = array_search('Failed', $contributionStatus);
+    $contribution->contribution_status_id = $contributionStatuses['Failed'];
     $contribution->save();
 
     //add lineitems for recurring payments
     if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
-      $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, CRM_Core_DAO::$_nullArray);
+      $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
     }
 
     //add new soft credit against current contribution id and
@@ -215,21 +229,28 @@ class CRM_Core_Payment_BaseIPN {
     if (empty($input['skipComponentSync'])) {
       if (!empty($memberships)) {
         // if transaction is failed then set "Cancelled" as membership status
-        $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus());
+        $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
+            'labelColumn' => 'name',
+            'flip' => 1,
+          ));
         foreach ($memberships as $membership) {
           if ($membership) {
-            $membership->status_id = $cancelStatusId;
+            $membership->status_id = $membershipStatuses['Cancelled'];
             $membership->save();
 
             //update related Memberships.
-            $params = array('status_id' => $cancelStatusId);
+            $params = array('status_id' => $membershipStatuses['Cancelled']);
             CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
           }
         }
       }
 
       if ($participant) {
-        $participant->status_id = 4;
+        $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
+            'labelColumn' => 'name',
+            'flip' => 1,
+          ));
+        $participant->status_id = $participantStatuses['Cancelled'];
         $participant->save();
       }
     }
@@ -244,9 +265,9 @@ class CRM_Core_Payment_BaseIPN {
    * Handled pending contribution status
    * @param array $objects
    * @param object $transaction
-   * @return boolean
+   * @return bool
    */
-  function pending(&$objects, &$transaction) {
+  public function pending(&$objects, &$transaction) {
     $transaction->commit();
     CRM_Core_Error::debug_log_message("returning since contribution status is pending");
     echo "Success: Returning since contribution status is pending<p>";
@@ -260,7 +281,7 @@ class CRM_Core_Payment_BaseIPN {
    *
    * @return bool
    */
-  function cancelled(&$objects, &$transaction, $input = array()) {
+  public function cancelled(&$objects, &$transaction, $input = array()) {
     $contribution = &$objects['contribution'];
     $memberships = &$objects['membership'];
     if (is_numeric($memberships)) {
@@ -272,7 +293,11 @@ class CRM_Core_Payment_BaseIPN {
     if (empty($contribution->id)) {
       $addLineItems = TRUE;
     }
-    $contribution->contribution_status_id = 3;
+    $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+        'labelColumn' => 'name',
+        'flip' => 1,
+      ));
+    $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
     $contribution->cancel_date = self::$_now;
     $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
@@ -282,7 +307,7 @@ class CRM_Core_Payment_BaseIPN {
 
     //add lineitems for recurring payments
     if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
-      $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, CRM_Core_DAO::$_nullArray);
+      $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
     }
 
     //add new soft credit against current $contribution and
@@ -294,20 +319,28 @@ class CRM_Core_Payment_BaseIPN {
 
     if (empty($input['skipComponentSync'])) {
       if (!empty($memberships)) {
+        $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
+            'labelColumn' => 'name',
+            'flip' => 1,
+          ));
         foreach ($memberships as $membership) {
           if ($membership) {
-            $membership->status_id = 6;
+            $membership->status_id = $membershipStatuses['Cancelled'];
             $membership->save();
 
             //update related Memberships.
-            $params = array('status_id' => 6);
+            $params = array('status_id' => $membershipStatuses['Cancelled']);
             CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
           }
         }
       }
 
       if ($participant) {
-        $participant->status_id = 4;
+        $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
+            'labelColumn' => 'name',
+            'flip' => 1,
+          ));
+        $participant->status_id = $participantStatuses['Cancelled'];
         $participant->save();
       }
     }
@@ -323,11 +356,10 @@ class CRM_Core_Payment_BaseIPN {
    *
    * @return bool
    */
-  function unhandled(&$objects, &$transaction) {
+  public function unhandled(&$objects, &$transaction) {
     $transaction->rollback();
-    // we dont handle this as yet
-    CRM_Core_Error::debug_log_message("returning since contribution status: $status is not handled");
-    echo "Failure: contribution status $status is not handled<p>";
+    CRM_Core_Error::debug_log_message("returning since contribution status: is not handled");
+    echo "Failure: contribution status is not handled<p>";
     return FALSE;
   }
 
@@ -338,7 +370,7 @@ class CRM_Core_Payment_BaseIPN {
    * @param $transaction
    * @param bool $recur
    */
-  function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
+  public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
     $contribution = &$objects['contribution'];
 
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
@@ -347,9 +379,9 @@ class CRM_Core_Payment_BaseIPN {
     if (is_numeric($memberships)) {
       $memberships = array($objects['membership']);
     }
-    $participant  = &$objects['participant'];
-    $event        = &$objects['event'];
-    $changeToday  = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
+    $participant = &$objects['participant'];
+    $event = &$objects['event'];
+    $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib = &$objects['contributionRecur'];
 
     $values = array();
@@ -368,7 +400,7 @@ class CRM_Core_Payment_BaseIPN {
         $values['receipt_from_name'] = $domainValues[0];
         $values['receipt_from_email'] = $domainValues[1];
       }
-      if($recurContrib && $recurContrib->id){
+      if ($recurContrib && $recurContrib->id) {
         //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
         $values['is_email_receipt'] = $recurContrib->is_email_receipt;
       }
@@ -379,7 +411,7 @@ class CRM_Core_Payment_BaseIPN {
       }
 
       if (!empty($memberships)) {
-        $membershipsUpdate = array( );
+        $membershipsUpdate = array();
         foreach ($memberships as $membershipTypeIdKey => $membership) {
           if ($membership) {
             $format = '%Y%m%d';
@@ -397,7 +429,7 @@ FROM      civicrm_membership_log
 WHERE     membership_id=$membership->id
 ORDER BY  id DESC
 LIMIT 1;";
-            $dao = new CRM_Core_DAO;
+            $dao = new CRM_Core_DAO();
             $dao->query($sql);
             if ($dao->fetch()) {
               if (!empty($dao->membership_type_id)) {
@@ -440,7 +472,8 @@ LIMIT 1;";
               (array) $membership
             );
 
-            $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
+            $formatedParams = array(
+              'status_id' => CRM_Utils_Array::value('id', $calcStatus, 2),
               'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format),
               'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format),
               'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format),
@@ -502,13 +535,13 @@ LIMIT 1;";
 
       $ufJoinParams = array(
         'entity_table' => 'civicrm_event',
-        'entity_id'    => $ids['event'],
-        'module'       => 'CiviEvent',
+        'entity_id' => $ids['event'],
+        'module' => 'CiviEvent',
       );
 
       list($custom_pre_id,
-           $custom_post_ids
-           ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
+        $custom_post_ids
+        ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
 
       $values['custom_pre_id'] = $custom_pre_id;
       $values['custom_post_id'] = $custom_post_ids;
@@ -523,7 +556,11 @@ LIMIT 1;";
         $values['is_email_receipt'] = 1;
       }
       if (empty($input['skipComponentSync'])) {
-        $participant->status_id = 1;
+        $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
+            'labelColumn' => 'name',
+            'flip' => 1,
+          ));
+        $participant->status_id = $participantStatuses['Registered'];
       }
       $participant->save();
     }
@@ -537,8 +574,11 @@ LIMIT 1;";
     if (empty($contribution->id)) {
       $addLineItems = TRUE;
     }
-
-    $contribution->contribution_status_id = 1;
+    $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+        'labelColumn' => 'name',
+        'flip' => 1,
+      ));
+    $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
@@ -568,8 +608,14 @@ LIMIT 1;";
     }
 
     //add lineitems for recurring payments
-    if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
-      $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id, $input);
+    if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
+      if ($addLineItems) {
+        $input['line_item'] = $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
+      }
+      else {
+        // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
+        $input['line_item'] = array();
+      }
     }
 
     //copy initial contribution custom fields for recurring contributions
@@ -594,12 +640,14 @@ LIMIT 1;";
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
-      $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
-      if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later &&
-       $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses))) {
-       $input['payment_processor'] = $paymentProcessorId;
+      $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+          'labelColumn' => 'name',
+          'flip' => 1,
+        ));
+      if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
+        $input['payment_processor'] = $paymentProcessorId;
       }
-      $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
+      $input['contribution_status_id'] = $contributionStatuses['Completed'];
       $input['total_amount'] = $input['amount'];
       $input['contribution'] = $contribution;
       $input['financial_type_id'] = $contribution->financial_type_id;
@@ -614,7 +662,7 @@ LIMIT 1;";
         $input['contribution_mode'] = 'membership';
       }
       //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
-      // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
+      // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
       // and since the contribution is saved prior to this line there is always a contribution-id,
       // however there is never a prevContribution (which appears to mean original contribution not previous
       // contribution - or preUpdateContributionObject most accurately)
@@ -622,6 +670,7 @@ LIMIT 1;";
       // to mean "are we updating an exisitng pending contribution"
       //I was able to make the unit test complete as fataling here doesn't prevent
       // the contribution being created - but activities would not be created or emails sent
+
       CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
 
@@ -655,6 +704,9 @@ LIMIT 1;";
     }
 
     CRM_Core_Error::debug_log_message("Success: Database updated");
+    if ($this->_isRecurring) {
+      $this->sendRecurringStartOrEndNotification($ids, $recur);
+    }
   }
 
   /**
@@ -662,7 +714,7 @@ LIMIT 1;";
    *
    * @return bool
    */
-  function getBillingID(&$ids) {
+  public function getBillingID(&$ids) {
     // get the billing location type
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
     // CRM-8108 remove the ts around the Billing locationtype
@@ -676,28 +728,26 @@ LIMIT 1;";
     return TRUE;
   }
 
-  /*
+  /**
    * Send receipt from contribution. Note that the compose message part has been moved to contribution
    * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
    *
-   * @params array $input Incoming data from Payment processor
-   * @params array $ids Related object IDs
-   * @params array $values values related to objects that have already been loaded
-   * @params bool $recur is it part of a recurring contribution
-   * @params bool $returnMessageText Should text be returned instead of sent. This
-   * is because the function is also used to generate pdfs
-   */
-  /**
-   * @param $input
-   * @param $ids
+   * @param array $input
+   *   Incoming data from Payment processor.
+   * @param array $ids
+   *   Related object IDs.
    * @param $objects
-   * @param $values
+   * @param array $values
+   *   Values related to objects that have already been loaded.
    * @param bool $recur
+   *   Is it part of a recurring contribution.
    * @param bool $returnMessageText
+   *   Should text be returned instead of sent. This.
+   *   is because the function is also used to generate pdfs
    *
-   * @return mixed
+   * @return array
    */
-  function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
+  public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
     $contribution = &$objects['contribution'];
     $input['is_recur'] = $recur;
     // set receipt from e-mail and name in value
@@ -713,22 +763,46 @@ LIMIT 1;";
     return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
   }
 
+  /**
+   * Send start or end notification for recurring payments
+   * @param $ids
+   * @param $recur
+   */
+  public function sendRecurringStartOrEndNotification($ids, $recur) {
+    if ($this->_isFirstOrLastRecurringPayment) {
+      $autoRenewMembership = FALSE;
+      if ($recur->id &&
+        isset($ids['membership']) && $ids['membership']
+      ) {
+        $autoRenewMembership = TRUE;
+      }
+
+      //send recurring Notification email for user
+      CRM_Contribute_BAO_ContributionPage::recurringNotify($this->_isFirstOrLastRecurringPayment,
+        $ids['contact'],
+        $ids['contributionPage'],
+        $recur,
+        $autoRenewMembership
+      );
+    }
+  }
+
   /**
    * Update contribution status - this is only called from one place in the code &
    * it is unclear whether it is a function on the way in or on the way out
    *
-   * @param unknown_type $params
-   * @return void|Ambigous <value, unknown, array>
+   * @param array $params
+   * @return void|NULL|int
    */
-  function updateContributionStatus(&$params) {
+  public function updateContributionStatus(&$params) {
     // get minimum required values.
-    $statusId       = CRM_Utils_Array::value('contribution_status_id', $params);
-    $componentId    = CRM_Utils_Array::value('component_id', $params);
-    $componentName  = CRM_Utils_Array::value('componentName', $params);
+    $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
+    $componentId = CRM_Utils_Array::value('component_id', $params);
+    $componentName = CRM_Utils_Array::value('componentName', $params);
     $contributionId = CRM_Utils_Array::value('contribution_id', $params);
 
     if (!$contributionId || !$componentId || !$componentName || !$statusId) {
-      return;
+      return NULL;
     }
 
     $input = $ids = $objects = array();
@@ -776,28 +850,34 @@ LIMIT 1;";
 
     $contribution = &$objects['contribution'];
 
-    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+    $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+        'labelColumn' => 'name',
+        'flip' => 1,
+      ));
     $input['skipComponentSync'] = CRM_Utils_Array::value('skipComponentSync', $params);
-    if ($statusId == array_search('Cancelled', $contributionStatuses)) {
+    if ($statusId == $contributionStatuses['Cancelled']) {
       $baseIPN->cancelled($objects, $transaction, $input);
       $transaction->commit();
       return $statusId;
     }
-    elseif ($statusId == array_search('Failed', $contributionStatuses)) {
+    elseif ($statusId == $contributionStatuses['Failed']) {
       $baseIPN->failed($objects, $transaction, $input);
       $transaction->commit();
       return $statusId;
     }
 
     // status is not pending
-    if ($contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
+    if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
       $transaction->commit();
       return;
     }
 
     //set values for ipn code.
     foreach (array(
-      'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
+               'fee_amount',
+               'check_number',
+               'payment_instrument_id',
+             ) as $field) {
       if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
         $input[$field] = $contribution->$field;
       }
@@ -823,7 +903,7 @@ LIMIT 1;";
     return $statusId;
   }
 
-  /*
+  /**
    * Update pledge associated with a recurring contribution
    *
    * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
@@ -835,17 +915,17 @@ LIMIT 1;";
    *
    * The pledge payment record should already exist & will need to be updated with the new contribution ID.
    * If not the contribution will also need to be linked to the pledge
+   *
+   * @param CRM_Contribute_BAO_Contribution $contribution
    */
-  /**
-   * @param $contribution
-   */
-  function updateRecurLinkedPledge(&$contribution) {
+  public function updateRecurLinkedPledge(&$contribution) {
     $returnProperties = array('id', 'pledge_id');
-    $paymentDetails   = $paymentIDs = array();
+    $paymentDetails = $paymentIDs = array();
 
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
-        $paymentDetails, $returnProperties
-      )) {
+      $paymentDetails, $returnProperties
+    )
+    ) {
       foreach ($paymentDetails as $key => $value) {
         $paymentIDs[] = $value['id'];
         $pledgeId = $value['pledge_id'];
@@ -879,7 +959,7 @@ LIMIT 1;";
 
       // we have a pledge now we need to get the oldest unpaid payment
       $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
-      if(empty($paymentDetails['id'])){
+      if (empty($paymentDetails['id'])) {
         // we can assume this pledge is now completed
         // return now so we don't create a core error & roll back
         return;
@@ -900,41 +980,48 @@ LIMIT 1;";
   }
 
   /**
-   * @param $recurId
-   * @param $contributionId
-   * @param $input
+   * @param int $recurId
+   * @param $contribution
+   *
+   * @return array
    */
-  function addrecurLineItems($recurId, $contributionId, &$input) {
-    $lineSets = $lineItems = array();
-
-    //Get the first contribution id with recur id
-    if ($recurId) {
-      $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
-      $lineItems = CRM_Price_BAO_LineItem::getLineItems($contriID, 'contribution');
-      if (!empty($lineItems)) {
-        foreach ($lineItems as $key => $value) {
-          $pricesetID = new CRM_Price_DAO_PriceField();
-          $pricesetID->id = $value['price_field_id'];
-          $pricesetID->find(TRUE);
-          $lineSets[$pricesetID->price_set_id][] = $value;
+  public function addRecurLineItems($recurId, $contribution) {
+    $lineSets = array();
+
+    $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
+    $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
+    if (!empty($lineItems)) {
+      foreach ($lineItems as $key => $value) {
+        $priceField = new CRM_Price_DAO_PriceField();
+        $priceField->id = $value['price_field_id'];
+        $priceField->find(TRUE);
+        $lineSets[$priceField->price_set_id][] = $value;
+        if ($value['entity_table'] == 'civicrm_membership') {
+          try {
+            civicrm_api3('membership_payment', 'create', array(
+                'membership_id' => $value['entity_id'],
+                'contribution_id' => $contribution->id,
+              ));
+          }
+          catch (CiviCRM_API3_Exception $e) {
+            // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
+            // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
+          }
         }
       }
-      if (!empty($input)) {
-        $input['line_item'] = $lineSets;
-      }
-      else {
-        CRM_Price_BAO_LineItem::processPriceSet($contributionId, $lineSets);
-      }
     }
+    else {
+      CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
+    }
+    return $lineSets;
   }
 
-  // function to copy custom data of the
-  // initial contribution into its recurring contributions
   /**
-   * @param $recurId
-   * @param $targetContributionId
+   * copy custom data of the initial contribution into its recurring contributions
+   * @param int $recurId
+   * @param int $targetContributionId
    */
-  function copyCustomValues($recurId, $targetContributionId) {
+  public function copyCustomValues($recurId, $targetContributionId) {
     if ($recurId && $targetContributionId) {
       // get the initial contribution id of recur id
       $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
@@ -961,25 +1048,26 @@ LIMIT 1;";
         }
 
         foreach ($table as $tableName => $tableColumns) {
-          $insert          = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
+          $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
           $tableColumns[0] = $targetContributionId;
-          $select          = 'SELECT ' . implode(', ', $tableColumns);
-          $from            = ' FROM ' . $tableName;
-          $where           = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
-          $query           = $insert . $select . $from . $where;
-          $dao             = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
+          $select = 'SELECT ' . implode(', ', $tableColumns);
+          $from = ' FROM ' . $tableName;
+          $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
+          $query = $insert . $select . $from . $where;
+          $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
         }
       }
     }
   }
 
-  // function to copy soft credit record of first recurring contribution
-  // and add new soft credit against $targetContributionId
   /**
-   * @param $recurId
-   * @param $targetContributionId
+   * copy soft credit record of first recurring contribution
+   * and add new soft credit against $targetContributionId
+   *
+   * @param int $recurId
+   * @param int $targetContributionId
    */
-  function addrecurSoftCredit($recurId, $targetContributionId) {
+  public function addrecurSoftCredit($recurId, $targetContributionId) {
     $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
 
     $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
@@ -992,4 +1080,5 @@ LIMIT 1;";
       $soft_contribution->save();
     }
   }
+
 }