Exemple #1
0
 /**
  * Register a participant.
  *
  * @param array $params
  * @param CRM_Event_BAO_Participant $participant
  * @param CRM_Event_BAO_Event $event
  *
  * @return mixed
  */
 public function registerParticipant($params, &$participant, $event)
 {
     $transaction = new CRM_Core_Transaction();
     // handle register date CRM-4320
     $registerDate = date('YmdHis');
     $participantParams = array('id' => $participant->id, 'event_id' => $event->id, 'register_date' => $registerDate, 'source' => CRM_Utils_Array::value('participant_source', $params, $this->description), 'is_pay_later' => $this->is_pay_later, 'fee_amount' => CRM_Utils_Array::value('amount', $params, 0), 'fee_currency' => CRM_Utils_Array::value('currencyID', $params));
     if ($participant->must_wait) {
         $participant_status = 'On waitlist';
     } elseif (CRM_Utils_Array::value('is_pay_later', $params, FALSE)) {
         $participant_status = 'Pending from pay later';
     } else {
         $participant_status = 'Registered';
     }
     $participant_statuses = CRM_Event_PseudoConstant::participantStatus();
     $participantParams['status_id'] = array_search($participant_status, $participant_statuses);
     $participant_status_label = CRM_Utils_Array::value($participantParams['status_id'], CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'));
     $participantParams['participant_status'] = $participant_status_label;
     $this->assign('isOnWaitlist', $participant->must_wait);
     if ($this->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
         $participantParams['is_test'] = 1;
     } else {
         $participantParams['is_test'] = 0;
     }
     if (self::is_administrator()) {
         if (!empty($params['note'])) {
             $note_params = array('participant_id' => $participant->id, 'contact_id' => self::getContactID(), 'note' => $params['note']);
             CRM_Event_BAO_Participant::update_note($note_params);
         }
     }
     $participant->copyValues($participantParams);
     $participant->save();
     if (!empty($params['contributionID'])) {
         $payment_params = array('participant_id' => $participant->id, 'contribution_id' => $params['contributionID']);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
     }
     $transaction->commit();
     $event_values = array();
     CRM_Core_DAO::storeValues($event, $event_values);
     $location = array();
     if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
         $locationParams = array('entity_id' => $participant->event_id, 'entity_table' => 'civicrm_event');
         $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
         CRM_Core_BAO_Address::fixAddress($location['address'][1]);
     }
     list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
     $payer_values = array('email' => '', 'name' => '');
     if ($this->payer_contact_id) {
         $payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
         $payer_values = array('email' => $payer_contact_details[1], 'name' => $payer_contact_details[0]);
     }
     $values = array('params' => array($participant->id => $participantParams), 'event' => $event_values, 'location' => $location, 'custom_pre_id' => $pre_id, 'custom_post_id' => $post_id, 'payer' => $payer_values);
     CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
     return $participant;
 }
 public static function find_all_by_params($params)
 {
     $participant = new CRM_Event_BAO_Participant();
     $participant->copyValues($params);
     $result = array();
     if ($participant->find()) {
         while ($participant->fetch()) {
             $result[] = new CRM_Event_Cart_BAO_MerParticipant(clone $participant);
         }
     }
     return $result;
 }
 public function preProcess()
 {
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
     $this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     $this->assign('component', $this->_component);
     $this->assign('id', $this->_id);
     $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
     if ($this->_view == 'transaction' && $this->_action & CRM_Core_Action::BROWSE) {
         $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, TRUE);
         $transactionRows = $paymentInfo['transaction'];
         $title = ts('View Payment');
         if ($this->_component == 'event') {
             $info = CRM_Event_BAO_Participant::participantDetails($this->_id);
             $title .= " - {$info['title']}";
         }
         CRM_Utils_System::setTitle($title);
         $this->assign('transaction', TRUE);
         $this->assign('rows', $transactionRows);
         return;
     }
     $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     $enitityType = NULL;
     if ($this->_component == 'event') {
         $enitityType = 'participant';
         $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
     }
     $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
     $this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($eventId);
     $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $enitityType);
     $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
     $this->_amtPaid = $paymentDetails['paid'];
     $this->_amtTotal = $paymentDetails['total'];
     if (!empty($paymentInfo['refund_due'])) {
         $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
         $this->_paymentType = 'refund';
     } elseif (!empty($paymentInfo['amount_owed'])) {
         $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
         $this->_paymentType = 'owed';
     } else {
         CRM_Core_Error::fatal(ts('No payment information found for this record'));
     }
     //set the payment mode - _mode property is defined in parent class
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     if (!empty($this->_mode) && $this->_paymentType == 'refund') {
         CRM_Core_Error::fatal(ts('Credit card payment is not for Refund payments use'));
     }
     list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
     $this->assignPaymentRelatedVariables();
     $this->assign('contributionMode', $this->_mode);
     $this->assign('contactId', $this->_contactId);
     $this->assign('paymentType', $this->_paymentType);
     $this->assign('paymentAmt', abs($paymentAmt));
     $this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
 }
Exemple #4
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $value = array();
     foreach ($this->_participantIds as $participantId) {
         $value['id'] = $participantId;
         // Cancelled status id = 4
         $value['status_id'] = 4;
         CRM_Event_BAO_Participant::create($value);
     }
 }
Exemple #5
0
 /**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 public function preProcess()
 {
     require_once 'CRM/Event/BAO/Participant.php';
     $values = $ids = array();
     $participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, true);
     $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, true);
     $params = array('id' => $participantID);
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     if (empty($values)) {
         require_once 'CRM/Core/Error.php';
         CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).'));
     }
     CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]);
     if (CRM_Utils_Array::value('fee_level', $values[$participantID])) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']);
     }
     if ($values[$participantID]['is_test']) {
         $values[$participantID]['status'] .= ' (test) ';
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant');
     $values[$participantID]['note'] = array_values($noteValue);
     require_once 'CRM/Price/BAO/LineItem.php';
     // Get Line Items
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID);
     if (!CRM_Utils_System::isNull($lineItem)) {
         $values[$participantID]['lineItem'][] = $lineItem;
     }
     $values[$participantID]['totalAmount'] = $values[$participantID]['fee_amount'];
     // get the option value for custom data type
     $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
     $roleGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $values[$participantID]['role_id'], $roleCustomDataTypeID);
     $eventGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $values[$participantID]['event_id'], $eventNameCustomDataTypeID);
     $eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id');
     $eventTypeGroupTree =& CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, null, $eventTypeID, $eventTypeCustomDataTypeID);
     $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
     $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree);
     $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID));
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $this->assign($values[$participantID]);
     // add viewed participant to recent items list
     require_once 'CRM/Utils/Recent.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title');
     $displayName = CRM_Contact_BAO_Contact::displayName($contactID);
     $this->assign('displayName', $displayName);
     $title = $displayName . ' (' . $participantRoles[$values[$participantID]['role_id']] . ' - ' . $eventTitle . ')';
     // add Participant to Recent Items
     CRM_Utils_Recent::add($title, $url, $values[$participantID]['id'], 'Participant', $values[$participantID]['contact_id'], null);
 }
Exemple #6
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $deletedParticipants = 0;
     require_once 'CRM/Event/BAO/Participant.php';
     foreach ($this->_participantIds as $participantId) {
         if (CRM_Event_BAO_Participant::deleteParticipant($participantId)) {
             $deletedParticipants++;
         }
     }
     $status = array(ts('Deleted Participation(s): %1', array(1 => $deletedParticipants)), ts('Total Selected Participation(s): %1', array(1 => count($this->_participantIds))));
     CRM_Core_Session::setStatus($status);
 }
Exemple #7
0
 /**
  * @param $event_id
  *
  * @return bool|int|null|string
  */
 function checkEventCapacity($event_id)
 {
     $empty_seats = CRM_Event_BAO_Participant::eventFull($event_id, TRUE);
     if (is_numeric($empty_seats)) {
         return $empty_seats;
     }
     if (is_string($empty_seats)) {
         return 0;
     } else {
         return NULL;
     }
 }
 function _addParticipantWithPayment($feeTotal, $actualPaidAmt)
 {
     // creating price set, price field
     $paramsSet['title'] = 'Price Set';
     $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
     $paramsSet['is_active'] = FALSE;
     $paramsSet['extends'] = 1;
     $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
     CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceset->id);
     $priceSetId = $priceset->id;
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title', 'id', $paramsSet['title'], 'Check DB for created priceset');
     $paramsField = array('label' => 'Price Field', 'name' => CRM_Utils_String::titleToVar('Price Field'), 'html_type' => 'Text', 'price' => $feeTotal, 'option_label' => array('1' => 'Price Field'), 'option_value' => array('1' => $feeTotal), 'option_name' => array('1' => $feeTotal), 'option_weight' => array('1' => 1), 'option_amount' => array('1' => 1), 'is_display_amounts' => 1, 'weight' => 1, 'options_per_line' => 1, 'is_active' => array('1' => 1), 'price_set_id' => $priceset->id, 'is_enter_qty' => 1);
     $ids = array();
     $pricefield = CRM_Price_BAO_PriceField::create($paramsField, $ids);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceField', $pricefield->id, 'label', 'id', $paramsField['label'], 'Check DB for created pricefield');
     // create participant record
     $eventId = $this->_eventId;
     $participantParams = array('send_receipt' => 1, 'is_test' => 0, 'is_pay_later' => 0, 'event_id' => $eventId, 'register_date' => date('Y-m-d') . " 00:00:00", 'role_id' => 1, 'status_id' => 14, 'source' => 'Event_' . $eventId, 'contact_id' => $this->_contactId, 'note' => 'Note added for Event_' . $eventId, 'fee_level' => 'Price_Field - 55');
     $participant = CRM_Event_BAO_Participant::add($participantParams);
     // create participant contribution with partial payment
     $contributionParams = array('total_amount' => $actualPaidAmt, 'source' => 'Fall Fundraiser Dinner: Offline registration', 'currency' => 'USD', 'non_deductible_amount' => 'null', 'receipt_date' => date('Y-m-d') . " 00:00:00", 'contact_id' => $this->_contactId, 'financial_type_id' => 4, 'payment_instrument_id' => 4, 'contribution_status_id' => 1, 'receive_date' => date('Y-m-d') . " 00:00:00", 'skipLineItem' => 1, 'partial_payment_total' => $feeTotal, 'partial_amount_pay' => $actualPaidAmt);
     $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, CRM_Core_DAO::$_nullArray);
     $contributionId = $contribution->id;
     // add participant payment entry
     $this->participantPaymentCreate($participant->id, $contributionId);
     // -- processing priceSet using the BAO
     $lineItem = array();
     $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, FALSE);
     $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
     $feeBlock = CRM_Utils_Array::value('fields', $priceSet);
     $params['price_2'] = $feeTotal;
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItem);
     $lineItemVal[$priceSetId] = $lineItem;
     CRM_Price_BAO_LineItem::processPriceSet($participant->id, $lineItemVal, $contribution, 'civicrm_participant');
     return array($participant, $contribution);
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
         $links = array();
         foreach ($this->_participantIds as $participantId) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
     }
     $deletedParticipants = $additionalCount = 0;
     foreach ($this->_participantIds as $participantId) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantId)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
                 $additionalCount = count($additionalIds);
                 foreach ($additionalIds as $value) {
                     CRM_Event_BAO_Participant::deleteParticipant($value);
                 }
                 CRM_Event_BAO_Participant::deleteParticipant($participantId);
             }
             $deletedParticipants++;
         } else {
             CRM_Event_BAO_Participant::deleteParticipant($participantId);
             $deletedParticipants++;
         }
     }
     if ($additionalCount) {
         $deletedParticipants += $additionalCount;
     }
     $status = array(ts('Participant(s) Deleted: %1', array(1 => $deletedParticipants)), ts('Total Selected Participant(s): %1', array(1 => $deletedParticipants)));
     if (!empty($participantLinks)) {
         $status[] = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br>' . $participantLinks;
     }
     CRM_Core_Session::setStatus($status);
 }
 /**
  * set the first participant ID if not set, CRM-10032
  *
  * @param int $participantID
  */
 public function processFirstParticipant($participantID)
 {
     $this->_participantId = $participantID;
     $this->set('participantId', $this->_participantId);
     $ids = $participantValues = array();
     $participantParams = array('id' => $this->_participantId);
     CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
     $this->_values['participant'] = $participantValues[$this->_participantId];
     $this->set('values', $this->_values);
     // also set the allow confirmation stuff
     if (array_key_exists($this->_values['participant']['status_id'], CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'"))) {
         $this->_allowConfirmation = TRUE;
         $this->set('allowConfirmation', TRUE);
     }
 }
Exemple #11
0
 /**
  * @param $values
  * @param $query
  */
 public static function whereClauseSingle(&$values, &$query)
 {
     list($name, $op, $value, $grouping, $wildcard) = $values;
     $fields = array_merge(CRM_Event_BAO_Event::fields(), CRM_Event_BAO_Participant::exportableFields());
     switch ($name) {
         case 'event_start_date_low':
         case 'event_start_date_high':
             $query->dateQueryBuilder($values, 'civicrm_event', 'event_start_date', 'start_date', 'Start Date');
             return;
         case 'event_end_date_low':
         case 'event_end_date_high':
             $query->dateQueryBuilder($values, 'civicrm_event', 'event_end_date', 'end_date', 'End Date');
             return;
         case 'event_include_repeating_events':
             /**
              * Include Repeating Events
              */
             //Get parent of this event
             $exEventId = '';
             if ($query->_where[$grouping]) {
                 foreach ($query->_where[$grouping] as $key => $val) {
                     if (strstr($val, 'civicrm_event.id =')) {
                         $exEventId = $val;
                         $extractEventId = explode(" ", $val);
                         $value = $extractEventId[2];
                         $where = $query->_where[$grouping][$key];
                     } else {
                         if (strstr($val, 'civicrm_event.id IN')) {
                             //extract the first event id if multiple events are selected
                             preg_match('/civicrm_event.id IN \\(\\"(\\d+)/', $val, $matches);
                             $value = $matches[1];
                             $where = $query->_where[$grouping][$key];
                         }
                     }
                 }
                 if ($exEventId) {
                     $extractEventId = explode(" ", $exEventId);
                     $value = $extractEventId[2];
                 } else {
                     if (!empty($matches[1])) {
                         $value = $matches[1];
                     }
                 }
                 $where = $query->_where[$grouping][$key];
             }
             $thisEventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($value, 'civicrm_event');
             if ($thisEventHasParent) {
                 $getAllConnections = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($thisEventHasParent, 'civicrm_event');
                 $allEventIds = array();
                 foreach ($getAllConnections as $key => $val) {
                     $allEventIds[] = $val['id'];
                 }
                 if (!empty($allEventIds)) {
                     $op = "IN";
                     $value = "(" . implode(",", $allEventIds) . ")";
                 }
             }
             $query->_where[$grouping][] = "{$where} OR civicrm_event.id {$op} {$value}";
             $query->_qill[$grouping][] = ts('Include Repeating Events');
             $query->_tables['civicrm_event'] = $query->_whereTables['civicrm_event'] = 1;
             return;
         case 'participant_is_test':
             $key = array_search('civicrm_participant.is_test = 0', $query->_where[$grouping]);
             if (!empty($key)) {
                 unset($query->_where[$grouping][$key]);
             }
         case 'participant_test':
             // We dont want to include all tests for sql OR CRM-7827
             if (!$value || $query->getOperator() != 'OR') {
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_participant.is_test", $op, $value, "Boolean");
                 $isTest = $value ? 'a Test' : 'not a Test';
                 $query->_qill[$grouping][] = ts("Participant is %1", array(1 => $isTest));
                 $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
             }
             return;
         case 'participant_fee_id':
             foreach ($value as $k => &$val) {
                 $val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
                 $val = CRM_Core_DAO::escapeString(trim($val));
             }
             $feeLabel = implode('|', $value);
             $query->_where[$grouping][] = "civicrm_participant.fee_level REGEXP '{$feeLabel}'";
             $query->_qill[$grouping][] = ts("Fee level") . " IN " . implode(', ', $value);
             $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
             return;
         case 'participant_fee_amount_high':
         case 'participant_fee_amount_low':
             $query->numberRangeBuilder($values, 'civicrm_participant', 'participant_fee_amount', 'fee_amount', 'Fee Amount');
             return;
         case 'participant_status_id':
             if ($value && is_array($value) && strpos($op, 'IN') === FALSE) {
                 $op = 'IN';
             }
         case 'participant_status':
         case 'participant_source':
         case 'participant_id':
         case 'participant_contact_id':
         case 'participant_is_pay_later':
         case 'participant_fee_amount':
         case 'participant_fee_level':
         case 'participant_campaign_id':
             $qillName = $name;
             if (in_array($name, array('participant_status_id', 'participant_source', 'participant_id', 'participant_contact_id', 'participant_fee_amount', 'participant_fee_level', 'participant_is_pay_later', 'participant_campaign_id'))) {
                 $name = str_replace('participant_', '', $name);
                 if ($name == 'is_pay_later') {
                     $qillName = $name;
                 }
             } elseif ($name == 'participant_status') {
                 $name = 'status_id';
             }
             $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
             $tableName = empty($tableName) ? 'civicrm_participant' : $tableName;
             if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                 $op = key($value);
                 $value = $value[$op];
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("{$tableName}.{$name}", $op, $value, $dataType);
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
             $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
             return;
         case 'participant_role':
         case 'participant_role_id':
             $qillName = $name;
             $name = 'role_id';
             if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                 $op = key($value);
                 $value = $value[$op];
             }
             if (!strstr($op, 'NULL') && !strstr($op, 'EMPTY') && !strstr($op, 'LIKE')) {
                 $regexOp = strstr($op, '!') || strstr($op, 'NOT') ? 'NOT REGEXP' : 'REGEXP';
                 $regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', (array) $value) . "[[:cntrl:]]*";
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_participant.{$name}", $regexOp, $regexp, 'String');
             } else {
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("{$tableName}.{$name}", $op, $value, $dataType);
             }
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
             $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
             return;
         case 'participant_register_date':
         case 'participant_register_date_high':
         case 'participant_register_date_low':
             $query->dateQueryBuilder($values, 'civicrm_participant', 'participant_register_date', 'register_date', 'Register Date');
             return;
         case 'event_id':
         case 'participant_event_id':
             $name = str_replace('participant_', '', $name);
         case 'event_is_public':
         case 'event_type_id':
         case 'event_title':
             $qillName = $name;
             if (in_array($name, array('event_id', 'event_title', 'event_is_public'))) {
                 $name = str_replace('event_', '', $name);
             }
             $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_event.{$name}", $op, $value, $dataType);
             $query->_tables['civicrm_event'] = $query->_whereTables['civicrm_event'] = 1;
             if (!array_key_exists($qillName, $fields)) {
                 break;
             }
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
             return;
     }
 }
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     $values = $ids = array();
     $participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $params = array('id' => $participantID);
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     if (empty($values)) {
         CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).'));
     }
     CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]);
     if (!empty($values[$participantID]['fee_level'])) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']);
     }
     $this->assign('contactId', $contactID);
     $this->assign('participantId', $participantID);
     $paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $participantID, 'id', 'participant_id');
     $this->assign('hasPayment', $paymentId);
     if ($parentParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'registered_by_id')) {
         $parentHasPayment = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $parentParticipantId, 'id', 'participant_id');
         $this->assign('parentHasPayment', $parentHasPayment);
     }
     $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'status_id', 'id');
     $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
     $status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
     if ($status == 'Transferred') {
         $transferId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'transferred_to_contact_id', 'id');
         $pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $transferId, 'id', 'contact_id');
         $transferName = current(CRM_Contact_BAO_Contact::getContactDetails($transferId));
         $this->assign('pid', $pid);
         $this->assign('transferId', $transferId);
         $this->assign('transferName', $transferName);
     }
     $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
     if ($values[$participantID]['is_test']) {
         $values[$participantID]['status'] .= ' (test) ';
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant');
     $values[$participantID]['note'] = array_values($noteValue);
     // Get Line Items
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID);
     if (!CRM_Utils_System::isNull($lineItem)) {
         $values[$participantID]['lineItem'][] = $lineItem;
     }
     $values[$participantID]['totalAmount'] = CRM_Utils_Array::value('fee_amount', $values[$participantID]);
     // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
     if (!empty($values[$participantID]['participant_registered_by_id'])) {
         $values[$participantID]['registered_by_contact_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $values[$participantID]['participant_registered_by_id'], 'contact_id', 'id');
         $values[$participantID]['registered_by_display_name'] = CRM_Contact_BAO_Contact::displayName($values[$participantID]['registered_by_contact_id']);
     }
     // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true  (CRM-4859)
     if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantID)) {
         $values[$participantID]['additionalParticipants'] = CRM_Event_BAO_Participant::getAdditionalParticipants($participantID);
     }
     // get the option value for custom data type
     $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
     $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
     $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
     $allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']);
     $groupTree = array();
     $finalTree = array();
     foreach ($allRoleIDs as $k => $v) {
         $roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $v, $roleCustomDataTypeID);
         $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $values[$participantID]['event_id'], $eventNameCustomDataTypeID);
         $eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id');
         $eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID);
         $groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
         $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree);
         $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID));
         foreach ($groupTree as $treeId => $trees) {
             $finalTree[$treeId] = $trees;
         }
     }
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $finalTree, FALSE, NULL, NULL, NULL, $participantID);
     $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title');
     //CRM-7150, show event name on participant view even if the event is disabled
     if (empty($values[$participantID]['event'])) {
         $values[$participantID]['event'] = $eventTitle;
     }
     //do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values[$participantID])) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values[$participantID]['campaign'] = $campaigns[$campaignId];
     }
     $this->assign($values[$participantID]);
     // add viewed participant to recent items list
     $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::check('edit event participants')) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::check('delete in CiviEvent')) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home");
     }
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']);
     $participantCount = array();
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $totalTaxAmount = 0;
     foreach ($lineItem as $k => $v) {
         if (CRM_Utils_Array::value('participant_count', $lineItem[$k]) > 0) {
             $participantCount[] = $lineItem[$k]['participant_count'];
         }
         $totalTaxAmount = $v['tax_amount'] + $totalTaxAmount;
     }
     if ($invoicing) {
         $this->assign('totalTaxAmount', $totalTaxAmount);
     }
     if ($participantCount) {
         $this->assign('pricesetFieldsCount', $participantCount);
     }
     $this->assign('displayName', $displayName);
     // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
     CRM_Utils_System::setTitle(ts('View Event Registration for') . ' ' . $displayName);
     $roleId = CRM_Utils_Array::value('role_id', $values[$participantID]);
     $title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')';
     $sep = CRM_Core_DAO::VALUE_SEPARATOR;
     $viewRoles = array();
     foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) {
         $viewRoles[] = $participantRoles[$v];
     }
     $values[$participantID]['role_id'] = implode(', ', $viewRoles);
     $this->assign('role', $values[$participantID]['role_id']);
     // add Participant to Recent Items
     CRM_Utils_Recent::add($title, $url, $values[$participantID]['id'], 'Participant', $values[$participantID]['contact_id'], NULL, $recentOther);
 }
 /**
  * FixEventLevel() method (Setting ',' values), resolveDefaults(assinging value to array) method
  */
 public function testfixEventLevel()
 {
     $paramsSet['title'] = 'Price Set';
     $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
     $paramsSet['is_active'] = FALSE;
     $paramsSet['extends'] = 1;
     $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceset->id, 'title', 'id', $paramsSet['title'], 'Check DB for created priceset');
     $paramsField = array('label' => 'Price Field', 'name' => CRM_Utils_String::titleToVar('Price Field'), 'html_type' => 'Text', 'price' => 10, 'option_label' => array('1' => 'Price Field'), 'option_value' => array('1' => 10), 'option_name' => array('1' => 10), 'option_weight' => array('1' => 1), 'is_display_amounts' => 1, 'weight' => 1, 'options_per_line' => 1, 'is_active' => array('1' => 1), 'price_set_id' => $priceset->id, 'is_enter_qty' => 1);
     $ids = array();
     $pricefield = CRM_Price_BAO_PriceField::create($paramsField, $ids);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceField', $pricefield->id, 'label', 'id', $paramsField['label'], 'Check DB for created pricefield');
     $eventId = $this->_eventId;
     $participantParams = array('send_receipt' => 1, 'is_test' => 0, 'is_pay_later' => 0, 'event_id' => $eventId, 'register_date' => date('Y-m-d') . " 00:00:00", 'role_id' => 1, 'status_id' => 1, 'source' => 'Event_' . $eventId, 'contact_id' => $this->_contactId, 'note' => 'Note added for Event_' . $eventId, 'fee_level' => 'Price_Field - 55');
     $participant = CRM_Event_BAO_Participant::add($participantParams);
     //Checking for participant added in the table.
     $this->assertDBCompareValue('CRM_Event_BAO_Participant', $this->_contactId, 'id', 'contact_id', $participant->id, 'Check DB for created participant');
     $values = array();
     $ids = array();
     $params = array('id' => $participant->id);
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     $this->assertNotEquals(count($values), 0, 'Checking for empty array.');
     CRM_Event_BAO_Participant::resolveDefaults($values[$participant->id]);
     if ($values[$participant->id]['fee_level']) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$participant->id]['fee_level']);
     }
     $deletePricefield = CRM_Price_BAO_PriceField::deleteField($pricefield->id);
     $this->assertDBNull('CRM_Price_BAO_PriceField', $pricefield->id, 'name', 'id', 'Check DB for non-existence of Price Field.');
     $deletePriceset = CRM_Price_BAO_PriceSet::deleteSet($priceset->id);
     $this->assertDBNull('CRM_Price_BAO_PriceSet', $priceset->id, 'title', 'id', 'Check DB for non-existence of Price Set.');
     Participant::delete($participant->id);
     Contact::delete($this->_contactId);
     Event::delete($eventId);
 }
 /**
  * This function update contribution as well as related objects.
  */
 function transitionComponents($params, $processContributionObject = false)
 {
     // get minimum required values.
     $contactId = CRM_Utils_Array::value('contact_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);
     $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
     // if we already processed contribution object pass previous status id.
     $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
     $updateResult = array();
     require_once 'CRM/Contribute/PseudoConstant.php';
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     // we process only ( Completed, Cancelled, or Failed ) contributions.
     if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) {
         return $updateResult;
     }
     if (!$componentName || !$componentId) {
         // get the related component details.
         $componentDetails = self::getComponentDetails($contributionId);
     } else {
         $componentDetails['contact_id'] = $contactId;
         $componentDetails['component'] = $componentName;
         if ($componentName = 'event') {
             $componentDetails['participant'] = $componentId;
         } else {
             $componentDetails['membership'] = $componentId;
         }
     }
     if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
         $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id');
     }
     // do check for required ids.
     if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) {
         return $updateResult;
     }
     //now we are ready w/ required ids, start processing.
     require_once 'CRM/Core/Payment/BaseIPN.php';
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $input = $ids = $objects = array();
     $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
     $ids['contribution'] = $contributionId;
     $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
     $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
     $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
     $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
     $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
     $ids['contributionRecur'] = null;
     $ids['contributionPage'] = null;
     if (!$baseIPN->validateData($input, $ids, $objects, false)) {
         CRM_Core_Error::fatal();
     }
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $pledgePayment =& $objects['pledge_payment'];
     $contribution =& $objects['contribution'];
     if ($pledgePayment) {
         require_once 'CRM/Pledge/BAO/Payment.php';
         $pledgePaymentIDs = array();
         foreach ($pledgePayment as $key => $object) {
             $pledgePaymentIDs[] = $object->id;
         }
         $pledgeID = $pledgePayment[0]->pledge_id;
     }
     require_once 'CRM/Event/PseudoConstant.php';
     require_once 'CRM/Event/BAO/Participant.php';
     require_once 'CRM/Pledge/BAO/Pledge.php';
     require_once 'CRM/Member/PseudoConstant.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
     if ($participant) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
         $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id');
     }
     // we might want to process contribution object.
     $processContribution = false;
     if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
         if ($membership) {
             $membership->status_id = array_search('Cancelled', $membershipStatuses);
             $membership->save();
             $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
     } else {
         if ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
             if ($membership) {
                 $membership->status_id = array_search('Expired', $membershipStatuses);
                 $membership->save();
                 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($participant) {
                 $updatedStatusId = array_search('Cancelled', $participantStatuses);
                 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($pledgePayment) {
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
         } else {
             if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
                 // only pending contribution related object processed.
                 if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) {
                     // this is case when we already processed contribution object.
                     return $updateResult;
                 } else {
                     if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
                         // this is case when we will going to process contribution object.
                         return $updateResult;
                     }
                 }
                 if ($membership) {
                     $format = '%Y%m%d';
                     require_once 'CRM/Member/BAO/MembershipType.php';
                     //CRM-4523
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     if ($currentMembership) {
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     require_once 'CRM/Member/BAO/MembershipStatus.php';
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     require_once 'CRM/Member/BAO/MembershipLog.php';
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y');
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($participant) {
                     $updatedStatusId = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                     $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($pledgePayment) {
                     CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                     $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
             }
         }
     }
     // process contribution object.
     if ($processContribution) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contributionParams = array();
         $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number');
         foreach ($fields as $field) {
             if (!CRM_Utils_Array::value($field, $params)) {
                 continue;
             }
             $contributionParams[$field] = $params[$field];
         }
         $ids = array('contribution' => $contributionId);
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
     }
     return $updateResult;
 }
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Exemple #16
0
 /**
  * @param array $submittedValues
  *
  * @param int $action
  *   Action constant
  *    - CRM_Core_Action::UPDATE
  *
  * @param $pledgePaymentID
  *
  * @return array
  * @throws \Exception
  */
 protected function submit($submittedValues, $action, $pledgePaymentID)
 {
     $softParams = $softIDs = array();
     $pId = $contribution = $isRelatedId = FALSE;
     $this->_params = $submittedValues;
     $this->beginPostProcess();
     if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
         // config should be treated the same.
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
     // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
     // as a point of fragility rather than a logical 'if' clause.
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         // @todo WHY  - quick config was conceived as a quick way to configure contribution forms.
         // this is an example of 'other' functionality being hung off it.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         // @todo - if we are completing a contribution then the api call
         // civicrm_api3('Contribution', 'completetransaction') should take care of
         // all associated updates rather than replicating them on the form layer.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         // @todo see above - new functionality has been inappropriately added to the quick config concept
         // and new functionality has been added onto the form layer rather than the BAO :-(
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
                 if (!($this->_action & CRM_Core_Action::UPDATE && $this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])) {
                     $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
                 }
             }
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
     // we should look at having a price field per contribution type & then there would be little reason
     // for the back-office contribution form postProcess to know if it is a quick-config form.
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     $formValues = $submittedValues;
     // Credit Card Contribution.
     if ($this->_mode) {
         $paramsSetByPaymentProcessingSubsystem = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             if (isset($formValues[$key])) {
                 unset($formValues[$key]);
             }
         }
         $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             $formValues[$key] = $contribution->{$key};
         }
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         //format soft-credit/pcp param first
         CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
         $params = array_merge($params, $submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('YmdHis');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
         // we are already handling note below, so to avoid duplicate notes against $contribution
         if (!empty($params['note']) && !empty($submittedValues['note'])) {
             unset($params['note']);
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
             $this->statusMessage[] = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
         $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
                 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
             }
         }
         $this->statusMessageTitle = ts('Saved');
     }
     if ($contribution->id && isset($formValues['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id, $this->_premiumID, $this->_options);
     }
     if ($contribution->id && !empty($submittedValues['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
     }
     CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
     CRM_Contribute_BAO_Contribution::updateRelatedPledge($action, $pledgePaymentID, $contribution->id, CRM_Utils_Array::value('option_type', $formValues) == 2 ? TRUE : FALSE, $formValues['total_amount'], CRM_Utils_Array::value('total_amount', $this->_defaults), $formValues['contribution_status_id'], CRM_Utils_Array::value('contribution_status_id', $this->_defaults));
     return $contribution;
 }
 /**
  * Given the component name and returns the count of participation of contact.
  *
  * @param string $component
  *   Input component name.
  * @param int $contactId
  *   Input contact id.
  * @param string $tableName
  *   Optional tableName if component is custom group.
  *
  * @return int
  *   total number in database
  */
 public static function getCountComponent($component, $contactId, $tableName = NULL)
 {
     $object = NULL;
     switch ($component) {
         case 'tag':
             return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
         case 'rel':
             $result = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::CURRENT, 0, 1);
             return $result;
         case 'group':
             return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
         case 'log':
             if (CRM_Core_BAO_Log::useLoggingReport()) {
                 return FALSE;
             }
             return CRM_Core_BAO_Log::getContactLogCount($contactId);
         case 'note':
             return CRM_Core_BAO_Note::getContactNoteCount($contactId);
         case 'contribution':
             return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
         case 'membership':
             return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
         case 'participant':
             return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
         case 'pledge':
             return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
         case 'case':
             return CRM_Case_BAO_Case::caseCount($contactId);
         case 'grant':
             return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
         case 'activity':
             $input = array('contact_id' => $contactId, 'admin' => FALSE, 'caseId' => NULL, 'context' => 'activity');
             return CRM_Activity_BAO_Activity::getActivitiesCount($input);
         case 'mailing':
             $params = array('contact_id' => $contactId);
             return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
         default:
             $custom = explode('_', $component);
             if ($custom['0'] = 'custom') {
                 if (!$tableName) {
                     $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
                 }
                 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
                 return CRM_Core_DAO::singleValueQuery($queryString);
             }
     }
 }
Exemple #18
0
 /**
  * Given a participant id/contribution id,
  * return contribution/fee line items
  *
  * @param int $entityId
  *   participant/contribution id.
  * @param string $entity
  *   participant/contribution.
  *
  * @param null $isQuick
  * @param bool $isQtyZero
  * @param bool $relatedEntity
  *
  * @param string $overrideWhereClause
  *   E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
  *   this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even
  *   when we don't want it's entity-id magix
  *
  * @param bool $invoice
  * @return array
  *   Array of line items
  */
 public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE)
 {
     $whereClause = $fromClause = NULL;
     $selectClause = "\n      SELECT    li.id,\n      li.label,\n      li.contribution_id,\n      li.qty,\n      li.unit_price,\n      li.line_total,\n      li.entity_table,\n      li.entity_id,\n      pf.label as field_title,\n      pf.html_type,\n      pfv.membership_type_id,\n      pfv.membership_num_terms,\n      li.price_field_id,\n      li.participant_count,\n      li.price_field_value_id,\n      li.financial_type_id,\n      li.tax_amount,\n      pfv.description";
     $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
     if ($relatedEntity) {
         $condition = "li.contribution_id = %2.id ";
     }
     $fromClause = "\n      FROM      civicrm_%2 as %2\n      LEFT JOIN civicrm_line_item li ON ({$condition})\n      LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )\n      LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
     $whereClause = "\n      WHERE     %2.id = %1";
     // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
     if ($entity == 'participant' && $invoice) {
         $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
         if (!empty($additionalParticipantIDs)) {
             $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
         }
     }
     $orderByClause = " ORDER BY pf.weight, pfv.weight";
     if ($isQuick) {
         $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
         $whereClause .= " and cps.is_quick_config = 0";
     }
     if (!$isQtyZero) {
         $whereClause .= " and li.qty != 0";
     }
     $lineItems = array();
     if (!$entityId || !$entity || !$fromClause) {
         return $lineItems;
     }
     $params = array(1 => array($entityId, 'Integer'), 2 => array($entity, 'Text'));
     $getTaxDetails = FALSE;
     $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     if ($overrideWhereClause) {
         $whereClause = $overrideWhereClause;
     }
     $dao = CRM_Core_DAO::executeQuery("{$selectClause} {$fromClause} {$whereClause} {$orderByClause}", $params);
     while ($dao->fetch()) {
         if (!$dao->id) {
             continue;
         }
         $lineItems[$dao->id] = array('qty' => (double) $dao->qty, 'label' => $dao->label, 'unit_price' => $dao->unit_price, 'line_total' => $dao->line_total, 'price_field_id' => $dao->price_field_id, 'participant_count' => $dao->participant_count, 'price_field_value_id' => $dao->price_field_value_id, 'field_title' => $dao->field_title, 'html_type' => $dao->html_type, 'description' => $dao->description, 'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id, 'entity_table' => $dao->entity_table, 'contribution_id' => $dao->contribution_id, 'financial_type_id' => $dao->financial_type_id, 'membership_type_id' => $dao->membership_type_id, 'membership_num_terms' => $dao->membership_num_terms, 'tax_amount' => $dao->tax_amount);
         $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
         $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
         if ($lineItems[$dao->id]['tax_amount'] != '') {
             $getTaxDetails = TRUE;
         }
     }
     if ($invoicing) {
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $smarty = CRM_Core_Smarty::singleton();
         $smarty->assign('taxTerm', $taxTerm);
         $smarty->assign('getTaxDetails', $getTaxDetails);
     }
     return $lineItems;
 }
 /**
  * Build the form object.
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function buildQuickForm(&$form)
 {
     if ($form->_eventId) {
         $form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
         if ($form->_isPaidEvent) {
             $form->addElement('hidden', 'hidden_feeblock', 1);
         }
         // make sure this is for backoffice registration.
         if ($form->getName() == 'Participant') {
             $eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
             $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
         }
     }
     if ($form->_pId) {
         if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $form->_pId, 'contribution_id', 'participant_id')) {
             $form->_online = TRUE;
         }
     }
     if ($form->_isPaidEvent) {
         $params = array('id' => $form->_eventId);
         CRM_Event_BAO_Event::retrieve($params, $event);
         //retrieve custom information
         $form->_values = array();
         CRM_Event_Form_Registration::initEventFee($form, $event['id']);
         CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
         $lineItem = array();
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $totalTaxAmount = 0;
         if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
             $lineItem[] = $form->_values['line_items'];
             foreach ($form->_values['line_items'] as $key => $value) {
                 $totalTaxAmount = $value['tax_amount'] + $totalTaxAmount;
             }
         }
         if ($invoicing) {
             $form->assign('totalTaxAmount', $totalTaxAmount);
         }
         $form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
         $discounts = array();
         if (!empty($form->_values['discount'])) {
             foreach ($form->_values['discount'] as $key => $value) {
                 $value = current($value);
                 $discounts[$key] = $value['name'];
             }
             $element = $form->add('select', 'discount_id', ts('Discount Set'), array(0 => ts('- select -')) + $discounts, FALSE, array('class' => "crm-select2"));
             if ($form->_online) {
                 $element->freeze();
             }
         }
         if ($form->_mode) {
             CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE);
         } elseif (!$form->_mode) {
             $form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL, array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);"));
             $form->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType());
             $form->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDate'));
             $form->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
             // don't show transaction id in batch update mode
             $path = CRM_Utils_System::currentPath();
             $form->assign('showTransactionId', FALSE);
             if ($path != 'civicrm/contact/search/basic') {
                 $form->add('text', 'trxn_id', ts('Transaction ID'));
                 $form->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id'));
                 $form->assign('showTransactionId', TRUE);
             }
             $status = CRM_Contribute_PseudoConstant::contributionStatus();
             // CRM-14417 suppressing contribution statuses that are NOT relevant to new participant registrations
             $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
             foreach (array('Cancelled', 'Failed', 'In Progress', 'Overdue', 'Refunded', 'Pending refund') as $suppress) {
                 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
             }
             $form->add('select', 'contribution_status_id', ts('Payment Status'), $status);
             $form->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
             $form->add('text', 'total_amount', ts('Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount'));
         }
     } else {
         $form->add('text', 'amount', ts('Event Fee(s)'));
     }
     $form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
     $form->assign('paid', $form->_isPaidEvent);
     $form->addElement('checkbox', 'send_receipt', ts('Send Confirmation?'), NULL, array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"));
     $form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
     $form->add('textarea', 'receipt_text', ts('Confirmation Message'));
     // Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
     if ($form->_context != 'standalone') {
         if ($form->_contactId) {
             list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
             $form->assign('email', $form->_contributorEmail);
         } else {
             //show email block for batch update for event
             $form->assign('batchEmail', TRUE);
         }
     }
     $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend');
     $form->assign('outBound_option', $mailingInfo['outBound_option']);
     $form->assign('hasPayment', $form->_paymentId);
 }
Exemple #20
0
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = null)
 {
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, false, false, false, false, false, $this->_contributionClause);
     // process the result of the query
     $rows = array();
     require_once 'CRM/Event/BAO/Participant.php';
     require_once 'CRM/Contact/BAO/Contact/Utils.php';
     //CRM-4418 check for view/edit/delete
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('edit contributions')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviContribute')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $qfKey = $this->_key;
     $componentId = $componentContext = null;
     if ($this->_context != 'contribute') {
         $qfKey = CRM_Utils_Request::retrieve('key', 'String', CRM_Core_DAO::$_nullObject);
         $componentId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject);
         $componentAction = CRM_Utils_Request::retrieve('action', 'String', CRM_Core_DAO::$_nullObject);
         $componentContext = CRM_Utils_Request::retrieve('compContext', 'String', CRM_Core_DAO::$_nullObject);
         if (!$componentContext && $this->_compContext) {
             $componentContext = $this->_compContext;
             $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, null, false, 'REQUEST');
         }
     }
     // get all contribution status
     $contributionStatuses = CRM_Core_OptionGroup::values('contribution_status', false, false, false, null, 'name', false);
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach (self::$_properties as $property) {
             if (property_exists($result, $property)) {
                 $row[$property] = $result->{$property};
             }
         }
         // add contribution status name
         $row['contribution_status_name'] = CRM_Utils_Array::value($row['contribution_status_id'], $contributionStatuses);
         if ($result->is_pay_later && CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
             $row['contribution_status'] .= ' (Pay Later)';
         } else {
             if (CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
                 $row['contribution_status'] .= ' (Incomplete Transaction)';
             }
         }
         if ($row['is_test']) {
             $row['contribution_type'] = $row['contribution_type'] . ' (test)';
         }
         $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contribution_id;
         $actions = array('id' => $result->contribution_id, 'cid' => $result->contact_id, 'cxt' => $this->_context);
         $row['action'] = CRM_Core_Action::formLink(self::links($componentId, $componentAction, $qfKey, $componentContext), $mask, $actions);
         $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, false, $result->contact_id);
         if (CRM_Utils_Array::value('amount_level', $row)) {
             CRM_Event_BAO_Participant::fixEventLevel($row['amount_level']);
         }
         $rows[] = $row;
     }
     return $rows;
 }
Exemple #21
0
 /**
  * Returns all the rows in the given offset and rowCount.
  *
  * @param string $action
  *   The action being performed.
  * @param int $offset
  *   The row number to start from.
  * @param int $rowCount
  *   The number of rows to return.
  * @param string $sort
  *   The sql string that describes the sort order.
  * @param string $output
  *   What should the result set include (web/email/csv).
  *
  * @return array
  *   rows in the given offset and rowCount
  */
 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_eventClause);
     // process the result of the query
     $rows = array();
     //lets handle view, edit and delete separately. CRM-4418
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('edit event participants')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviEvent')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $sep = CRM_Core_DAO::VALUE_SEPARATOR;
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach (self::$_properties as $property) {
             if (isset($result->{$property})) {
                 $row[$property] = $result->{$property};
             }
         }
         //carry campaign on selectors.
         $row['campaign'] = CRM_Utils_Array::value($result->participant_campaign_id, $allCampaigns);
         $row['campaign_id'] = $result->participant_campaign_id;
         // gross hack to show extra information for pending status
         $statusClass = NULL;
         if (isset($row['participant_status_id']) && ($statusId = array_search($row['participant_status_id'], $statusTypes))) {
             $statusClass = $statusClasses[$statusId];
         }
         $row['showConfirmUrl'] = $statusClass == 'Pending' ? TRUE : FALSE;
         if (!empty($row['participant_is_test'])) {
             $row['participant_status'] .= ' (' . ts('test') . ')';
         }
         $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
         $links = self::links($this->_key, $this->_context, $this->_compContext);
         if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Payment'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Payment'));
         }
         if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Refund'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Refund'));
         }
         $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->participant_id, 'cid' => $result->contact_id, 'cxt' => $this->_context), ts('more'), FALSE, 'participant.selector.row', 'Participant', $result->participant_id);
         $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id);
         $row['paid'] = CRM_Event_BAO_Event::isMonetary($row['event_id']);
         if (!empty($row['participant_fee_level'])) {
             CRM_Event_BAO_Participant::fixEventLevel($row['participant_fee_level']);
         }
         if (CRM_Event_BAO_Event::usesPriceSet($row['event_id'])) {
             // add line item details if applicable
             $lineItems[$row['participant_id']] = CRM_Price_BAO_LineItem::getLineItems($row['participant_id']);
         }
         if (!empty($row['participant_role_id'])) {
             $viewRoles = array();
             foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
                 $viewRoles[] = $participantRoles[$v];
             }
             $row['participant_role_id'] = implode(', ', $viewRoles);
         }
         $rows[] = $row;
     }
     CRM_Core_Selector_Controller::$_template->assign_by_ref('lineItems', $lineItems);
     return $rows;
 }
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     //get the button.
     $buttonName = $this->controller->getButtonName();
     $participantId = $this->_participantId;
     if ($buttonName == '_qf_ParticipantConfirm_next') {
         //lets get contact id in session.
         $session = CRM_Core_Session::singleton();
         $session->set('userID', $this->_csContactID);
         $this->postProcessHook();
         //check user registration status is from pending class
         $url = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$this->_eventId}&participantId={$participantId}");
         CRM_Utils_System::redirect($url);
     } elseif ($buttonName == '_qf_ParticipantConfirm_submit') {
         //need to registration status to 'cancelled'.
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
         $participantIds = array_merge(array($participantId), $additionalParticipantIds);
         $results = CRM_Event_BAO_Participant::transitionParticipants($participantIds, $cancelledId, NULL, TRUE);
         if (count($participantIds) > 1) {
             $statusMessage = ts("%1 Event registration(s) have been cancelled.", array(1 => count($participantIds)));
         } else {
             $statusMessage = ts("Your event registration has been cancelled.");
         }
         if (!empty($results['mailedParticipants'])) {
             foreach ($results['mailedParticipants'] as $key => $displayName) {
                 $statusMessage .= "<br />" . ts("Email has been sent to : %1", array(1 => $displayName));
             }
         }
         $this->postProcessHook();
         CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}&noFullMsg=1", FALSE, NULL, FALSE, TRUE));
     }
 }
 /**
  * Cancel this participant and finish, send cancellation email. At this point no
  * auto-cancellation of payment is handled, so payment needs to be manually cancelled
  *
  * return @void
  */
 public function cancelParticipant($params)
 {
     //set participant record status to Cancelled, refund payment if possible
     // send email to participant and admin, and log Activity
     $value = array();
     $value['id'] = $this->_participant_id;
     $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
     $value['status_id'] = $cancelledId;
     CRM_Event_BAO_Participant::create($value);
     $domainValues = array();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
     foreach ($tokens['domain'] as $token) {
         $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
     }
     $participantRoles = array();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $participantDetails = array();
     $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $participantDetails[$dao->id] = array('id' => $dao->id, 'role' => $participantRoles[$dao->role_id], 'is_test' => $dao->is_test, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'fee_amount' => $dao->fee_amount, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id);
     }
     $eventDetails = array();
     $eventParams = array('id' => $this->_event_id);
     CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
     //get default participant role.
     $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
     //get the location info
     $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
     $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
     //get contact details
     $contactIds[$this->_contact_id] = $this->_contact_id;
     list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
     foreach ($currentContactDetails as $contactId => $contactValues) {
         $contactDetails[$this->_contact_id] = $contactValues;
     }
     //send a 'cancelled' email to user, and cc the event's cc_confirm email
     $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_participant_id, $participantDetails[$this->_participant_id], $eventDetails[$this->_event_id], $contactDetails[$this->_contact_id], $domainValues, "Cancelled", "");
     $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
     $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
     CRM_Utils_System::redirect($url);
 }
 /**
  * @param array $params
  * @param int $participantId
  * @param int $contributionId
  * @param $feeBlock
  * @param array $lineItems
  * @param $paidAmount
  * @param int $priceSetId
  */
 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems);
     // get the submitted
     foreach ($feeBlock as $id => $values) {
         CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
         $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
     }
     if (!empty($submittedLineItems)) {
         $insertLines = $submittedLineItems;
         $submittedFieldValueIds = array_keys($submittedLineItems);
         $updateLines = array();
         foreach ($previousLineItems as $id => $previousLineItem) {
             // check through the submitted items if the previousItem exists,
             // if found in submitted items, do not use it for new item creations
             if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
                 // if submitted line items are existing don't fire INSERT query
                 unset($insertLines[$previousLineItem['price_field_value_id']]);
                 // for updating the line items i.e. use-case - once deselect-option selecting again
                 if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] || $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1 || $previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty']) {
                     $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
                     $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
                 }
             }
         }
         $submittedFields = implode(', ', $submittedFieldId);
         $submittedFieldValues = implode(', ', $submittedFieldValueIds);
     }
     if (!empty($submittedFields) && !empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n    li.line_total = 0.00,\n    li.tax_amount = NULL\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n       (price_field_value_id NOT IN ({$submittedFieldValues}))\n";
         CRM_Core_DAO::executeQuery($updateLineItem);
         // gathering necessary info to record negative (deselected) financial_item
         $updateFinancialItem = "\n  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount\n    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id\n";
         $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
         $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $updateFinancialItemInfoValues = array();
         $financialItemsArray = array();
         while ($updateFinancialItemInfoDAO->fetch()) {
             $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
             $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
             // the below params are not needed
             unset($updateFinancialItemInfoValues['id']);
             unset($updateFinancialItemInfoValues['created_date']);
             // if not submitted and difference is not 0 make it negative
             if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
                 // INSERT negative financial_items
                 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
                 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
                     $updateFinancialItemInfoValues['tax']['amount'] = -$previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateFinancialItemInfoValues['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
                     }
                 }
                 // INSERT negative financial_items for tax amount
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
                 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
                 // INSERT financial_items for tax amount
                 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] && isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])) {
                     $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
                     }
                 }
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             }
         }
     } elseif (empty($submittedFields) && empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\n        INNER JOIN civicrm_financial_item fi\n        ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\n        SET li.qty = 0,\n        li.line_total = 0.00,\n        li.tax_amount = NULL\n        WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
         CRM_Core_DAO::executeQuery($updateLineItem);
     }
     $amountLevel = array();
     $totalParticipant = $participantCount = 0;
     if (!empty($updateLines)) {
         foreach ($updateLines as $valueId => $vals) {
             $taxAmount = "NULL";
             if (isset($vals['tax_amount'])) {
                 $taxAmount = $vals['tax_amount'];
             }
             $amountLevel[] = $vals['label'] . ' - ' . (double) $vals['qty'];
             if (isset($vals['participant_count'])) {
                 $participantCount = $vals['participant_count'];
                 $totalParticipant += $vals['participant_count'];
             }
             $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n    li.line_total = {$vals['line_total']},\n    li.tax_amount = {$taxAmount},\n    li.unit_price = {$vals['unit_price']},\n    li.participant_count = {$participantCount},\n    li.label = %1\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n      (price_field_value_id = {$valueId})\n";
             CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
         }
     }
     // insert new 'adjusted amount' transaction entry and update contribution entry.
     // ensure entity_financial_trxn table has a linking of it.
     // insert new line items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineParams['contribution_id'] = $contributionId;
             $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
         }
     }
     // the recordAdjustedAmt code would execute over here
     $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
     if (count($ids) > 1) {
         $total = 0;
         foreach ($ids as $val) {
             $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
         }
         $updatedAmount = $total;
     } else {
         $updatedAmount = $params['amount'];
     }
     if (strlen($params['tax_amount']) != 0) {
         $taxAmount = $params['tax_amount'];
     } else {
         $taxAmount = "NULL";
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $updateAmountLevel = NULL;
     if (!empty($amountLevel)) {
         $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     }
     $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
     $trxnId = array();
     if ($trxn) {
         $trxnId['id'] = $trxn->id;
         foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
             CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             if (!empty($updateFinancialItemInfoValues['tax'])) {
                 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
                 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
                 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
                     $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
                 }
                 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             }
         }
     }
     $fetchCon = array('id' => $contributionId);
     $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     // insert financial items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
             // insert financial items
             // ensure entity_financial_trxn table has a linking of it.
             $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
             if (isset($lineObj->tax_amount)) {
                 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
             }
         }
     }
     // update participant fee_amount column
     $partUpdateFeeAmt['id'] = $participantId;
     $getUpdatedLineItems = "SELECT *\nFROM civicrm_line_item\nWHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
     $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
     while ($getUpdatedLineItemsDAO->fetch()) {
         $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (double) $getUpdatedLineItemsDAO->qty;
     }
     $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
     $partUpdateFeeAmt['fee_amount'] = $params['amount'];
     self::add($partUpdateFeeAmt);
     //activity creation
     self::addActivityForSelection($participantId, 'Change Registration');
 }
Exemple #26
0
    /**
     * Function to get participant count
     *
     * @param  boolean $considerStatus consider status for participant count.
     * @param  boolean $status         consider counted participant.
     * @param  boolean $considerRole   consider role for participant count.
     * @param  boolean $role           consider counted( is filter role) participant.
     * @param  array   $eventIds       consider participants from given events.
     * @param  boolean $countWithStatus  retrieve participant count w/ each participant status.
     *
     * @access public
     * @return array array with count of participants for each event based on status/role
     */
    function getParticipantCount($considerStatus = true, $status = true, $considerRole = true, $role = true, $eventIds = array(), $countWithStatus = false)
    {
        // consider both role and status for counted participants, CRM-4924.
        require_once 'CRM/Event/PseudoConstant.php';
        require_once 'CRM/Event/BAO/Participant.php';
        $operator = " AND ";
        // not counted participant.
        if ($considerStatus && $considerRole && !$status && !$role) {
            $operator = " OR ";
        }
        $clause = array();
        if ($considerStatus) {
            $statusTypes = CRM_Event_PseudoConstant::participantStatus(null, 'is_counted = 1');
            $statusClause = 'NOT IN';
            if ($status) {
                $statusClause = 'IN';
            }
            $status = implode(',', array_keys($statusTypes));
            if (empty($status)) {
                $status = 0;
            }
            $clause[] = "civicrm_participant.status_id {$statusClause} ( {$status} ) ";
        }
        if ($considerRole) {
            $roleTypes = CRM_Event_PseudoConstant::participantRole(null, 'filter = 1');
            $roleClause = 'NOT IN';
            if ($role) {
                $roleClause = 'IN';
            }
            $roles = implode(',', array_keys($roleTypes));
            if (empty($roles)) {
                $roles = 0;
            }
            $clause[] = "civicrm_participant.role_id {$roleClause} ( {$roles} )";
        }
        $sqlClause = '';
        if (!empty($clause)) {
            $sqlClause = ' AND ( ' . implode($operator, $clause) . ' )';
        }
        $eventLimit = 10;
        if (is_array($eventIds) && !empty($eventIds)) {
            $eventLimit = null;
            $sqlClause .= ' AND civicrm_event.id IN (' . implode(',', $eventIds) . ')';
        }
        $select = '
    SELECT   civicrm_event.id as id, 
             civicrm_participant.id as participantId';
        $from = '
      FROM   civicrm_event 
INNER JOIN   civicrm_participant ON ( civicrm_event.id = civicrm_participant.event_id )
INNER JOIN   civicrm_contact contact ON ( contact.id = civicrm_participant.contact_id AND contact.is_deleted = 0 )';
        if ($countWithStatus) {
            $select .= ', status_id as statusId, status_type.class as statusClass';
            $from .= ' 
INNER JOIN   civicrm_participant_status_type status_type ON ( civicrm_participant.status_id = status_type.id )';
        }
        $where = "\n     WHERE   ( civicrm_participant.is_test = 0 OR civicrm_participant.is_test IS NULL ) \n       AND   civicrm_event.is_active = 1\n             {$sqlClause}";
        $orderBy = 'Order By civicrm_event.end_date DESC';
        $participantIds = $participantCount = array();
        $query = "{$select} {$from} {$where} {$orderBy}";
        $event = CRM_Core_DAO::executeQuery($query);
        while ($event->fetch()) {
            //we are interested in first 10 events only.
            if ($eventLimit && count(array_keys($participantIds)) > $eventLimit) {
                break;
            }
            if ($countWithStatus) {
                $participantIds[$event->id][$event->statusId]['pIds'][$event->participantId] = $event->participantId;
                $participantIds[$event->id][$event->statusId]['statusClass'] = $event->statusClass;
            } else {
                $participantIds[$event->id][$event->participantId] = $event->participantId;
            }
        }
        //poped last 11th events participants.
        if ($eventLimit && count(array_keys($participantIds)) > $eventLimit) {
            array_pop($participantIds);
        }
        //pickup event seats
        foreach ($participantIds as $eventId => $pInfo) {
            $pIds = $pInfo;
            if ($countWithStatus) {
                foreach ($pInfo as $statusId => $values) {
                    $participantCount[$eventId][$statusId]['count'] = CRM_Event_BAO_Participant::totalEventSeats($values['pIds']);
                    $participantCount[$eventId][$statusId]['class'] = $values['statusClass'];
                }
            } else {
                $participantCount[$eventId] = CRM_Event_BAO_Participant::totalEventSeats($pIds);
            }
        }
        return $participantCount;
    }
 /**
  * Alter display of rows.
  *
  * Iterate through the rows retrieved via SQL and make changes for display purposes,
  * such as rendering contacts as links.
  *
  * @param array $rows
  *   Rows generated by SQL, with an array for each row.
  */
 public function alterDisplay(&$rows)
 {
     $entryFound = FALSE;
     $eventType = CRM_Core_OptionGroup::values('event_type');
     $financialTypes = CRM_Contribute_PseudoConstant::financialType();
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
     foreach ($rows as $rowNum => $row) {
         // make count columns point to detail report
         // convert display name to links
         if (array_key_exists('civicrm_participant_event_id', $row)) {
             $eventId = $row['civicrm_participant_event_id'];
             if ($eventId) {
                 $rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE);
                 $url = CRM_Report_Utils_Report::getNextUrl('event/income', 'reset=1&force=1&id_op=in&id_value=' . $eventId, $this->_absoluteUrl, $this->_id, $this->_drilldownReport);
                 $rows[$rowNum]['civicrm_participant_event_id_link'] = $url;
                 $rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event");
             }
             $entryFound = TRUE;
         }
         // handle event type id
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType);
         // handle participant status id
         if (array_key_exists('civicrm_participant_status_id', $row)) {
             $statusId = $row['civicrm_participant_status_id'];
             if ($statusId) {
                 $rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label');
             }
             $entryFound = TRUE;
         }
         // handle participant role id
         if (array_key_exists('civicrm_participant_role_id', $row)) {
             $roleId = $row['civicrm_participant_role_id'];
             if ($roleId) {
                 $roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId);
                 $roleId = array();
                 foreach ($roles as $role) {
                     $roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
                 }
                 $rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId);
             }
             $entryFound = TRUE;
         }
         // Handel value seperator in Fee Level
         if (array_key_exists('civicrm_participant_participant_fee_level', $row)) {
             $feeLevel = $row['civicrm_participant_participant_fee_level'];
             if ($feeLevel) {
                 CRM_Event_BAO_Participant::fixEventLevel($feeLevel);
                 $rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel;
             }
             $entryFound = TRUE;
         }
         // Convert display name to link
         $displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row);
         $cid = CRM_Utils_Array::value('civicrm_contact_id', $row);
         $id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row);
         if ($displayName && $cid && $id) {
             $url = CRM_Report_Utils_Report::getNextUrl('contact/detail', "reset=1&force=1&id_op=eq&id_value={$cid}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport);
             $viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant", "reset=1&id={$id}&cid={$cid}&action=view&context=participant");
             $contactTitle = ts('View Contact Details');
             $participantTitle = ts('View Participant Record');
             $rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='{$contactTitle}' href={$url}>{$displayName}</a>";
             if ($this->_outputMode !== 'csv') {
                 $rows[$rowNum]['civicrm_contact_sort_name_linked'] .= "<span style='float: right;'><a title='{$participantTitle}' href={$viewUrl}>" . ts('View') . "</a></span>";
             }
             $entryFound = TRUE;
         }
         // Handle country id
         if (array_key_exists('civicrm_address_country_id', $row)) {
             $countryId = $row['civicrm_address_country_id'];
             if ($countryId) {
                 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE);
             }
             $entryFound = TRUE;
         }
         // Handle state/province id
         if (array_key_exists('civicrm_address_state_province_id', $row)) {
             $provinceId = $row['civicrm_address_state_province_id'];
             if ($provinceId) {
                 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE);
             }
             $entryFound = TRUE;
         }
         // Handle employer id
         if (array_key_exists('civicrm_contact_employer_id', $row)) {
             $employerId = $row['civicrm_contact_employer_id'];
             if ($employerId) {
                 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
                 $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl);
                 $rows[$rowNum]['civicrm_contact_employer_id_link'] = $url;
                 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.');
             }
         }
         // Convert campaign_id to campaign title
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns);
         // handle contribution status
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus);
         // handle payment instrument
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments);
         // handle financial type
         $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes);
         $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound;
         // display birthday in the configured custom format
         if (array_key_exists('civicrm_contact_birth_date', $row)) {
             $birthDate = $row['civicrm_contact_birth_date'];
             if ($birthDate) {
                 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
             }
             $entryFound = TRUE;
         }
         // skip looking further in rows, if first row itself doesn't
         // have the column we need
         if (!$entryFound) {
             break;
         }
     }
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Participant');
             $value['id'] = $key;
             if (CRM_Utils_Array::value('participant_register_date', $value)) {
                 $value['register_date'] = CRM_Utils_Date::processDate($value['participant_register_date'], $value['participant_register_date_time']);
             }
             if (CRM_Utils_Array::value('participant_role', $value)) {
                 $participantRoles = CRM_Event_PseudoConstant::participantRole();
                 if (is_array($value['participant_role'])) {
                     $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
                 } else {
                     $value['role_id'] = $value['participant_role'];
                 }
             }
             //need to send mail when status change
             $statusChange = FALSE;
             if (CRM_Utils_Array::value('participant_status', $value)) {
                 $value['status_id'] = $value['participant_status'];
                 $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
                 if (!$fromStatusId) {
                     $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
                 }
                 if ($fromStatusId != $value['status_id']) {
                     $statusChange = TRUE;
                 }
             }
             if (CRM_Utils_Array::value('participant_source', $value)) {
                 $value['source'] = $value['participant_source'];
             }
             unset($value['participant_register_date']);
             unset($value['participant_status']);
             unset($value['participant_source']);
             CRM_Event_BAO_Participant::create($value);
             //need to trigger mails when we change status
             if ($statusChange) {
                 CRM_Event_BAO_Participant::transitionParticipants(array($key), $value['status_id'], $fromStatusId);
                 //update related contribution status, CRM-4395
                 self::updatePendingOnlineContribution($key, $value['status_id']);
             }
         }
         CRM_Core_Session::setStatus(ts('The updates have been saved.'));
     } else {
         CRM_Core_Session::setStatus(ts('No updates have been saved.'));
     }
 }
Exemple #29
0
 /**
  * Process Registration of free event.
  *
  * @param array $params
  *   Form values.
  * @param int $contactID
  */
 public function processRegistration($params, $contactID = NULL)
 {
     $session = CRM_Core_Session::singleton();
     $this->_participantInfo = array();
     // CRM-4320, lets build array of cancelled additional participant ids
     // those are drop or skip by primary at the time of confirmation.
     // get all in and then unset those are confirmed.
     $cancelledIds = $this->_additionalParticipantIds;
     $participantCount = array();
     foreach ($params as $participantNum => $record) {
         if ($record == 'skip') {
             $participantCount[$participantNum] = 'skip';
         } elseif ($participantNum) {
             $participantCount[$participantNum] = 'participant';
         }
     }
     $registerByID = NULL;
     foreach ($params as $key => $value) {
         if ($value != 'skip') {
             $fields = NULL;
             // setting register by Id and unset contactId.
             if (empty($value['is_primary'])) {
                 $contactID = NULL;
                 $registerByID = $this->get('registerByID');
                 if ($registerByID) {
                     $value['registered_by_id'] = $registerByID;
                 }
                 // get an email if one exists for the participant
                 $participantEmail = '';
                 foreach (array_keys($value) as $valueName) {
                     if (substr($valueName, 0, 6) == 'email-') {
                         $participantEmail = $value[$valueName];
                     }
                 }
                 if ($participantEmail) {
                     $this->_participantInfo[] = $participantEmail;
                 } else {
                     $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
                 }
             } elseif (!empty($value['contact_id'])) {
                 $contactID = $value['contact_id'];
             } else {
                 $contactID = $this->getContactID();
             }
             CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
             //for free event or additional participant, dont create billing email address.
             if (empty($value['is_primary']) || !$this->_values['event']['is_monetary']) {
                 unset($value["email-{$this->_bltID}"]);
             }
             $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
             // lets store the contactID in the session
             // we dont store in userID in case the user is doing multiple
             // transactions etc
             // for things like tell a friend
             if (!$this->getContactID() && !empty($value['is_primary'])) {
                 $session->set('transaction.userID', $contactID);
             }
             //lets get the status if require approval or waiting.
             $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($this->_allowWaitlist && !$this->_allowConfirmation) {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
             } elseif ($this->_requireApproval && !$this->_allowConfirmation) {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
             }
             $this->set('value', $value);
             $this->confirmPostProcess($contactID, NULL, NULL);
             //lets get additional participant id to cancel.
             if ($this->_allowConfirmation && is_array($cancelledIds)) {
                 $additonalId = CRM_Utils_Array::value('participant_id', $value);
                 if ($additonalId && ($key = array_search($additonalId, $cancelledIds))) {
                     unset($cancelledIds[$key]);
                 }
             }
         }
     }
     // update status and send mail to cancelled additional participants, CRM-4320
     if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
     }
     //set information about additional participants if exists
     if (count($this->_participantInfo)) {
         $this->set('participantInfo', $this->_participantInfo);
     }
     //send mail Confirmation/Receipt
     if ($this->_contributeMode != 'checkout' || $this->_contributeMode != 'notify') {
         $isTest = FALSE;
         if ($this->_action & CRM_Core_Action::PREVIEW) {
             $isTest = TRUE;
         }
         //handle if no additional participant.
         if (!$registerByID) {
             $registerByID = $this->get('registerByID');
         }
         $primaryContactId = $this->get('primaryContactId');
         //build an array of custom profile and assigning it to template.
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
         //lets carry all participant params w/ values.
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = NULL;
             if ($participantID == $registerByID) {
                 $participantNum = 0;
             } else {
                 if ($participantNum = array_search('participant', $participantCount)) {
                     unset($participantCount[$participantNum]);
                 }
             }
             if ($participantNum === NULL) {
                 break;
             }
             //carry the participant submitted values.
             $this->_values['params'][$participantID] = $params[$participantNum];
         }
         //lets send  mails to all with meanigful text, CRM-4320.
         $this->assign('isOnWaitlist', $this->_allowWaitlist);
         $this->assign('isRequireApproval', $this->_requireApproval);
         foreach ($additionalIDs as $participantID => $contactId) {
             if ($participantID == $registerByID) {
                 //set as Primary Participant
                 $this->assign('isPrimary', 1);
                 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
                 if (count($customProfile)) {
                     $this->assign('customProfile', $customProfile);
                     $this->set('customProfile', $customProfile);
                 }
             } else {
                 $this->assign('isPrimary', 0);
                 $this->assign('customProfile', NULL);
             }
             //send Confirmation mail to Primary & additional Participants if exists
             CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
         }
     }
 }
 /**
  * Get list of payments displayed by Contribute_Page_PaymentInfo.
  *
  * @param int $id
  * @param $component
  * @param bool $getTrxnInfo
  * @param bool $usingLineTotal
  *
  * @return mixed
  */
 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE)
 {
     if ($component == 'event') {
         $entity = 'participant';
         $entityTable = 'civicrm_participant';
         $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
         if (!$contributionId) {
             if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
                 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
                 $id = $primaryParticipantId;
             }
             if (!$contributionId) {
                 return;
             }
         }
     }
     $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
     $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
     $isBalance = NULL;
     if ($baseTrxnId) {
         $isBalance = TRUE;
     } else {
         $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
         $baseTrxnId = $baseTrxnId['financialTrxnId'];
         $isBalance = FALSE;
     }
     if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
         // for additional participants
         if ($entityTable == 'civicrm_participant') {
             $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
             $total = 0;
             foreach ($ids as $val) {
                 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
             }
         } else {
             $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
         }
     } else {
         $baseTrxnId = $total['trxn_id'];
         $total = $total['total_amount'];
     }
     $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
     $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
     $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
     $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
     $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
     if ($paymentBalance == 0 && $contributionIsPayLater) {
         $paymentBalance = $total;
     }
     $info['total'] = $total;
     $info['paid'] = $total - $paymentBalance;
     $info['balance'] = $paymentBalance;
     $info['id'] = $id;
     $info['component'] = $component;
     $info['payLater'] = $contributionIsPayLater;
     $rows = array();
     if ($getTrxnInfo && $baseTrxnId) {
         // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
         $sql = "\nSELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number\nFROM civicrm_contribution con\n  LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')\n  INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}\nWHERE con.id = {$contributionId}\n";
         // conditioned WHERE clause
         if ($isBalance) {
             // if balance trxn exists don't include details of it in transaction info
             $sql .= " AND ft.id != {$baseTrxnId} ";
         }
         $resultDAO = CRM_Core_DAO::executeQuery($sql);
         $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
         $financialTypes = CRM_Contribute_PseudoConstant::financialType();
         while ($resultDAO->fetch()) {
             $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
             $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
             $val = array('total_amount' => $resultDAO->total_amount, 'financial_type' => $financialTypes[$resultDAO->financial_type_id], 'payment_instrument' => $paidByLabel, 'receive_date' => $resultDAO->trxn_date, 'trxn_id' => $resultDAO->trxn_id, 'status' => $statuses[$resultDAO->status_id]);
             if ($paidByName == 'Check') {
                 $val['check_number'] = $resultDAO->check_number;
             }
             $rows[] = $val;
         }
         $info['transaction'] = $rows;
     }
     return $info;
 }